integrado modelo de identificacao de ruas no software

This commit is contained in:
Diego Freitas 2024-02-19 10:11:53 -03:00
parent 0682f8d250
commit 46373953d5
111 changed files with 32694 additions and 803 deletions

Binary file not shown.

File diff suppressed because one or more lines are too long

View File

@ -55,6 +55,15 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="AForge, Version=2.2.5.0, Culture=neutral, PublicKeyToken=c1db6ff4eaa06aeb, processorArchitecture=MSIL">
<HintPath>..\packages\AForge.2.2.5\lib\AForge.dll</HintPath>
</Reference>
<Reference Include="AForge.Video, Version=2.2.5.0, Culture=neutral, PublicKeyToken=cbfb6e07d173c401, processorArchitecture=MSIL">
<HintPath>..\packages\AForge.Video.2.2.5\lib\AForge.Video.dll</HintPath>
</Reference>
<Reference Include="AForge.Video.DirectShow, Version=2.2.5.0, Culture=neutral, PublicKeyToken=61ea4348d43881b7, processorArchitecture=MSIL">
<HintPath>..\packages\AForge.Video.DirectShow.2.2.5\lib\AForge.Video.DirectShow.dll</HintPath>
</Reference>
<Reference Include="CefSharp, Version=119.4.30.0, Culture=neutral, PublicKeyToken=40c4b6fc221f4138, processorArchitecture=MSIL">
<HintPath>..\packages\CefSharp.Common.119.4.30\lib\net462\CefSharp.dll</HintPath>
</Reference>
@ -204,6 +213,18 @@
<Compile Include="Forms\frmPinout.Designer.cs">
<DependentUpon>frmPinout.cs</DependentUpon>
</Compile>
<Compile Include="Forms\IHM\frmIHM.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Forms\IHM\frmIHM.Designer.cs">
<DependentUpon>frmIHM.cs</DependentUpon>
</Compile>
<Compile Include="Forms\Movimentacao\frmMovCamera.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Forms\Movimentacao\frmMovCamera.Designer.cs">
<DependentUpon>frmMovCamera.cs</DependentUpon>
</Compile>
<Compile Include="Forms\Movimentacao\frmMovDiagnosticos.cs">
<SubType>Form</SubType>
</Compile>
@ -240,6 +261,12 @@
<Compile Include="Forms\Operacoes\frmOperacaoSeguidorLinha.Designer.cs">
<DependentUpon>frmOperacaoSeguidorLinha.cs</DependentUpon>
</Compile>
<Compile Include="Forms\Operacoes\frmParametrizacaoOperacao.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Forms\Operacoes\frmParametrizacaoOperacao.Designer.cs">
<DependentUpon>frmParametrizacaoOperacao.cs</DependentUpon>
</Compile>
<Compile Include="Forms\Sensoriamento\frmSenCamera.cs">
<SubType>Form</SubType>
</Compile>
@ -254,6 +281,7 @@
</Compile>
<Compile Include="Models\AlarmeModel.cs" />
<Compile Include="Models\CameraModel.cs" />
<Compile Include="Models\CameraSoloModel.cs" />
<Compile Include="Models\GPSModel.cs" />
<Compile Include="Models\MapasModel.cs" />
<Compile Include="Models\Modules\AtuadorModel.cs" />
@ -284,6 +312,39 @@
<Compile Include="Services\PythonService.cs" />
<Compile Include="Services\SerialService.cs" />
<Compile Include="Services\SocketService.cs" />
<Content Include="Python\Models\deeplabv3plus\backbone\hrnetv2.py">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Python\Models\deeplabv3plus\backbone\mobilenetv2.py">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Python\Models\deeplabv3plus\backbone\resnet.py">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Python\Models\deeplabv3plus\backbone\xception.py">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Python\Models\deeplabv3plus\backbone\__init__.py">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Python\Models\deeplabv3plus\modeling.py">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Python\Models\deeplabv3plus\utils.py">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Python\Models\deeplabv3plus\_deeplab.py">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Python\Models\deeplabv3plus\__init__.py">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Python\Scripts\street-detector.py">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Python\Scripts\weed-detector.py">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<EmbeddedResource Include="Forms\Atuador\frmAtuConfig.resx">
<DependentUpon>frmAtuConfig.cs</DependentUpon>
</EmbeddedResource>
@ -308,6 +369,12 @@
<EmbeddedResource Include="Forms\frmPinout.resx">
<DependentUpon>frmPinout.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\IHM\frmIHM.resx">
<DependentUpon>frmIHM.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\Movimentacao\frmMovCamera.resx">
<DependentUpon>frmMovCamera.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\Movimentacao\frmMovConfig.resx">
<DependentUpon>frmMovConfig.cs</DependentUpon>
</EmbeddedResource>
@ -329,6 +396,9 @@
<EmbeddedResource Include="Forms\Operacoes\frmOperacaoSeguidorLinha.resx">
<DependentUpon>frmOperacaoSeguidorLinha.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\Operacoes\frmParametrizacaoOperacao.resx">
<DependentUpon>frmParametrizacaoOperacao.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\Sensoriamento\frmSenCamera.resx">
<DependentUpon>frmSenCamera.cs</DependentUpon>
</EmbeddedResource>
@ -382,6 +452,33 @@
<Content Include="Python\Models\yolo\crop_weed_detection.weights">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<None Include="Python\Models\deeplabv3plus\backbone\__pycache__\hrnetv2.cpython-311.pyc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Python\Models\deeplabv3plus\backbone\__pycache__\mobilenetv2.cpython-311.pyc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Python\Models\deeplabv3plus\backbone\__pycache__\resnet.cpython-311.pyc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Python\Models\deeplabv3plus\backbone\__pycache__\xception.cpython-311.pyc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Python\Models\deeplabv3plus\backbone\__pycache__\__init__.cpython-311.pyc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Python\Models\deeplabv3plus\__pycache__\modeling.cpython-311.pyc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Python\Models\deeplabv3plus\__pycache__\utils.cpython-311.pyc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Python\Models\deeplabv3plus\__pycache__\_deeplab.cpython-311.pyc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Python\Models\deeplabv3plus\__pycache__\__init__.cpython-311.pyc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />

View File

@ -86,7 +86,7 @@ namespace AgroBase.Forms
{
cameraService.ArquivoLeitura = ArquivoLeitura;
cameraService.IniciarCamera(
PythonService.ScriptGreenDetector,
PythonService.ScriptWeedDetector,
new string[] { MaxLeituras.ToString(), VideoPorta, VideoUrl, ArquivoLeitura, "1", SocketPorta },
VideoPorta,
VideoUrl,

View File

@ -0,0 +1,192 @@
namespace AgroBase.Forms.IHM
{
partial class frmIHM
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmIHM));
this.picRobo = new System.Windows.Forms.PictureBox();
this.lblD_Mov = new System.Windows.Forms.Label();
this.lblD_Dir = new System.Windows.Forms.Label();
this.lblD_Atu = new System.Windows.Forms.Label();
this.lblD_Sen = new System.Windows.Forms.Label();
this.lblD_Gps = new System.Windows.Forms.Label();
this.btnConfigurar = new System.Windows.Forms.Button();
this.btnIniciar = new System.Windows.Forms.Button();
this.cmbOperacao = new System.Windows.Forms.ComboBox();
this.lblOperacao = new System.Windows.Forms.Label();
this.lblOperacaoStatus = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.picRobo)).BeginInit();
this.SuspendLayout();
//
// picRobo
//
this.picRobo.Image = ((System.Drawing.Image)(resources.GetObject("picRobo.Image")));
this.picRobo.Location = new System.Drawing.Point(111, 12);
this.picRobo.Name = "picRobo";
this.picRobo.Size = new System.Drawing.Size(370, 673);
this.picRobo.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.picRobo.TabIndex = 1;
this.picRobo.TabStop = false;
//
// lblD_Mov
//
this.lblD_Mov.AutoSize = true;
this.lblD_Mov.Location = new System.Drawing.Point(457, 40);
this.lblD_Mov.Name = "lblD_Mov";
this.lblD_Mov.Size = new System.Drawing.Size(133, 24);
this.lblD_Mov.TabIndex = 2;
this.lblD_Mov.Text = "Movimentação";
//
// lblD_Dir
//
this.lblD_Dir.AutoSize = true;
this.lblD_Dir.Location = new System.Drawing.Point(61, 422);
this.lblD_Dir.Name = "lblD_Dir";
this.lblD_Dir.Size = new System.Drawing.Size(94, 24);
this.lblD_Dir.TabIndex = 3;
this.lblD_Dir.Text = "Direcional";
//
// lblD_Atu
//
this.lblD_Atu.AutoSize = true;
this.lblD_Atu.Location = new System.Drawing.Point(435, 645);
this.lblD_Atu.Name = "lblD_Atu";
this.lblD_Atu.Size = new System.Drawing.Size(76, 24);
this.lblD_Atu.TabIndex = 4;
this.lblD_Atu.Text = "Atuador";
//
// lblD_Sen
//
this.lblD_Sen.AutoSize = true;
this.lblD_Sen.Location = new System.Drawing.Point(311, 519);
this.lblD_Sen.Name = "lblD_Sen";
this.lblD_Sen.Size = new System.Drawing.Size(137, 24);
this.lblD_Sen.TabIndex = 5;
this.lblD_Sen.Text = "Sensoriamento";
//
// lblD_Gps
//
this.lblD_Gps.AutoSize = true;
this.lblD_Gps.Location = new System.Drawing.Point(129, 193);
this.lblD_Gps.Name = "lblD_Gps";
this.lblD_Gps.Size = new System.Drawing.Size(48, 24);
this.lblD_Gps.TabIndex = 6;
this.lblD_Gps.Text = "GPS";
//
// btnConfigurar
//
this.btnConfigurar.Location = new System.Drawing.Point(775, 173);
this.btnConfigurar.Name = "btnConfigurar";
this.btnConfigurar.Size = new System.Drawing.Size(202, 64);
this.btnConfigurar.TabIndex = 8;
this.btnConfigurar.Text = "Configurar";
this.btnConfigurar.UseVisualStyleBackColor = true;
this.btnConfigurar.Click += new System.EventHandler(this.btnConfigurar_Click);
//
// btnIniciar
//
this.btnIniciar.Location = new System.Drawing.Point(775, 258);
this.btnIniciar.Name = "btnIniciar";
this.btnIniciar.Size = new System.Drawing.Size(202, 64);
this.btnIniciar.TabIndex = 9;
this.btnIniciar.Text = "Iniciar";
this.btnIniciar.UseVisualStyleBackColor = true;
this.btnIniciar.Click += new System.EventHandler(this.btnIniciar_Click);
//
// cmbOperacao
//
this.cmbOperacao.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbOperacao.FormattingEnabled = true;
this.cmbOperacao.Location = new System.Drawing.Point(775, 81);
this.cmbOperacao.Name = "cmbOperacao";
this.cmbOperacao.Size = new System.Drawing.Size(202, 32);
this.cmbOperacao.TabIndex = 10;
this.cmbOperacao.SelectedIndexChanged += new System.EventHandler(this.cmbOperacao_SelectedIndexChanged);
//
// lblOperacao
//
this.lblOperacao.AutoSize = true;
this.lblOperacao.Location = new System.Drawing.Point(771, 45);
this.lblOperacao.Name = "lblOperacao";
this.lblOperacao.Size = new System.Drawing.Size(175, 24);
this.lblOperacao.TabIndex = 11;
this.lblOperacao.Text = "Modo de Operação";
//
// lblOperacaoStatus
//
this.lblOperacaoStatus.AutoSize = true;
this.lblOperacaoStatus.Location = new System.Drawing.Point(671, 664);
this.lblOperacaoStatus.Name = "lblOperacaoStatus";
this.lblOperacaoStatus.Size = new System.Drawing.Size(287, 24);
this.lblOperacaoStatus.TabIndex = 12;
this.lblOperacaoStatus.Text = "Operação: Manual - Não iniciado";
//
// frmIHM
//
this.AutoScaleDimensions = new System.Drawing.SizeF(11F, 24F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1020, 697);
this.Controls.Add(this.lblOperacaoStatus);
this.Controls.Add(this.lblOperacao);
this.Controls.Add(this.cmbOperacao);
this.Controls.Add(this.btnIniciar);
this.Controls.Add(this.btnConfigurar);
this.Controls.Add(this.lblD_Gps);
this.Controls.Add(this.lblD_Sen);
this.Controls.Add(this.lblD_Atu);
this.Controls.Add(this.lblD_Dir);
this.Controls.Add(this.lblD_Mov);
this.Controls.Add(this.picRobo);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Margin = new System.Windows.Forms.Padding(6);
this.Name = "frmIHM";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Agrobotics Persistence";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Load += new System.EventHandler(this.frmIHM_Load);
((System.ComponentModel.ISupportInitialize)(this.picRobo)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox picRobo;
private System.Windows.Forms.Label lblD_Mov;
private System.Windows.Forms.Label lblD_Dir;
private System.Windows.Forms.Label lblD_Atu;
private System.Windows.Forms.Label lblD_Sen;
private System.Windows.Forms.Label lblD_Gps;
private System.Windows.Forms.Button btnConfigurar;
private System.Windows.Forms.Button btnIniciar;
private System.Windows.Forms.ComboBox cmbOperacao;
private System.Windows.Forms.Label lblOperacao;
private System.Windows.Forms.Label lblOperacaoStatus;
}
}

View File

@ -0,0 +1,155 @@
using AgroBase.Comum;
using AgroBase.Forms.Operacoes;
using AgroBase.Models;
using AgroBase.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static AgroBase.Models.Enuns;
namespace AgroBase.Forms.IHM
{
public partial class frmIHM : Form
{
Timer tmrDispositivos = new Timer() { Interval = 5000, Enabled = false };
public frmIHM()
{
InitializeComponent();
}
private void frmIHM_Load(object sender, EventArgs e)
{
tmrDispositivos.Tick += TmrDispositivos_Tick;
tmrDispositivos.Start();
cmbOperacao.Items.Clear();
cmbOperacao.Items.AddRange(Enum.GetNames(typeof(ModoOperacao)));
cmbOperacao.SelectedIndex = (int)Variaveis.OperacaoEmAndamento.Modo;
Variaveis.OperacaoEmAndamento = OperacaoModel.CarregarOperacaoPersonalizada(Application.StartupPath + "\\operacao" + Enum.GetName(typeof(ModoOperacao), Variaveis.OperacaoEmAndamento.Modo) + ".opr");
}
private void TmrDispositivos_Tick(object sender, EventArgs e)
{
SerialService.AtualizarDispositivos();
var Labels = this.Controls.OfType<Label>().Where(y => y.Name.Contains("lblD_")).ToList();
Labels.ForEach(lbl =>
{
lbl.ForeColor = Color.Black;
});
SerialService.DispositivosMapeados.ForEach(Modulo =>
{
Label lblDisp = Labels.Where(y => y.Name.Replace("lblD_", "") == Enum.GetName(typeof(T_Code), Modulo.Dispositivo)).FirstOrDefault();
if (lblDisp != null)
{
bool DispositivoConectado = false;
if (Modulo.Dispositivo == T_Code.Gps)
{
try
{
if (!GPSService.PortaGPS.IsOpen)
{
GPSService.IniciarRecepcaoDados();
}
DispositivoConectado = GPSService.PortaGPS.IsOpen;
}
catch
{
DispositivoConectado = false;
}
}
else
{
IDispositivosService dispositivoService = Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == Modulo.Dispositivo && x._Porta.PortName == Modulo.PortaCOM);
if (dispositivoService == null)
{
dispositivoService = DispositivosServiceFactory.CreateDispositivoService(
Modulo.Dispositivo,
"Nome: " + Enum.GetName(typeof(T_Code), Modulo.Dispositivo),
"Descrição: " + Enum.GetName(typeof(T_Code), Modulo.Dispositivo),
new SerialPort()
);
Variaveis.DispositivosConectados.Add(dispositivoService);
dispositivoService.InstanciarDispositivo(Variaveis.DispositivosConectados.Count - 1);
}
if (!dispositivoService._Porta.IsOpen)
{
dispositivoService.btnConectar_Click(new object(), new EventArgs());
}
DispositivoConectado = dispositivoService._Porta.IsOpen;
}
lblDisp.ForeColor = DispositivoConectado ? Color.Green : Color.Red;
}
});
if (SerialService.DispositivosMapeados.Count == 0)
{
Variaveis.DispositivosConectados.Where(x => x.Dados.GetStatusConexao()).ToList().ForEach(x => x.AcaoDesconectar());
}
}
private void btnConfigurar_Click(object sender, EventArgs e)
{
frmParametrizacaoOperacao frmParametrizacaoOperacao = new frmParametrizacaoOperacao();
frmParametrizacaoOperacao.ShowDialog();
}
private void cmbOperacao_SelectedIndexChanged(object sender, EventArgs e)
{
Variaveis.OperacaoEmAndamento = OperacaoModel.CarregarParametrosOperacaoPadrao((ModoOperacao)cmbOperacao.SelectedIndex);
}
private void btnIniciar_Click(object sender, EventArgs e)
{
Variaveis.OperacaoEmAndamento.ModulosMandatorios.ForEach(Modulo =>
{
Modulo.Conectado = Variaveis.DispositivosConectados.Any(x => x.Dispositivo == Modulo.Dispositivo && x._Porta.IsOpen);
});
bool OperacaoLiberada =
(Variaveis.OperacaoEmAndamento.ModulosMandatorios.Where(x => x.Mandatorio).All(x => x.Conectado) && Variaveis.OperacaoEmAndamento.ModulosMandatorios.Any(x => x.Mandatorio)) ||
(Variaveis.OperacaoEmAndamento.ModulosMandatorios.All(x => !x.Mandatorio) && Variaveis.OperacaoEmAndamento.ModulosMandatorios.Any(x => x.Conectado));
if (Variaveis.OperacaoEmAndamento.Iniciado)
{
Variaveis.OperacaoEmAndamento.FinalizarOperacao();
}
else
{
if (OperacaoLiberada)
{
Variaveis.OperacaoEmAndamento.IniciarOperacao();
}
else
{
string MensagemErro = "Para iniciar a operação " + Enum.GetName(typeof(ModoOperacao), Variaveis.OperacaoEmAndamento.Modo) +
", é necessário que todos os módulos mandatórios estejam devidamente conectados ao equipamento, ou pelo menos um dos módulos:\r\n";
Variaveis.OperacaoEmAndamento.ModulosMandatorios.ForEach(Modulo =>
{
MensagemErro += Enum.GetName(typeof(T_Code), Modulo.Dispositivo) + ": ( " + (Modulo.Conectado ? "OK" : " ") + " ) - Mandatório: " + (Modulo.Mandatorio ? "Sim" : "Não") + "\r\n";
});
MessageBox.Show(MensagemErro, "Conexão de módulos pendentes", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
btnIniciar.Text = Variaveis.OperacaoEmAndamento.Iniciado ? "Finalizar" : "Iniciar";
cmbOperacao.Enabled = !Variaveis.OperacaoEmAndamento.Iniciado;
lblOperacaoStatus.Text = "Operação: " + Enum.GetName(typeof(ModoOperacao), Variaveis.OperacaoEmAndamento.Modo) + " " + (Variaveis.OperacaoEmAndamento.Iniciado ? "Iniciado" : "Não iniciado");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,189 @@
namespace AgroBase.Forms.Movimentacao
{
partial class frmMovCamera
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.pnlContornos = new System.Windows.Forms.Panel();
this.btnDesenhar = new System.Windows.Forms.Button();
this.cmbClasse = new System.Windows.Forms.ComboBox();
this.lblClasse = new System.Windows.Forms.Label();
this.gpbCameras = new System.Windows.Forms.GroupBox();
this.btnIniciar = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.btnSalvar = new System.Windows.Forms.Button();
this.cmbCameras = new System.Windows.Forms.ComboBox();
this.pnlCamera = new System.Windows.Forms.Panel();
this.gpbCameras.SuspendLayout();
this.SuspendLayout();
//
// pnlContornos
//
this.pnlContornos.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.pnlContornos.Location = new System.Drawing.Point(12, 12);
this.pnlContornos.Name = "pnlContornos";
this.pnlContornos.Size = new System.Drawing.Size(543, 525);
this.pnlContornos.TabIndex = 0;
this.pnlContornos.Paint += new System.Windows.Forms.PaintEventHandler(this.pnlContornos_Paint);
//
// btnDesenhar
//
this.btnDesenhar.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnDesenhar.Location = new System.Drawing.Point(671, 162);
this.btnDesenhar.Name = "btnDesenhar";
this.btnDesenhar.Size = new System.Drawing.Size(141, 23);
this.btnDesenhar.TabIndex = 1;
this.btnDesenhar.Text = "Atualizar";
this.btnDesenhar.UseVisualStyleBackColor = true;
this.btnDesenhar.Click += new System.EventHandler(this.btnDesenhar_Click);
//
// cmbClasse
//
this.cmbClasse.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cmbClasse.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbClasse.FormattingEnabled = true;
this.cmbClasse.Location = new System.Drawing.Point(671, 135);
this.cmbClasse.Name = "cmbClasse";
this.cmbClasse.Size = new System.Drawing.Size(141, 21);
this.cmbClasse.TabIndex = 2;
//
// lblClasse
//
this.lblClasse.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.lblClasse.AutoSize = true;
this.lblClasse.Location = new System.Drawing.Point(668, 119);
this.lblClasse.Name = "lblClasse";
this.lblClasse.Size = new System.Drawing.Size(38, 13);
this.lblClasse.TabIndex = 3;
this.lblClasse.Text = "Classe";
//
// gpbCameras
//
this.gpbCameras.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.gpbCameras.Controls.Add(this.btnIniciar);
this.gpbCameras.Controls.Add(this.button1);
this.gpbCameras.Controls.Add(this.btnSalvar);
this.gpbCameras.Controls.Add(this.cmbCameras);
this.gpbCameras.Location = new System.Drawing.Point(671, 12);
this.gpbCameras.Margin = new System.Windows.Forms.Padding(2);
this.gpbCameras.Name = "gpbCameras";
this.gpbCameras.Padding = new System.Windows.Forms.Padding(2);
this.gpbCameras.Size = new System.Drawing.Size(141, 105);
this.gpbCameras.TabIndex = 8;
this.gpbCameras.TabStop = false;
this.gpbCameras.Text = "Cameras";
//
// btnIniciar
//
this.btnIniciar.Enabled = false;
this.btnIniciar.Location = new System.Drawing.Point(4, 72);
this.btnIniciar.Margin = new System.Windows.Forms.Padding(2);
this.btnIniciar.Name = "btnIniciar";
this.btnIniciar.Size = new System.Drawing.Size(132, 23);
this.btnIniciar.TabIndex = 3;
this.btnIniciar.Text = "Iniciar";
this.btnIniciar.UseVisualStyleBackColor = true;
this.btnIniciar.Click += new System.EventHandler(this.btnIniciar_Click);
//
// button1
//
this.button1.Location = new System.Drawing.Point(4, 45);
this.button1.Margin = new System.Windows.Forms.Padding(2);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(64, 23);
this.button1.TabIndex = 2;
this.button1.Text = "Atualizar";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.btnAtualizar_Click);
//
// btnSalvar
//
this.btnSalvar.Location = new System.Drawing.Point(73, 45);
this.btnSalvar.Margin = new System.Windows.Forms.Padding(2);
this.btnSalvar.Name = "btnSalvar";
this.btnSalvar.Size = new System.Drawing.Size(64, 23);
this.btnSalvar.TabIndex = 1;
this.btnSalvar.Text = "Editar";
this.btnSalvar.UseVisualStyleBackColor = true;
this.btnSalvar.Click += new System.EventHandler(this.btnSalvar_Click);
//
// cmbCameras
//
this.cmbCameras.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbCameras.Enabled = false;
this.cmbCameras.FormattingEnabled = true;
this.cmbCameras.Location = new System.Drawing.Point(4, 20);
this.cmbCameras.Margin = new System.Windows.Forms.Padding(2);
this.cmbCameras.Name = "cmbCameras";
this.cmbCameras.Size = new System.Drawing.Size(133, 21);
this.cmbCameras.TabIndex = 0;
//
// pnlCamera
//
this.pnlCamera.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.pnlCamera.Location = new System.Drawing.Point(561, 347);
this.pnlCamera.Name = "pnlCamera";
this.pnlCamera.Size = new System.Drawing.Size(250, 190);
this.pnlCamera.TabIndex = 9;
//
// frmMovCamera
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(823, 544);
this.Controls.Add(this.pnlCamera);
this.Controls.Add(this.gpbCameras);
this.Controls.Add(this.lblClasse);
this.Controls.Add(this.cmbClasse);
this.Controls.Add(this.btnDesenhar);
this.Controls.Add(this.pnlContornos);
this.Name = "frmMovCamera";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "frmMovCamera";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmMovCamera_FormClosing);
this.Load += new System.EventHandler(this.frmMovCamera_Load);
this.gpbCameras.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Panel pnlContornos;
private System.Windows.Forms.Button btnDesenhar;
private System.Windows.Forms.ComboBox cmbClasse;
private System.Windows.Forms.Label lblClasse;
private System.Windows.Forms.GroupBox gpbCameras;
private System.Windows.Forms.Button btnIniciar;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button btnSalvar;
private System.Windows.Forms.ComboBox cmbCameras;
private System.Windows.Forms.Panel pnlCamera;
}
}

View File

@ -0,0 +1,313 @@
using AgroBase.Models;
using AgroBase.Services;
using CefSharp.WinForms;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AgroBase.Forms.Movimentacao
{
public partial class frmMovCamera : Form
{
private List<CameraDeepLabV3PlusModel> Leituras;
private Dictionary<string, Color> ClassMap = new Dictionary<string, Color>()
{
{ "background", Color.Black },
{ "rua", Color.DarkRed },
{ "cana", Color.DarkGreen },
{ "ceu", Color.Gold },
};
private CameraService<CameraDeepLabV3PlusModel> cameraService = new CameraService<CameraDeepLabV3PlusModel>();
private ChromiumWebBrowser chromiumWebBrowser = null;
private Timer tmrLeitura;
private int MaxLeituras = 1;
private string VideoPorta = VariaveisPortas.CameraCaminho;
private string VideoUrl = "street_detector";
private string SocketPorta = VariaveisPortas.SocketCaminho;
private bool MostrarDebug = true;
private string ArquivoLeitura = "leitura_solo.json";
public frmMovCamera()
{
InitializeComponent();
// Ativa o double buffering
this.DoubleBuffered = true;
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
pnlContornos.GetType().GetMethod("SetStyle", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(pnlContornos, new object[] { ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true });
}
private void frmMovCamera_Load(object sender, EventArgs e)
{
AtualizaListaCameras();
cmbClasse.Items.Clear();
cmbClasse.Items.AddRange(ClassMap.Keys.ToArray());
cmbClasse.SelectedIndex = 0;
}
private void frmMovCamera_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
tmrLeitura.Stop();
cameraService.socket.Disconnect();
cameraService.pythonProcess.Kill();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void TmrLeitura_Tick(object sender, EventArgs e)
{
DesenharContornos();
}
private void pnlContornos_Paint(object sender, PaintEventArgs e)
{
if (Leituras == null || Leituras.Count == 0) return;
Graphics graphics = e.Graphics;
graphics.Clear(pnlContornos.BackColor); // Limpa o fundo
// Determina as dimensões máximas dos contornos
float larguraMaxContornos = 512; // Substitua pelo valor real
float alturaMaxContornos = 512; // Substitua pelo valor real
// Proporção de escala baseada no tamanho do Panel e nas dimensões dos contornos
float proporcaoX = pnlContornos.Width / larguraMaxContornos;
float proporcaoY = pnlContornos.Height / alturaMaxContornos;
float escala = Math.Min(proporcaoX, proporcaoY); // Mantém a proporção sem distorcer
// Calcula o novo tamanho dos contornos após o redimensionamento
float novaLargura = larguraMaxContornos * escala;
float novaAltura = alturaMaxContornos * escala;
// Calcula o deslocamento para centralizar os contornos no Panel
float deslocamentoX = (pnlContornos.Width - novaLargura) / 2;
float deslocamentoY = (pnlContornos.Height - novaAltura) / 2;
List<Point> pontosCamera = new List<Point>();
var Classe = ClassMap.FirstOrDefault(x => x.Key == cmbClasse.Text);
foreach (var Leitura in Leituras.OrderByDescending(x => x.timestamp))
{
foreach (var cameraClass in Leitura.Classes.Where(x => x.Classe == Classe.Key))
{
if (cameraClass.Contornos == null || cameraClass.Contornos.Length == 0) continue;
using (Pen pen = new Pen(Color.Blue, 2))
{
for (int i = 0; i < cameraClass.Contornos.Length - 1; i++)
{
Point contorno = new Point() { X = cameraClass.Contornos[i][0], Y = cameraClass.Contornos[i][1] };
Point contornoP = new Point() { X = cameraClass.Contornos[i + 1][0], Y = cameraClass.Contornos[i + 1][1] };
// Aplica a escala e o deslocamento às coordenadas
Point start = new Point((int)(contorno.X * escala + deslocamentoX), (int)(contorno.Y * escala + deslocamentoY));
Point end = new Point((int)(contornoP.X * escala + deslocamentoX), (int)(contornoP.Y * escala + deslocamentoY));
graphics.DrawLine(pen, start, end);
pontosCamera.Add(contorno);
}
// Se necessário, fechar o contorno conectando o último ponto ao primeiro
if (cameraClass.Contornos.Length > 1)
{
var primeiro = cameraClass.Contornos.First();
var ultimo = cameraClass.Contornos.Last();
Point start = new Point((int)(ultimo[0] * escala + deslocamentoX), (int)(ultimo[1] * escala + deslocamentoY));
Point end = new Point((int)(primeiro[0] * escala + deslocamentoX), (int)(primeiro[1] * escala + deslocamentoY));
graphics.DrawLine(pen, start, end);
}
}
}
// Plotar apenas a ultima leitura do json
break;
}
using (Pen pen = new Pen(Classe.Value, 2))
{
var PontosExtremos = DefinirPontosExtremos(pontosCamera);
for (int i = 0; i < PontosExtremos.Count - 1; i++)
{
// Aplica a escala e o deslocamento às coordenadas
Point start = new Point((int)(PontosExtremos[i].X * escala + deslocamentoX), (int)(PontosExtremos[i].Y * escala + deslocamentoY));
Point end = new Point((int)(PontosExtremos[i + 1].X * escala + deslocamentoX), (int)(PontosExtremos[i + 1].Y * escala + deslocamentoY));
graphics.DrawLine(pen, start, end);
}
}
}
private List<Point> DefinirPontosExtremos(List<Point> PontosCamera)
{
if (!PontosCamera.Any())
{
return new List<Point>();
}
List<Point> Pontos = new List<Point>()
{
new Point(9999, -1), // Ponto 0 - Mais a esquerda e abaixo
new Point(9999, -1), // Ponto 1 - Mais a esquerda e abaixo, e esquerda > Ponto0.X
new Point(9999, 9999), // Ponto 2 - Mais a esquerda e acima
new Point(-1, 9999), // Ponto 3 - Mais a direita e acima
new Point(-1, -1), // Ponto 4 - Mais a direita e abaixo, e direita < Ponto5.X
new Point(-1, -1), // Ponto 5 - Mais a direita e abaixo
};
foreach (var Ponto in PontosCamera)
{
// Ponto 0 - Mais a esquerda e abaixo
if (Ponto.X < Pontos[0].X)
{
Pontos[0] = new Point() { X = Ponto.X, Y = Ponto.Y };
}
// Ponto 5 - Mais a direita e abaixo
if (Ponto.X > Pontos[5].X)
{
Pontos[5] = new Point() { X = Ponto.X, Y = Ponto.Y };
}
}
var Ponto0 = PontosCamera.Where(Ponto => Ponto.X == Pontos[0].X).OrderByDescending(Ponto => Ponto.Y).First();
Pontos[0] = Ponto0;
var Ponto5 = PontosCamera.Where(Ponto => Ponto.X == Pontos[5].X).OrderByDescending(Ponto => Ponto.Y).First();
Pontos[5] = Ponto5;
foreach (var Ponto in PontosCamera)
{
// Ponto 1 - Mais a esquerda e abaixo, e esquerda > Ponto0.X
if (Ponto.X < Pontos[1].X && Ponto.X > Ponto0.X)
{
Pontos[1] = new Point() { X = Ponto.X, Y = Ponto.Y };
}
// Ponto 4 Mais a direita e abaixo, e direita < Ponto5.X
if (Ponto.X > Pontos[4].X && Ponto.X < Ponto5.X)
{
Pontos[4] = new Point() { X = Ponto.X, Y = Ponto.Y };
}
}
var Ponto1 = PontosCamera.Where(Ponto => Ponto.X == Pontos[1].X).OrderByDescending(Ponto => Ponto.Y).First();
Pontos[1] = Ponto1;
var Ponto4 = PontosCamera.Where(Ponto => Ponto.X == Pontos[4].X).OrderByDescending(Ponto => Ponto.Y).First();
Pontos[4] = Ponto4;
int Y_min = PontosCamera.OrderBy(Ponto => Ponto.Y).First().Y;
foreach (var Ponto in PontosCamera.Where(x => x.Y == Y_min))
{
// Ponto 2 - Mais a esquerda e acima
if (Ponto.X < Pontos[2].X)
{
Pontos[2] = new Point() { X = Ponto.X, Y = Ponto.Y };
}
// Ponto 3 - Mais a direita e acima
if (Ponto.X > Pontos[3].X)
{
Pontos[3] = new Point() { X = Ponto.X, Y = Ponto.Y };
}
}
return Pontos;
}
private void btnDesenhar_Click(object sender, EventArgs e)
{
DesenharContornos();
}
private void DesenharContornos()
{
if (chromiumWebBrowser == null)
{
chromiumWebBrowser = new ChromiumWebBrowser(cameraService.URLcamera);
this.pnlCamera.Controls.Add(chromiumWebBrowser);
chromiumWebBrowser.Dock = DockStyle.Fill;
}
try
{
var contornosJson = File.ReadAllText("Python/Output/" + ArquivoLeitura);
Leituras = JsonConvert.DeserializeObject<CameraDeepLabV3PlusModel[]>(contornosJson).ToList();
//Leituras = cameraService.socket.DadosRecebidos;
pnlContornos.Invalidate();
}
catch
{
}
}
private void btnAtualizar_Click(object sender, EventArgs e)
{
AtualizaListaCameras();
}
private void btnSalvar_Click(object sender, EventArgs e)
{
if (btnSalvar.Text == "Editar")
{
btnSalvar.Text = "Salvar";
}
else
{
btnSalvar.Text = "Editar";
cameraService.selectedCamera = cmbCameras.SelectedIndex;
}
btnIniciar.Enabled = btnSalvar.Text == "Editar" && cmbCameras.SelectedIndex > 0;
cmbCameras.Enabled = btnSalvar.Text == "Salvar";
}
private void btnIniciar_Click(object sender, EventArgs e)
{
cameraService.ArquivoLeitura = ArquivoLeitura;
cameraService.IniciarCamera(
PythonService.ScriptStreetDetector,
new string[] { MaxLeituras.ToString(), VideoPorta, VideoUrl, ArquivoLeitura, MostrarDebug ? "1" : "0", SocketPorta },
VideoPorta,
VideoUrl,
SocketPorta
);
tmrLeitura = new Timer() { Interval = 200 };
tmrLeitura.Tick += TmrLeitura_Tick;
tmrLeitura.Start();
}
private void AtualizaListaCameras()
{
cameraService.selectedCamera = cmbCameras.SelectedIndex > 0 ? cmbCameras.SelectedIndex : 0;
cmbCameras.Items.Clear();
cmbCameras.Items.AddRange(cameraService.AtualizaListaCameras().ToArray());
if (cmbCameras.Items.Count == 1)
{
cameraService.selectedCamera = 0;
}
cmbCameras.SelectedIndex = cameraService.selectedCamera;
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -33,9 +33,12 @@ namespace AgroBase.Forms.Operacoes
System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
this.pnlCameraSolo = new System.Windows.Forms.Panel();
this.pnlCameraSoloD = new System.Windows.Forms.Panel();
this.pnlCameraSoloE = new System.Windows.Forms.Panel();
this.pnlCameraCaminho = new System.Windows.Forms.Panel();
this.pnlAtuadores = new System.Windows.Forms.Panel();
this.pnlMapa = new System.Windows.Forms.Panel();
this.btnDesenharMapa = new System.Windows.Forms.Button();
this.pnlGraficos = new System.Windows.Forms.Panel();
this.chartGraficos = new System.Windows.Forms.DataVisualization.Charting.Chart();
this.pnlNiveis = new System.Windows.Forms.Panel();
@ -46,13 +49,14 @@ namespace AgroBase.Forms.Operacoes
this.lblPorcentagemReservatorio = new System.Windows.Forms.Label();
this.pgbReservatorio = new System.Windows.Forms.ProgressBar();
this.gpbOpcoes = new System.Windows.Forms.GroupBox();
this.cmbCameraSoloD = new System.Windows.Forms.ComboBox();
this.lblCameraSoloD = new System.Windows.Forms.Label();
this.btnIniciarOperacao = new System.Windows.Forms.Button();
this.btnCarregarMapa = new System.Windows.Forms.Button();
this.lblMapa = new System.Windows.Forms.Label();
this.cmbCameraCaminho = new System.Windows.Forms.ComboBox();
this.lblCameraCaminho = new System.Windows.Forms.Label();
this.cmbCameraSolo = new System.Windows.Forms.ComboBox();
this.lblCameraSolo = new System.Windows.Forms.Label();
this.cmbCameraSoloE = new System.Windows.Forms.ComboBox();
this.lblCameraSoloE = new System.Windows.Forms.Label();
this.btnCarregarMapa = new System.Windows.Forms.Button();
this.lblMapaCarregado = new System.Windows.Forms.Label();
this.gpbInformacoesGerais = new System.Windows.Forms.GroupBox();
this.lblBateriaConsumida = new System.Windows.Forms.Label();
@ -68,7 +72,8 @@ namespace AgroBase.Forms.Operacoes
this.pnlInferior = new System.Windows.Forms.Panel();
this.lblUltimaLeituraRua = new System.Windows.Forms.Label();
this.lblUltimaLeituraSolo = new System.Windows.Forms.Label();
this.btnDesenharMapa = new System.Windows.Forms.Button();
this.pnlCameraSolo.SuspendLayout();
this.pnlMapa.SuspendLayout();
this.pnlGraficos.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.chartGraficos)).BeginInit();
this.pnlNiveis.SuspendLayout();
@ -80,44 +85,77 @@ namespace AgroBase.Forms.Operacoes
// pnlCameraSolo
//
this.pnlCameraSolo.BackColor = System.Drawing.SystemColors.ControlDark;
this.pnlCameraSolo.Location = new System.Drawing.Point(12, 40);
this.pnlCameraSolo.Controls.Add(this.pnlCameraSoloD);
this.pnlCameraSolo.Controls.Add(this.pnlCameraSoloE);
this.pnlCameraSolo.Location = new System.Drawing.Point(9, 32);
this.pnlCameraSolo.Margin = new System.Windows.Forms.Padding(2);
this.pnlCameraSolo.Name = "pnlCameraSolo";
this.pnlCameraSolo.Size = new System.Drawing.Size(790, 558);
this.pnlCameraSolo.Size = new System.Drawing.Size(592, 453);
this.pnlCameraSolo.TabIndex = 0;
//
// pnlCameraSoloD
//
this.pnlCameraSoloD.Location = new System.Drawing.Point(299, 186);
this.pnlCameraSoloD.Name = "pnlCameraSoloD";
this.pnlCameraSoloD.Size = new System.Drawing.Size(289, 264);
this.pnlCameraSoloD.TabIndex = 1;
//
// pnlCameraSoloE
//
this.pnlCameraSoloE.Location = new System.Drawing.Point(4, 186);
this.pnlCameraSoloE.Name = "pnlCameraSoloE";
this.pnlCameraSoloE.Size = new System.Drawing.Size(289, 264);
this.pnlCameraSoloE.TabIndex = 0;
//
// pnlCameraCaminho
//
this.pnlCameraCaminho.BackColor = System.Drawing.SystemColors.ControlDarkDark;
this.pnlCameraCaminho.Location = new System.Drawing.Point(481, 12);
this.pnlCameraCaminho.Location = new System.Drawing.Point(361, 10);
this.pnlCameraCaminho.Margin = new System.Windows.Forms.Padding(2);
this.pnlCameraCaminho.Name = "pnlCameraCaminho";
this.pnlCameraCaminho.Size = new System.Drawing.Size(349, 250);
this.pnlCameraCaminho.Size = new System.Drawing.Size(262, 203);
this.pnlCameraCaminho.TabIndex = 1;
//
// pnlAtuadores
//
this.pnlAtuadores.BackColor = System.Drawing.SystemColors.Control;
this.pnlAtuadores.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.pnlAtuadores.Location = new System.Drawing.Point(12, 604);
this.pnlAtuadores.Location = new System.Drawing.Point(9, 491);
this.pnlAtuadores.Margin = new System.Windows.Forms.Padding(2);
this.pnlAtuadores.Name = "pnlAtuadores";
this.pnlAtuadores.Size = new System.Drawing.Size(790, 86);
this.pnlAtuadores.Size = new System.Drawing.Size(594, 71);
this.pnlAtuadores.TabIndex = 2;
this.pnlAtuadores.Paint += new System.Windows.Forms.PaintEventHandler(this.pnlAtuadores_Paint);
//
// pnlMapa
//
this.pnlMapa.BackColor = System.Drawing.Color.White;
this.pnlMapa.Location = new System.Drawing.Point(836, 12);
this.pnlMapa.Controls.Add(this.btnDesenharMapa);
this.pnlMapa.Location = new System.Drawing.Point(627, 10);
this.pnlMapa.Margin = new System.Windows.Forms.Padding(2);
this.pnlMapa.Name = "pnlMapa";
this.pnlMapa.Size = new System.Drawing.Size(512, 343);
this.pnlMapa.Size = new System.Drawing.Size(384, 279);
this.pnlMapa.TabIndex = 3;
this.pnlMapa.Paint += new System.Windows.Forms.PaintEventHandler(this.pnlMapa_Paint);
//
// btnDesenharMapa
//
this.btnDesenharMapa.Location = new System.Drawing.Point(306, 258);
this.btnDesenharMapa.Margin = new System.Windows.Forms.Padding(2);
this.btnDesenharMapa.Name = "btnDesenharMapa";
this.btnDesenharMapa.Size = new System.Drawing.Size(76, 19);
this.btnDesenharMapa.TabIndex = 14;
this.btnDesenharMapa.Text = "Desenhar";
this.btnDesenharMapa.UseVisualStyleBackColor = true;
this.btnDesenharMapa.Click += new System.EventHandler(this.btnDesenharMapa_Click);
//
// pnlGraficos
//
this.pnlGraficos.Controls.Add(this.chartGraficos);
this.pnlGraficos.Location = new System.Drawing.Point(808, 378);
this.pnlGraficos.Location = new System.Drawing.Point(606, 307);
this.pnlGraficos.Margin = new System.Windows.Forms.Padding(2);
this.pnlGraficos.Name = "pnlGraficos";
this.pnlGraficos.Size = new System.Drawing.Size(540, 312);
this.pnlGraficos.Size = new System.Drawing.Size(405, 254);
this.pnlGraficos.TabIndex = 4;
//
// chartGraficos
@ -128,12 +166,13 @@ namespace AgroBase.Forms.Operacoes
legend1.Name = "Legend1";
this.chartGraficos.Legends.Add(legend1);
this.chartGraficos.Location = new System.Drawing.Point(0, 0);
this.chartGraficos.Margin = new System.Windows.Forms.Padding(2);
this.chartGraficos.Name = "chartGraficos";
series1.ChartArea = "ChartArea1";
series1.Legend = "Legend1";
series1.Name = "Series1";
this.chartGraficos.Series.Add(series1);
this.chartGraficos.Size = new System.Drawing.Size(540, 312);
this.chartGraficos.Size = new System.Drawing.Size(405, 254);
this.chartGraficos.TabIndex = 0;
this.chartGraficos.Text = "chart1";
//
@ -147,150 +186,178 @@ namespace AgroBase.Forms.Operacoes
this.pnlNiveis.Controls.Add(this.lblPorcentagemReservatorio);
this.pnlNiveis.Controls.Add(this.pgbReservatorio);
this.pnlNiveis.Font = new System.Drawing.Font("Mongolian Baiti", 9F, System.Drawing.FontStyle.Bold);
this.pnlNiveis.Location = new System.Drawing.Point(12, 702);
this.pnlNiveis.Location = new System.Drawing.Point(9, 570);
this.pnlNiveis.Margin = new System.Windows.Forms.Padding(2);
this.pnlNiveis.Name = "pnlNiveis";
this.pnlNiveis.Size = new System.Drawing.Size(790, 85);
this.pnlNiveis.Size = new System.Drawing.Size(592, 69);
this.pnlNiveis.TabIndex = 6;
//
// lblPorcentagemProgresso
//
this.lblPorcentagemProgresso.AutoSize = true;
this.lblPorcentagemProgresso.Location = new System.Drawing.Point(522, 13);
this.lblPorcentagemProgresso.Location = new System.Drawing.Point(392, 11);
this.lblPorcentagemProgresso.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblPorcentagemProgresso.Name = "lblPorcentagemProgresso";
this.lblPorcentagemProgresso.Size = new System.Drawing.Size(134, 16);
this.lblPorcentagemProgresso.Size = new System.Drawing.Size(108, 13);
this.lblPorcentagemProgresso.TabIndex = 5;
this.lblPorcentagemProgresso.Text = "Progresso: 0,00%";
//
// pgbProgresso
//
this.pgbProgresso.Location = new System.Drawing.Point(525, 33);
this.pgbProgresso.Location = new System.Drawing.Point(394, 27);
this.pgbProgresso.Margin = new System.Windows.Forms.Padding(2);
this.pgbProgresso.Name = "pgbProgresso";
this.pgbProgresso.Size = new System.Drawing.Size(255, 49);
this.pgbProgresso.Size = new System.Drawing.Size(191, 40);
this.pgbProgresso.TabIndex = 4;
//
// lblPorcentagemBateria
//
this.lblPorcentagemBateria.AutoSize = true;
this.lblPorcentagemBateria.Location = new System.Drawing.Point(264, 13);
this.lblPorcentagemBateria.Location = new System.Drawing.Point(198, 11);
this.lblPorcentagemBateria.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblPorcentagemBateria.Name = "lblPorcentagemBateria";
this.lblPorcentagemBateria.Size = new System.Drawing.Size(115, 16);
this.lblPorcentagemBateria.Size = new System.Drawing.Size(91, 13);
this.lblPorcentagemBateria.TabIndex = 3;
this.lblPorcentagemBateria.Text = "Bateria: 0,00%";
//
// pgbBateria
//
this.pgbBateria.Location = new System.Drawing.Point(264, 33);
this.pgbBateria.Location = new System.Drawing.Point(198, 27);
this.pgbBateria.Margin = new System.Windows.Forms.Padding(2);
this.pgbBateria.Name = "pgbBateria";
this.pgbBateria.Size = new System.Drawing.Size(255, 49);
this.pgbBateria.Size = new System.Drawing.Size(191, 40);
this.pgbBateria.TabIndex = 2;
//
// lblPorcentagemReservatorio
//
this.lblPorcentagemReservatorio.AutoSize = true;
this.lblPorcentagemReservatorio.Location = new System.Drawing.Point(3, 13);
this.lblPorcentagemReservatorio.Location = new System.Drawing.Point(2, 11);
this.lblPorcentagemReservatorio.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblPorcentagemReservatorio.Name = "lblPorcentagemReservatorio";
this.lblPorcentagemReservatorio.Size = new System.Drawing.Size(155, 16);
this.lblPorcentagemReservatorio.Size = new System.Drawing.Size(123, 13);
this.lblPorcentagemReservatorio.TabIndex = 1;
this.lblPorcentagemReservatorio.Text = "Reservatório: 0,00%";
//
// pgbReservatorio
//
this.pgbReservatorio.Location = new System.Drawing.Point(3, 33);
this.pgbReservatorio.Location = new System.Drawing.Point(2, 27);
this.pgbReservatorio.Margin = new System.Windows.Forms.Padding(2);
this.pgbReservatorio.Name = "pgbReservatorio";
this.pgbReservatorio.Size = new System.Drawing.Size(255, 49);
this.pgbReservatorio.Size = new System.Drawing.Size(191, 40);
this.pgbReservatorio.TabIndex = 0;
//
// gpbOpcoes
//
this.gpbOpcoes.Controls.Add(this.cmbCameraSoloD);
this.gpbOpcoes.Controls.Add(this.lblCameraSoloD);
this.gpbOpcoes.Controls.Add(this.btnIniciarOperacao);
this.gpbOpcoes.Controls.Add(this.btnCarregarMapa);
this.gpbOpcoes.Controls.Add(this.lblMapa);
this.gpbOpcoes.Controls.Add(this.cmbCameraCaminho);
this.gpbOpcoes.Controls.Add(this.lblCameraCaminho);
this.gpbOpcoes.Controls.Add(this.cmbCameraSolo);
this.gpbOpcoes.Controls.Add(this.lblCameraSolo);
this.gpbOpcoes.Controls.Add(this.cmbCameraSoloE);
this.gpbOpcoes.Controls.Add(this.lblCameraSoloE);
this.gpbOpcoes.Font = new System.Drawing.Font("Mongolian Baiti", 9F, System.Drawing.FontStyle.Bold);
this.gpbOpcoes.Location = new System.Drawing.Point(1084, 696);
this.gpbOpcoes.Location = new System.Drawing.Point(813, 566);
this.gpbOpcoes.Margin = new System.Windows.Forms.Padding(2);
this.gpbOpcoes.Name = "gpbOpcoes";
this.gpbOpcoes.Size = new System.Drawing.Size(264, 147);
this.gpbOpcoes.Padding = new System.Windows.Forms.Padding(2);
this.gpbOpcoes.Size = new System.Drawing.Size(198, 119);
this.gpbOpcoes.TabIndex = 7;
this.gpbOpcoes.TabStop = false;
this.gpbOpcoes.Text = "Opções";
//
// cmbCameraSoloD
//
this.cmbCameraSoloD.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbCameraSoloD.FormattingEnabled = true;
this.cmbCameraSoloD.Location = new System.Drawing.Point(83, 42);
this.cmbCameraSoloD.Margin = new System.Windows.Forms.Padding(2);
this.cmbCameraSoloD.Name = "cmbCameraSoloD";
this.cmbCameraSoloD.Size = new System.Drawing.Size(111, 21);
this.cmbCameraSoloD.TabIndex = 8;
this.cmbCameraSoloD.SelectedIndexChanged += new System.EventHandler(this.cmbCameraSolo_SelectedIndexChanged);
//
// lblCameraSoloD
//
this.lblCameraSoloD.AutoSize = true;
this.lblCameraSoloD.Location = new System.Drawing.Point(4, 45);
this.lblCameraSoloD.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblCameraSoloD.Name = "lblCameraSoloD";
this.lblCameraSoloD.Size = new System.Drawing.Size(76, 13);
this.lblCameraSoloD.TabIndex = 7;
this.lblCameraSoloD.Text = "Cam Solo D";
//
// btnIniciarOperacao
//
this.btnIniciarOperacao.Location = new System.Drawing.Point(9, 115);
this.btnIniciarOperacao.Location = new System.Drawing.Point(7, 93);
this.btnIniciarOperacao.Margin = new System.Windows.Forms.Padding(2);
this.btnIniciarOperacao.Name = "btnIniciarOperacao";
this.btnIniciarOperacao.Size = new System.Drawing.Size(249, 26);
this.btnIniciarOperacao.Size = new System.Drawing.Size(187, 21);
this.btnIniciarOperacao.TabIndex = 6;
this.btnIniciarOperacao.Text = "Iniciar Operação";
this.btnIniciarOperacao.UseVisualStyleBackColor = true;
this.btnIniciarOperacao.Click += new System.EventHandler(this.btnIniciarOperacao_Click);
//
// btnCarregarMapa
//
this.btnCarregarMapa.Location = new System.Drawing.Point(111, 81);
this.btnCarregarMapa.Name = "btnCarregarMapa";
this.btnCarregarMapa.Size = new System.Drawing.Size(147, 26);
this.btnCarregarMapa.TabIndex = 5;
this.btnCarregarMapa.Text = "Carregar...";
this.btnCarregarMapa.UseVisualStyleBackColor = true;
this.btnCarregarMapa.Click += new System.EventHandler(this.btnCarregarMapa_Click);
//
// lblMapa
//
this.lblMapa.AutoSize = true;
this.lblMapa.Location = new System.Drawing.Point(6, 86);
this.lblMapa.Name = "lblMapa";
this.lblMapa.Size = new System.Drawing.Size(47, 16);
this.lblMapa.TabIndex = 4;
this.lblMapa.Text = "Mapa";
//
// cmbCameraCaminho
//
this.cmbCameraCaminho.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbCameraCaminho.FormattingEnabled = true;
this.cmbCameraCaminho.Location = new System.Drawing.Point(111, 51);
this.cmbCameraCaminho.Location = new System.Drawing.Point(83, 67);
this.cmbCameraCaminho.Margin = new System.Windows.Forms.Padding(2);
this.cmbCameraCaminho.Name = "cmbCameraCaminho";
this.cmbCameraCaminho.Size = new System.Drawing.Size(147, 24);
this.cmbCameraCaminho.Size = new System.Drawing.Size(111, 21);
this.cmbCameraCaminho.TabIndex = 3;
this.cmbCameraCaminho.SelectedIndexChanged += new System.EventHandler(this.cmbCameraCaminho_SelectedIndexChanged);
//
// lblCameraCaminho
//
this.lblCameraCaminho.AutoSize = true;
this.lblCameraCaminho.Location = new System.Drawing.Point(6, 54);
this.lblCameraCaminho.Location = new System.Drawing.Point(4, 70);
this.lblCameraCaminho.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblCameraCaminho.Name = "lblCameraCaminho";
this.lblCameraCaminho.Size = new System.Drawing.Size(95, 16);
this.lblCameraCaminho.Size = new System.Drawing.Size(75, 13);
this.lblCameraCaminho.TabIndex = 2;
this.lblCameraCaminho.Text = "Camera Rua";
//
// cmbCameraSolo
// cmbCameraSoloE
//
this.cmbCameraSolo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbCameraSolo.FormattingEnabled = true;
this.cmbCameraSolo.Location = new System.Drawing.Point(111, 21);
this.cmbCameraSolo.Name = "cmbCameraSolo";
this.cmbCameraSolo.Size = new System.Drawing.Size(147, 24);
this.cmbCameraSolo.TabIndex = 1;
this.cmbCameraSolo.SelectedIndexChanged += new System.EventHandler(this.cmbCameraSolo_SelectedIndexChanged);
this.cmbCameraSoloE.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbCameraSoloE.FormattingEnabled = true;
this.cmbCameraSoloE.Location = new System.Drawing.Point(83, 17);
this.cmbCameraSoloE.Margin = new System.Windows.Forms.Padding(2);
this.cmbCameraSoloE.Name = "cmbCameraSoloE";
this.cmbCameraSoloE.Size = new System.Drawing.Size(111, 21);
this.cmbCameraSoloE.TabIndex = 1;
this.cmbCameraSoloE.SelectedIndexChanged += new System.EventHandler(this.cmbCameraSolo_SelectedIndexChanged);
//
// lblCameraSolo
// lblCameraSoloE
//
this.lblCameraSolo.AutoSize = true;
this.lblCameraSolo.Location = new System.Drawing.Point(6, 24);
this.lblCameraSolo.Name = "lblCameraSolo";
this.lblCameraSolo.Size = new System.Drawing.Size(99, 16);
this.lblCameraSolo.TabIndex = 0;
this.lblCameraSolo.Text = "Camera Solo";
this.lblCameraSoloE.AutoSize = true;
this.lblCameraSoloE.Location = new System.Drawing.Point(4, 20);
this.lblCameraSoloE.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblCameraSoloE.Name = "lblCameraSoloE";
this.lblCameraSoloE.Size = new System.Drawing.Size(74, 13);
this.lblCameraSoloE.TabIndex = 0;
this.lblCameraSoloE.Text = "Cam Solo E";
//
// btnCarregarMapa
//
this.btnCarregarMapa.Location = new System.Drawing.Point(933, 291);
this.btnCarregarMapa.Margin = new System.Windows.Forms.Padding(2);
this.btnCarregarMapa.Name = "btnCarregarMapa";
this.btnCarregarMapa.Size = new System.Drawing.Size(76, 22);
this.btnCarregarMapa.TabIndex = 5;
this.btnCarregarMapa.Text = "Carregar...";
this.btnCarregarMapa.UseVisualStyleBackColor = true;
this.btnCarregarMapa.Click += new System.EventHandler(this.btnCarregarMapa_Click);
//
// lblMapaCarregado
//
this.lblMapaCarregado.AutoSize = true;
this.lblMapaCarregado.Font = new System.Drawing.Font("Mongolian Baiti", 9F, System.Drawing.FontStyle.Bold);
this.lblMapaCarregado.Location = new System.Drawing.Point(918, 358);
this.lblMapaCarregado.Location = new System.Drawing.Point(688, 291);
this.lblMapaCarregado.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblMapaCarregado.Name = "lblMapaCarregado";
this.lblMapaCarregado.Size = new System.Drawing.Size(162, 16);
this.lblMapaCarregado.Size = new System.Drawing.Size(129, 13);
this.lblMapaCarregado.TabIndex = 8;
this.lblMapaCarregado.Text = "Mapa carregado: N/A";
//
@ -304,9 +371,11 @@ namespace AgroBase.Forms.Operacoes
this.gpbInformacoesGerais.Controls.Add(this.lblTempoOperacao);
this.gpbInformacoesGerais.Controls.Add(this.lblDistanciaPercorrida);
this.gpbInformacoesGerais.Font = new System.Drawing.Font("Mongolian Baiti", 9F, System.Drawing.FontStyle.Bold);
this.gpbInformacoesGerais.Location = new System.Drawing.Point(808, 696);
this.gpbInformacoesGerais.Location = new System.Drawing.Point(606, 566);
this.gpbInformacoesGerais.Margin = new System.Windows.Forms.Padding(2);
this.gpbInformacoesGerais.Name = "gpbInformacoesGerais";
this.gpbInformacoesGerais.Size = new System.Drawing.Size(270, 147);
this.gpbInformacoesGerais.Padding = new System.Windows.Forms.Padding(2);
this.gpbInformacoesGerais.Size = new System.Drawing.Size(202, 119);
this.gpbInformacoesGerais.TabIndex = 9;
this.gpbInformacoesGerais.TabStop = false;
this.gpbInformacoesGerais.Text = "Informações Gerais";
@ -314,72 +383,80 @@ namespace AgroBase.Forms.Operacoes
// lblBateriaConsumida
//
this.lblBateriaConsumida.AutoSize = true;
this.lblBateriaConsumida.Location = new System.Drawing.Point(11, 123);
this.lblBateriaConsumida.Location = new System.Drawing.Point(8, 100);
this.lblBateriaConsumida.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblBateriaConsumida.Name = "lblBateriaConsumida";
this.lblBateriaConsumida.Size = new System.Drawing.Size(200, 16);
this.lblBateriaConsumida.Size = new System.Drawing.Size(158, 13);
this.lblBateriaConsumida.TabIndex = 6;
this.lblBateriaConsumida.Text = "Bateria Consumida: 0,00%";
//
// lblHerbicidaPorErva
//
this.lblHerbicidaPorErva.AutoSize = true;
this.lblHerbicidaPorErva.Location = new System.Drawing.Point(11, 107);
this.lblHerbicidaPorErva.Location = new System.Drawing.Point(8, 87);
this.lblHerbicidaPorErva.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblHerbicidaPorErva.Name = "lblHerbicidaPorErva";
this.lblHerbicidaPorErva.Size = new System.Drawing.Size(224, 16);
this.lblHerbicidaPorErva.Size = new System.Drawing.Size(177, 13);
this.lblHerbicidaPorErva.TabIndex = 5;
this.lblHerbicidaPorErva.Text = "Herbicida por Erva: 0,000 mL";
//
// lblHerbicidaAplicado
//
this.lblHerbicidaAplicado.AutoSize = true;
this.lblHerbicidaAplicado.Location = new System.Drawing.Point(11, 91);
this.lblHerbicidaAplicado.Location = new System.Drawing.Point(8, 74);
this.lblHerbicidaAplicado.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblHerbicidaAplicado.Name = "lblHerbicidaAplicado";
this.lblHerbicidaAplicado.Size = new System.Drawing.Size(205, 16);
this.lblHerbicidaAplicado.Size = new System.Drawing.Size(162, 13);
this.lblHerbicidaAplicado.TabIndex = 4;
this.lblHerbicidaAplicado.Text = "Herbicida Aplicado: 0,00 L";
//
// lblErvasIdentificadas
//
this.lblErvasIdentificadas.AutoSize = true;
this.lblErvasIdentificadas.Location = new System.Drawing.Point(11, 75);
this.lblErvasIdentificadas.Location = new System.Drawing.Point(8, 61);
this.lblErvasIdentificadas.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblErvasIdentificadas.Name = "lblErvasIdentificadas";
this.lblErvasIdentificadas.Size = new System.Drawing.Size(183, 16);
this.lblErvasIdentificadas.Size = new System.Drawing.Size(145, 13);
this.lblErvasIdentificadas.TabIndex = 3;
this.lblErvasIdentificadas.Text = "Ervas Identificadas: 000";
//
// lblVelocidadeMedia
//
this.lblVelocidadeMedia.AutoSize = true;
this.lblVelocidadeMedia.Location = new System.Drawing.Point(11, 59);
this.lblVelocidadeMedia.Location = new System.Drawing.Point(8, 48);
this.lblVelocidadeMedia.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblVelocidadeMedia.Name = "lblVelocidadeMedia";
this.lblVelocidadeMedia.Size = new System.Drawing.Size(221, 16);
this.lblVelocidadeMedia.Size = new System.Drawing.Size(174, 13);
this.lblVelocidadeMedia.TabIndex = 2;
this.lblVelocidadeMedia.Text = "Velocidade Média: 0,00 km/h";
//
// lblTempoOperacao
//
this.lblTempoOperacao.AutoSize = true;
this.lblTempoOperacao.Location = new System.Drawing.Point(11, 43);
this.lblTempoOperacao.Location = new System.Drawing.Point(8, 35);
this.lblTempoOperacao.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblTempoOperacao.Name = "lblTempoOperacao";
this.lblTempoOperacao.Size = new System.Drawing.Size(226, 16);
this.lblTempoOperacao.Size = new System.Drawing.Size(177, 13);
this.lblTempoOperacao.TabIndex = 1;
this.lblTempoOperacao.Text = "Tempo de Operação: 00:00:00";
//
// lblDistanciaPercorrida
//
this.lblDistanciaPercorrida.AutoSize = true;
this.lblDistanciaPercorrida.Location = new System.Drawing.Point(11, 27);
this.lblDistanciaPercorrida.Location = new System.Drawing.Point(8, 22);
this.lblDistanciaPercorrida.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblDistanciaPercorrida.Name = "lblDistanciaPercorrida";
this.lblDistanciaPercorrida.Size = new System.Drawing.Size(214, 16);
this.lblDistanciaPercorrida.Size = new System.Drawing.Size(170, 13);
this.lblDistanciaPercorrida.TabIndex = 0;
this.lblDistanciaPercorrida.Text = "Distancia Percorrida: 0,00 m";
//
// pnlInclinacao
//
this.pnlInclinacao.BackColor = System.Drawing.Color.White;
this.pnlInclinacao.Location = new System.Drawing.Point(808, 268);
this.pnlInclinacao.Location = new System.Drawing.Point(606, 218);
this.pnlInclinacao.Margin = new System.Windows.Forms.Padding(2);
this.pnlInclinacao.Name = "pnlInclinacao";
this.pnlInclinacao.Size = new System.Drawing.Size(104, 104);
this.pnlInclinacao.Size = new System.Drawing.Size(78, 84);
this.pnlInclinacao.TabIndex = 10;
this.pnlInclinacao.Paint += new System.Windows.Forms.PaintEventHandler(this.pnlInclinacao_Paint);
//
@ -387,9 +464,10 @@ namespace AgroBase.Forms.Operacoes
//
this.lblDistanciaEsquerda.AutoSize = true;
this.lblDistanciaEsquerda.Font = new System.Drawing.Font("Mongolian Baiti", 9F, System.Drawing.FontStyle.Bold);
this.lblDistanciaEsquerda.Location = new System.Drawing.Point(12, 20);
this.lblDistanciaEsquerda.Location = new System.Drawing.Point(9, 16);
this.lblDistanciaEsquerda.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblDistanciaEsquerda.Name = "lblDistanciaEsquerda";
this.lblDistanciaEsquerda.Size = new System.Drawing.Size(228, 16);
this.lblDistanciaEsquerda.Size = new System.Drawing.Size(180, 13);
this.lblDistanciaEsquerda.TabIndex = 11;
this.lblDistanciaEsquerda.Text = "Distancia da Esquerda: 000 px";
//
@ -397,9 +475,10 @@ namespace AgroBase.Forms.Operacoes
//
this.lblDistanciaDireita.AutoSize = true;
this.lblDistanciaDireita.Font = new System.Drawing.Font("Mongolian Baiti", 9F, System.Drawing.FontStyle.Bold);
this.lblDistanciaDireita.Location = new System.Drawing.Point(253, 20);
this.lblDistanciaDireita.Location = new System.Drawing.Point(190, 16);
this.lblDistanciaDireita.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblDistanciaDireita.Name = "lblDistanciaDireita";
this.lblDistanciaDireita.Size = new System.Drawing.Size(211, 16);
this.lblDistanciaDireita.Size = new System.Drawing.Size(167, 13);
this.lblDistanciaDireita.TabIndex = 12;
this.lblDistanciaDireita.Text = "Distancia da Direita: 000 px";
//
@ -408,46 +487,40 @@ namespace AgroBase.Forms.Operacoes
this.pnlInferior.Controls.Add(this.lblUltimaLeituraRua);
this.pnlInferior.Controls.Add(this.lblUltimaLeituraSolo);
this.pnlInferior.Font = new System.Drawing.Font("Mongolian Baiti", 9F, System.Drawing.FontStyle.Bold);
this.pnlInferior.Location = new System.Drawing.Point(12, 793);
this.pnlInferior.Location = new System.Drawing.Point(9, 644);
this.pnlInferior.Margin = new System.Windows.Forms.Padding(2);
this.pnlInferior.Name = "pnlInferior";
this.pnlInferior.Size = new System.Drawing.Size(790, 50);
this.pnlInferior.Size = new System.Drawing.Size(592, 41);
this.pnlInferior.TabIndex = 13;
//
// lblUltimaLeituraRua
//
this.lblUltimaLeituraRua.AutoSize = true;
this.lblUltimaLeituraRua.Location = new System.Drawing.Point(3, 5);
this.lblUltimaLeituraRua.Location = new System.Drawing.Point(2, 4);
this.lblUltimaLeituraRua.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblUltimaLeituraRua.Name = "lblUltimaLeituraRua";
this.lblUltimaLeituraRua.Size = new System.Drawing.Size(251, 16);
this.lblUltimaLeituraRua.Size = new System.Drawing.Size(198, 13);
this.lblUltimaLeituraRua.TabIndex = 5;
this.lblUltimaLeituraRua.Text = "Ultima Leitura Rua: 00:00:00.000";
//
// lblUltimaLeituraSolo
//
this.lblUltimaLeituraSolo.AutoSize = true;
this.lblUltimaLeituraSolo.Location = new System.Drawing.Point(3, 30);
this.lblUltimaLeituraSolo.Location = new System.Drawing.Point(2, 24);
this.lblUltimaLeituraSolo.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblUltimaLeituraSolo.Name = "lblUltimaLeituraSolo";
this.lblUltimaLeituraSolo.Size = new System.Drawing.Size(255, 16);
this.lblUltimaLeituraSolo.Size = new System.Drawing.Size(202, 13);
this.lblUltimaLeituraSolo.TabIndex = 4;
this.lblUltimaLeituraSolo.Text = "Ultima Leitura Solo: 00:00:00.000";
//
// btnDesenharMapa
//
this.btnDesenharMapa.Location = new System.Drawing.Point(1241, 358);
this.btnDesenharMapa.Name = "btnDesenharMapa";
this.btnDesenharMapa.Size = new System.Drawing.Size(101, 23);
this.btnDesenharMapa.TabIndex = 14;
this.btnDesenharMapa.Text = "Desenhar";
this.btnDesenharMapa.UseVisualStyleBackColor = true;
this.btnDesenharMapa.Click += new System.EventHandler(this.btnDesenharMapa_Click);
//
// frmOperacaoSeguidorLinha
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1360, 855);
this.Controls.Add(this.btnDesenharMapa);
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(1020, 697);
this.Controls.Add(this.pnlInferior);
this.Controls.Add(this.btnCarregarMapa);
this.Controls.Add(this.lblDistanciaDireita);
this.Controls.Add(this.lblDistanciaEsquerda);
this.Controls.Add(this.pnlInclinacao);
@ -460,11 +533,14 @@ namespace AgroBase.Forms.Operacoes
this.Controls.Add(this.pnlAtuadores);
this.Controls.Add(this.pnlCameraCaminho);
this.Controls.Add(this.pnlCameraSolo);
this.Margin = new System.Windows.Forms.Padding(2);
this.Name = "frmOperacaoSeguidorLinha";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Operação Seguidor de Linha";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmOperacaoSeguidorLinha_FormClosing);
this.Load += new System.EventHandler(this.frmOperacaoSeguidorLinha_Load);
this.pnlCameraSolo.ResumeLayout(false);
this.pnlMapa.ResumeLayout(false);
this.pnlGraficos.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.chartGraficos)).EndInit();
this.pnlNiveis.ResumeLayout(false);
@ -498,11 +574,10 @@ namespace AgroBase.Forms.Operacoes
private System.Windows.Forms.ProgressBar pgbProgresso;
private System.Windows.Forms.Button btnIniciarOperacao;
private System.Windows.Forms.Button btnCarregarMapa;
private System.Windows.Forms.Label lblMapa;
private System.Windows.Forms.ComboBox cmbCameraCaminho;
private System.Windows.Forms.Label lblCameraCaminho;
private System.Windows.Forms.ComboBox cmbCameraSolo;
private System.Windows.Forms.Label lblCameraSolo;
private System.Windows.Forms.ComboBox cmbCameraSoloE;
private System.Windows.Forms.Label lblCameraSoloE;
private System.Windows.Forms.Label lblMapaCarregado;
private System.Windows.Forms.GroupBox gpbInformacoesGerais;
private System.Windows.Forms.Label lblBateriaConsumida;
@ -519,5 +594,9 @@ namespace AgroBase.Forms.Operacoes
private System.Windows.Forms.Label lblUltimaLeituraRua;
private System.Windows.Forms.Label lblUltimaLeituraSolo;
private System.Windows.Forms.Button btnDesenharMapa;
private System.Windows.Forms.Panel pnlCameraSoloD;
private System.Windows.Forms.Panel pnlCameraSoloE;
private System.Windows.Forms.ComboBox cmbCameraSoloD;
private System.Windows.Forms.Label lblCameraSoloD;
}
}

View File

@ -2,6 +2,7 @@
using AgroBase.Models;
using AgroBase.Models.Modules;
using AgroBase.Services;
using CefSharp;
using CefSharp.WinForms;
using System;
using System.Collections.Generic;
@ -20,12 +21,12 @@ namespace AgroBase.Forms.Operacoes
{
public partial class frmOperacaoSeguidorLinha : Form
{
private CameraService<CameraCoordenadasFrameModel> cameraSolo = new CameraService<CameraCoordenadasFrameModel>();
private ChromiumWebBrowser webSolo = null;
private string cameraSoloSelecionada = "";
private List<CameraSoloModel> CamerasSolo = new List<CameraSoloModel>();
private CameraService<CameraAnguloModel> cameraCaminho = new CameraService<CameraAnguloModel>();
private ChromiumWebBrowser webCaminho = null;
private string cameraCaminhoSelecionada = "";
private ChromiumWebBrowser webMapa = null;
private Timer tmrLeituras = new Timer() { Interval = 200 };
@ -53,7 +54,11 @@ namespace AgroBase.Forms.Operacoes
private void frmOperacaoSeguidorLinha_FormClosing(object sender, FormClosingEventArgs e)
{
tmrLeituras.Stop();
DesligarCameraSolo();
//DesligarCameraSoloE();
CamerasSolo.ForEach(Camera =>
{
DesligarCameraSolo(Camera);
});
DesligarCameraCaminho();
Variaveis.OperacaoEmAndamento.FinalizarOperacao();
}
@ -67,63 +72,47 @@ namespace AgroBase.Forms.Operacoes
AtualizarGrafico();
}
private void DesligarCameraSolo()
{
try
{
pnlCameraSolo.Controls.Remove(webSolo);
webSolo = null;
if (cameraSolo.socket != null)
{
cameraSolo.socket.Disconnect();
}
if (cameraSolo.pythonProcess != null)
{
cameraSolo.pythonProcess.Kill();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void DesligarCameraCaminho()
{
try
{
pnlCameraCaminho.Controls.Remove(webCaminho);
webCaminho = null;
if (cameraCaminho.socket != null)
{
cameraCaminho.socket.Disconnect();
}
if (cameraCaminho.pythonProcess != null)
{
cameraCaminho.pythonProcess.Kill();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void AtualizaListaCameras()
{
cameraSolo.selectedCamera = cmbCameraSolo.SelectedIndex > 0 ? cmbCameraSolo.SelectedIndex : 0;
cmbCameraSolo.Items.Clear();
cmbCameraSolo.Items.AddRange(cameraSolo.AtualizaListaCameras().ToArray());
if (cmbCameraSolo.Items.Count == 1)
var listaCameras = cameraCaminho.AtualizaListaCameras().ToArray();
var cameras = gpbOpcoes.Controls.OfType<ComboBox>().Where(x => x.Name.Contains("cmbCameraSolo")).ToList();
foreach (ComboBox cmb in cameras)
{
cameraSolo.selectedCamera = 0;
string CamNome = cmb.Name.Replace("cmbCameraSolo", "");
CameraSoloModel CameraSolo = CamerasSolo.FirstOrDefault(x => x.Nome == CamNome);
if (CameraSolo == null)
{
CameraSolo = new CameraSoloModel()
{
Nome = CamNome,
Posicao = CamerasSolo.Count(),
ArquivoLeitura = "verdes_" + CamNome + ".json",
browser = null,
camera = new CameraService<CameraCoordenadasFrameModel>(),
CameraSelecionada = "",
combo = cmb,
MaxLeituras = 10,
SocketPorta = (6535 + CamerasSolo.Count()).ToString(),
VideoPorta = (9080 + CamerasSolo.Count()).ToString(),
VideoUrl = "green_objects_" + CamNome,
panel = pnlCameraSolo.Controls.OfType<Panel>().Where(x => x.Name.Replace("pnl", "cmb") == cmb.Name).FirstOrDefault(),
};
CamerasSolo.Add(CameraSolo);
}
CameraSolo.combo.Items.Clear();
CameraSolo.combo.Items.AddRange(listaCameras);
if (CameraSolo.combo.Items.Count == 1)
{
CameraSolo.camera.selectedCamera = 0;
}
CameraSolo.combo.SelectedIndex = CameraSolo.camera.selectedCamera;
}
cmbCameraSolo.SelectedIndex = cameraSolo.selectedCamera;
cameraCaminho.selectedCamera = cmbCameraCaminho.SelectedIndex > 0 ? cmbCameraCaminho.SelectedIndex : 0;
cmbCameraCaminho.Items.Clear();
cmbCameraCaminho.Items.AddRange(cameraCaminho.AtualizaListaCameras().ToArray());
cmbCameraCaminho.Items.AddRange(listaCameras);
if (cmbCameraCaminho.Items.Count == 1)
{
cameraCaminho.selectedCamera = 0;
@ -134,36 +123,92 @@ namespace AgroBase.Forms.Operacoes
private void cmbCameraSolo_SelectedIndexChanged(object sender, EventArgs e)
{
if (cameraSoloSelecionada != "Sem vídeo" && cameraSoloSelecionada != "")
ComboBox cmb = (ComboBox)sender;
string CamNome = cmb.Name.Replace("cmbCameraSolo", "");
CameraSoloModel CameraSolo = CamerasSolo.FirstOrDefault(x => x.Nome == CamNome);
if (CameraSolo.CameraSelecionada != "Sem vídeo" && CameraSolo.CameraSelecionada != "")
{
cmbCameraCaminho.Items.Add(cameraSoloSelecionada);
cmbCameraCaminho.Items.Add(CameraSolo.CameraSelecionada);
CamerasSolo.Where(x => x.Nome != CamNome).ToList().ForEach(Camera =>
{
Camera.combo.Items.Add(CameraSolo.CameraSelecionada);
});
}
cameraSolo.selectedCamera = cmbCameraSolo.SelectedIndex;
if (cameraSolo.selectedCamera > 0)
CameraSolo.camera.selectedCamera = CameraSolo.combo.SelectedIndex;
DesligarCameraSolo(CameraSolo);
if (CameraSolo.camera.selectedCamera > 0)
{
DesligarCameraSolo();
IniciarCameraSolo();
IniciarCameraSolo(CameraSolo);
}
else
{
DesligarCameraSolo();
}
cameraSoloSelecionada = cmbCameraSolo.Text;
CameraSolo.CameraSelecionada = CameraSolo.combo.Text;
//btnIniciarOperacao.Enabled = cmbCameraSolo.SelectedIndex > 0 && cmbCameraCaminho.SelectedIndex > 0;
if (cameraSoloSelecionada != "Sem vídeo" && cameraSoloSelecionada != "")
if (CameraSolo.CameraSelecionada != "Sem vídeo" && CameraSolo.CameraSelecionada != "")
{
cmbCameraCaminho.Items.Remove(cameraSoloSelecionada);
cmbCameraCaminho.Items.Remove(CameraSolo.CameraSelecionada);
CamerasSolo.Where(x => x.Nome != CamNome).ToList().ForEach(Camera =>
{
Camera.combo.Items.Remove(CameraSolo.CameraSelecionada);
});
}
}
private void IniciarCameraSolo(CameraSoloModel CameraSolo)
{
CameraSolo.camera.IniciarCamera(
PythonService.ScriptWeedDetector,
new string[] { CameraSolo.MaxLeituras.ToString(), CameraSolo.VideoPorta, CameraSolo.VideoUrl, CameraSolo.ArquivoLeitura, "1", CameraSolo.SocketPorta },
CameraSolo.VideoPorta,
CameraSolo.VideoUrl,
CameraSolo.SocketPorta
);
if (CameraSolo.browser == null)
{
CameraSolo.browser = new ChromiumWebBrowser(CameraSolo.camera.URLcamera);
CameraSolo.panel.Controls.Add(CameraSolo.browser);
CameraSolo.browser.Dock = DockStyle.Fill;
}
}
private void DesligarCameraSolo(CameraSoloModel CameraSolo)
{
try
{
CameraSolo.panel.Controls.Remove(CameraSolo.browser);
CameraSolo.browser = null;
if (CameraSolo.camera.socket != null)
{
CameraSolo.camera.socket.Disconnect();
}
if (CameraSolo.camera.pythonProcess != null)
{
CameraSolo.camera.pythonProcess.Kill();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void cmbCameraCaminho_SelectedIndexChanged(object sender, EventArgs e)
{
if (cameraCaminhoSelecionada != "Sem vídeo" && cameraCaminhoSelecionada != "")
{
cmbCameraSolo.Items.Add(cameraCaminhoSelecionada);
//cmbCameraSoloE.Items.Add(cameraCaminhoSelecionada);
CamerasSolo.ForEach(Camera =>
{
Camera.combo.Items.Add(cameraCaminhoSelecionada);
});
}
cameraCaminho.selectedCamera = cmbCameraCaminho.SelectedIndex;
@ -180,38 +225,17 @@ namespace AgroBase.Forms.Operacoes
//btnIniciarOperacao.Enabled = cmbCameraSolo.SelectedIndex > 0 && cmbCameraCaminho.SelectedIndex > 0;
if (cameraCaminhoSelecionada != "Sem vídeo" && cameraCaminhoSelecionada != "" )
if (cameraCaminhoSelecionada != "Sem vídeo" && cameraCaminhoSelecionada != "")
{
cmbCameraSolo.Items.Remove(cameraCaminhoSelecionada);
cmbCameraSoloE.Items.Remove(cameraCaminhoSelecionada);
CamerasSolo.ForEach(Camera =>
{
Camera.combo.Items.Remove(cameraCaminhoSelecionada);
});
}
}
private void IniciarCameraSolo()
{
string ArquivoLeitura = "verdes.json";
int MaxLeituras = 10;
string VideoPorta = "8080";
string VideoUrl = "green_objects";
string SocketPorta = "6535";
cameraSolo.ArquivoLeitura = ArquivoLeitura;
cameraSolo.IniciarCamera(
PythonService.ScriptGreenDetector,
new string[] { MaxLeituras.ToString(), VideoPorta, VideoUrl, ArquivoLeitura, "1", SocketPorta },
VideoPorta,
VideoUrl,
SocketPorta
);
if (webSolo == null)
{
webSolo = new ChromiumWebBrowser(cameraSolo.URLcamera);
pnlCameraSolo.Controls.Add(webSolo);
webSolo.Dock = DockStyle.Fill;
}
}
private void IniciarCameraCaminho()
{
string ArquivoLeitura = "angulos.json";
@ -237,6 +261,34 @@ namespace AgroBase.Forms.Operacoes
}
}
private void DesligarCameraCaminho()
{
try
{
pnlCameraCaminho.Controls.Remove(webCaminho);
webCaminho = null;
if (cameraCaminho.socket != null)
{
cameraCaminho.socket.Disconnect();
}
if (cameraCaminho.pythonProcess != null)
{
cameraCaminho.pythonProcess.Kill();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void btnCarregarMapa_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
@ -267,7 +319,8 @@ namespace AgroBase.Forms.Operacoes
if (tmrLeituras.Enabled == true)
{
btnIniciarOperacao.Text = "Iniciar Operação";
cmbCameraSolo.Enabled = true;
cmbCameraSoloE.Enabled = true;
cmbCameraSoloD.Enabled = true;
cmbCameraCaminho.Enabled = true;
Variaveis.OperacaoEmAndamento.FinalizarOperacao();
@ -278,7 +331,8 @@ namespace AgroBase.Forms.Operacoes
else
{
btnIniciarOperacao.Text = "Finalizar Operação";
cmbCameraSolo.Enabled = false;
cmbCameraSoloE.Enabled = false;
cmbCameraSoloD.Enabled = false;
cmbCameraCaminho.Enabled = false;
Variaveis.OperacaoEmAndamento.IniciarOperacao();
@ -291,12 +345,13 @@ namespace AgroBase.Forms.Operacoes
private void TmrLeituras_Tick(object sender, EventArgs e)
{
if (cameraSolo.socket != null && cameraSolo.socket.DadosRecebidos.Any())
/*
if (camSoloE.socket != null && camSoloE.socket.DadosRecebidos.Any())
{
var leitura = cameraSolo.socket.DadosRecebidos.Last();
var leitura = camSoloE.socket.DadosRecebidos.Last();
var Verdes = leitura.objetos.ToList();
int intervaloPorBico = Convert.ToInt32(cameraSolo.socket.DadosRecebidos.First().x_max) / Atuador.Dados.QuantidadeBicos;
int inicioBarraPulverizadora = Convert.ToInt32(cameraSolo.socket.DadosRecebidos.First().y_max * (1 - Atuador.Dados.PercentualInicioPulverizacao));
int intervaloPorBico = Convert.ToInt32(camSoloE.socket.DadosRecebidos.First().x_max) / Atuador.Dados.QuantidadeBicos;
int inicioBarraPulverizadora = Convert.ToInt32(camSoloE.socket.DadosRecebidos.First().y_max * (1 - Atuador.Dados.PercentualInicioPulverizacao));
List<bool> BicosAnteriores = new List<bool>();
// Inicialize todos os bicos como inativos antes de verificar os objetos verdes
@ -348,6 +403,13 @@ namespace AgroBase.Forms.Operacoes
Variaveis.OperacaoEmAndamento.Controle.RPM_Max :
Variaveis.OperacaoEmAndamento.Controle.RPM_Min;
}
*/
CamerasSolo.ForEach(CameraSolo =>
{
AtualizaLeituraCameraSolo(CameraSolo);
});
if (cameraCaminho.socket != null && cameraCaminho.socket.DadosRecebidos.Any())
{
var leitura = cameraCaminho.socket != null && cameraCaminho.socket.DadosRecebidos.Any() ?
@ -359,7 +421,10 @@ namespace AgroBase.Forms.Operacoes
lblUltimaLeituraRua.Text = "Ultima Leitura Rua: " + FuncoesGlobais.TimestampToDate(leitura.timestamp);
pnlInclinacao.Invalidate();
Variaveis.OperacaoEmAndamento.Controle.Angulo = leitura.angulo;
Variaveis.OperacaoEmAndamento.Controle.Angulo =
leitura.angulo > Variaveis.OperacaoEmAndamento.Controle.Angulo_Max ? Variaveis.OperacaoEmAndamento.Controle.Angulo_Max :
leitura.angulo < Variaveis.OperacaoEmAndamento.Controle.Angulo_Min ? Variaveis.OperacaoEmAndamento.Controle.Angulo_Min :
leitura.angulo;
}
AtualizarGrafico();
@ -368,6 +433,71 @@ namespace AgroBase.Forms.Operacoes
AtualizarInformacoesGerais();
}
private void AtualizaLeituraCameraSolo(CameraSoloModel CameraSolo)
{
if (CameraSolo.camera.socket != null && CameraSolo.camera.socket.DadosRecebidos.Any())
{
int BicosPorCamera = Atuador.Dados.QuantidadeBicos / CamerasSolo.Count();
var leitura = CameraSolo.camera.socket.DadosRecebidos.Last();
var Verdes = leitura.objetos.ToList();
int intervaloPorBico = Convert.ToInt32(CameraSolo.camera.socket.DadosRecebidos.First().x_max) / BicosPorCamera;
int inicioBarraPulverizadora = Convert.ToInt32(CameraSolo.camera.socket.DadosRecebidos.First().y_max * (1 - Atuador.Dados.PercentualInicioPulverizacao));
List<bool> BicosAnteriores = new List<bool>();
// Inicialize todos os bicos como inativos antes de verificar os objetos verdes
for (int i = 0; i < BicosPorCamera; i++)
{
int iBico = i + (CameraSolo.Posicao * BicosPorCamera);
BicosAnteriores.Add(Atuador.Dados.BicosPulverizadores[iBico].Atuado);
Atuador.Dados.BicosPulverizadores[iBico].Atuado = false;
}
foreach (var verde in Verdes)
{
// Calcule a posição final (y + altura) do objeto verde
int posicaoFinalVerdeY = verde.y + verde.altura;
if (posicaoFinalVerdeY > inicioBarraPulverizadora)
{
// Calcule a posição final (x + largura) do objeto verde
int posicaoFinalVerdeX = verde.x + verde.largura;
// Para cada objeto verde, verifique se ele está dentro do intervalo de algum bico e atue-o
for (int i = 0; i < BicosPorCamera; i++)
{
// Determina o intervalo no eixo x para o bico atual
int limiteInferior = intervaloPorBico * i;
int limiteSuperior = limiteInferior + intervaloPorBico;
// Verifica se o objeto 'verde' está dentro do intervalo deste bico
// A condição foi ajustada para verificar se qualquer parte do objeto verde cruza com o intervalo do bico
if (verde.x < limiteSuperior && posicaoFinalVerdeX > limiteInferior)
{
int iBico = i + (CameraSolo.Posicao * BicosPorCamera);
Atuador.Dados.BicosPulverizadores[iBico].Atuado = true;
}
}
}
}
for (int i = 0; i < BicosPorCamera; i++)
{
int iBico = i + (CameraSolo.Posicao * BicosPorCamera);
if (Atuador.Dados.BicosPulverizadores[iBico].Atuado && BicosAnteriores[i] != Atuador.Dados.BicosPulverizadores[iBico].Atuado)
{
Variaveis.OperacaoEmAndamento.AtuacoesPorBico[iBico]++;
}
}
lblUltimaLeituraSolo.Text = "Ultima Leitura Solo: " + FuncoesGlobais.TimestampToDate(leitura.timestamp);
pnlAtuadores.Invalidate();
Variaveis.OperacaoEmAndamento.Controle.BicosAtuados = Atuador.Dados.BicosPulverizadores;
Variaveis.OperacaoEmAndamento.Controle.RPM = !Verdes.Any() ?
Variaveis.OperacaoEmAndamento.Controle.RPM_Max :
Variaveis.OperacaoEmAndamento.Controle.RPM_Min;
}
}
private void pnlAtuadores_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
@ -466,12 +596,12 @@ namespace AgroBase.Forms.Operacoes
Minimo = Logs.Min(x => x.Velocidade) < Minimo ? Logs.Min(x => x.Velocidade) : Minimo;
Maximo = Logs.Min(x => x.Velocidade) > Maximo ? Logs.Min(x => x.Velocidade) : Maximo;
var serieRPM = new Series("RPM: " + (Log != null ? Log.RPM : 0));
serieRPM.Points.DataBindXY(Momentos, Logs.Select(x => x.RPM).ToList());
serieRPM.ChartType = SeriesChartType.Spline;
chart.Series.Add(serieRPM);
Minimo = Logs.Min(x => x.RPM) < Minimo ? Logs.Min(x => x.RPM) : Minimo;
Maximo = Logs.Max(x => x.RPM) > Maximo ? Logs.Max(x => x.RPM) : Maximo;
//var serieRPM = new Series("RPM: " + (Log != null ? Log.RPM : 0));
//serieRPM.Points.DataBindXY(Momentos, Logs.Select(x => x.RPM).ToList());
//serieRPM.ChartType = SeriesChartType.Spline;
//chart.Series.Add(serieRPM);
//Minimo = Logs.Min(x => x.RPM) < Minimo ? Logs.Min(x => x.RPM) : Minimo;
//Maximo = Logs.Max(x => x.RPM) > Maximo ? Logs.Max(x => x.RPM) : Maximo;
var seriePotencia = new Series("Potencia: " + (Log != null ? Log.Potencia : 0));
seriePotencia.Points.DataBindXY(Momentos, Logs.Select(x => x.Potencia).ToList());
@ -499,8 +629,8 @@ namespace AgroBase.Forms.Operacoes
private void AtualizarInformacoesGerais()
{
lblDistanciaPercorrida.Text = "Distancia Percorrida: " + Variaveis.OperacaoEmAndamento.DistanciaPercorrida + " m";
TimeSpan tempo = TimeSpan.FromTicks(Variaveis.OperacaoEmAndamento.TimestampInicio - (Variaveis.OperacaoEmAndamento.TimestampFim > 0 ? Variaveis.OperacaoEmAndamento.TimestampFim : DateTime.Now.Ticks));
lblTempoOperacao.Text = "Tempo de Operação: " + tempo.Hours + ":" + tempo.Minutes + ":" + tempo.Seconds;
TimeSpan tempo = TimeSpan.FromTicks((Variaveis.OperacaoEmAndamento.TimestampFim > 0 ? Variaveis.OperacaoEmAndamento.TimestampFim : DateTime.Now.Ticks) - Variaveis.OperacaoEmAndamento.TimestampInicio);
lblTempoOperacao.Text = "Tempo de Operação: " + tempo.Hours.ToString("00") + ":" + tempo.Minutes.ToString("00") + ":" + tempo.Seconds.ToString("00");
lblVelocidadeMedia.Text = "Velocidade Média: " + Variaveis.OperacaoEmAndamento.VelocidadeMedia.ToString("0.00") + " km/h";
lblErvasIdentificadas.Text = "Ervas Identificadas: " + Variaveis.OperacaoEmAndamento.ErvasIdentificadas.ToString("000");
lblErvasIdentificadas.Text = "Herbicida Aplicado: " + Variaveis.OperacaoEmAndamento.HerbicidaConsumido.ToString("0.000") + " L";
@ -515,9 +645,13 @@ namespace AgroBase.Forms.Operacoes
}
private void pnlInclinacao_Paint(object sender, PaintEventArgs e)
{
try
{
DesenharInclinacao((Panel)sender, e);
}
catch { }
}
private void DesenharInclinacao(Panel pnlBussola, PaintEventArgs e)
{
@ -641,5 +775,6 @@ namespace AgroBase.Forms.Operacoes
//angle = cameraCaminho.socket != null && cameraCaminho.socket.DadosRecebidos.Any() ? (float)cameraCaminho.socket.DadosRecebidos.Last().angulo : 0;
UpdatePath(angle, distance);
}
}
}

View File

@ -0,0 +1,592 @@
namespace AgroBase.Forms.Operacoes
{
partial class frmParametrizacaoOperacao
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cmbOperacao = new System.Windows.Forms.ComboBox();
this.lblOperacao = new System.Windows.Forms.Label();
this.gpbModulos = new System.Windows.Forms.GroupBox();
this.gpbP_Gps = new System.Windows.Forms.GroupBox();
this.gpbP_Sen = new System.Windows.Forms.GroupBox();
this.gpbP_Atu = new System.Windows.Forms.GroupBox();
this.nudQtdCameras = new System.Windows.Forms.NumericUpDown();
this.lblQtdCameras = new System.Windows.Forms.Label();
this.nudQtdBicos = new System.Windows.Forms.NumericUpDown();
this.lblQtdBicos = new System.Windows.Forms.Label();
this.gpbP_Dir = new System.Windows.Forms.GroupBox();
this.nudVelocidadeMP = new System.Windows.Forms.NumericUpDown();
this.lblVelocidadePercentual = new System.Windows.Forms.Label();
this.lblVelocidadeMP = new System.Windows.Forms.Label();
this.nudAnguloMaximo = new System.Windows.Forms.NumericUpDown();
this.lblAngulo = new System.Windows.Forms.Label();
this.gpbP_Mov = new System.Windows.Forms.GroupBox();
this.nudVelocidadeComErvas = new System.Windows.Forms.NumericUpDown();
this.lblKmhCErvas = new System.Windows.Forms.Label();
this.lblVelocidadeComErvas = new System.Windows.Forms.Label();
this.nudVelocidadeSemErvas = new System.Windows.Forms.NumericUpDown();
this.lblKmhSErvas = new System.Windows.Forms.Label();
this.lblVelocidadeSemErvas = new System.Windows.Forms.Label();
this.chbO_Gps = new System.Windows.Forms.CheckBox();
this.chbO_Sen = new System.Windows.Forms.CheckBox();
this.chbO_Atu = new System.Windows.Forms.CheckBox();
this.chbO_Dir = new System.Windows.Forms.CheckBox();
this.chbO_Mov = new System.Windows.Forms.CheckBox();
this.chbD_Gps = new System.Windows.Forms.CheckBox();
this.chbD_Sen = new System.Windows.Forms.CheckBox();
this.chbD_Mov = new System.Windows.Forms.CheckBox();
this.chbD_Atu = new System.Windows.Forms.CheckBox();
this.chbD_Dir = new System.Windows.Forms.CheckBox();
this.btnCarregar = new System.Windows.Forms.Button();
this.btnSalvar = new System.Windows.Forms.Button();
this.nudAnguloMinimo = new System.Windows.Forms.NumericUpDown();
this.chbSalvar = new System.Windows.Forms.CheckBox();
this.gpbModulos.SuspendLayout();
this.gpbP_Atu.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudQtdCameras)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nudQtdBicos)).BeginInit();
this.gpbP_Dir.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudVelocidadeMP)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nudAnguloMaximo)).BeginInit();
this.gpbP_Mov.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudVelocidadeComErvas)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nudVelocidadeSemErvas)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nudAnguloMinimo)).BeginInit();
this.SuspendLayout();
//
// cmbOperacao
//
this.cmbOperacao.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbOperacao.Enabled = false;
this.cmbOperacao.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmbOperacao.FormattingEnabled = true;
this.cmbOperacao.Location = new System.Drawing.Point(15, 39);
this.cmbOperacao.Margin = new System.Windows.Forms.Padding(6);
this.cmbOperacao.Name = "cmbOperacao";
this.cmbOperacao.Size = new System.Drawing.Size(417, 32);
this.cmbOperacao.TabIndex = 0;
//
// lblOperacao
//
this.lblOperacao.AutoSize = true;
this.lblOperacao.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblOperacao.Location = new System.Drawing.Point(15, 9);
this.lblOperacao.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this.lblOperacao.Name = "lblOperacao";
this.lblOperacao.Size = new System.Drawing.Size(175, 24);
this.lblOperacao.TabIndex = 1;
this.lblOperacao.Text = "Modo de Operação";
//
// gpbModulos
//
this.gpbModulos.Controls.Add(this.gpbP_Gps);
this.gpbModulos.Controls.Add(this.gpbP_Sen);
this.gpbModulos.Controls.Add(this.gpbP_Atu);
this.gpbModulos.Controls.Add(this.gpbP_Dir);
this.gpbModulos.Controls.Add(this.gpbP_Mov);
this.gpbModulos.Controls.Add(this.chbO_Gps);
this.gpbModulos.Controls.Add(this.chbO_Sen);
this.gpbModulos.Controls.Add(this.chbO_Atu);
this.gpbModulos.Controls.Add(this.chbO_Dir);
this.gpbModulos.Controls.Add(this.chbO_Mov);
this.gpbModulos.Controls.Add(this.chbD_Gps);
this.gpbModulos.Controls.Add(this.chbD_Sen);
this.gpbModulos.Controls.Add(this.chbD_Mov);
this.gpbModulos.Controls.Add(this.chbD_Atu);
this.gpbModulos.Controls.Add(this.chbD_Dir);
this.gpbModulos.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.gpbModulos.Location = new System.Drawing.Point(15, 83);
this.gpbModulos.Margin = new System.Windows.Forms.Padding(6);
this.gpbModulos.Name = "gpbModulos";
this.gpbModulos.Padding = new System.Windows.Forms.Padding(6);
this.gpbModulos.Size = new System.Drawing.Size(990, 289);
this.gpbModulos.TabIndex = 3;
this.gpbModulos.TabStop = false;
this.gpbModulos.Text = "Módulos necessários para executar a operação";
//
// gpbP_Gps
//
this.gpbP_Gps.Location = new System.Drawing.Point(792, 105);
this.gpbP_Gps.Name = "gpbP_Gps";
this.gpbP_Gps.Size = new System.Drawing.Size(190, 168);
this.gpbP_Gps.TabIndex = 12;
this.gpbP_Gps.TabStop = false;
this.gpbP_Gps.Text = "Ajustes";
//
// gpbP_Sen
//
this.gpbP_Sen.Location = new System.Drawing.Point(596, 105);
this.gpbP_Sen.Name = "gpbP_Sen";
this.gpbP_Sen.Size = new System.Drawing.Size(190, 168);
this.gpbP_Sen.TabIndex = 12;
this.gpbP_Sen.TabStop = false;
this.gpbP_Sen.Text = "Ajustes";
//
// gpbP_Atu
//
this.gpbP_Atu.Controls.Add(this.nudQtdCameras);
this.gpbP_Atu.Controls.Add(this.lblQtdCameras);
this.gpbP_Atu.Controls.Add(this.nudQtdBicos);
this.gpbP_Atu.Controls.Add(this.lblQtdBicos);
this.gpbP_Atu.Location = new System.Drawing.Point(400, 105);
this.gpbP_Atu.Name = "gpbP_Atu";
this.gpbP_Atu.Size = new System.Drawing.Size(190, 168);
this.gpbP_Atu.TabIndex = 12;
this.gpbP_Atu.TabStop = false;
this.gpbP_Atu.Text = "Ajustes";
//
// nudQtdCameras
//
this.nudQtdCameras.Location = new System.Drawing.Point(10, 126);
this.nudQtdCameras.Name = "nudQtdCameras";
this.nudQtdCameras.Size = new System.Drawing.Size(120, 29);
this.nudQtdCameras.TabIndex = 11;
this.nudQtdCameras.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// lblQtdCameras
//
this.lblQtdCameras.AutoSize = true;
this.lblQtdCameras.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblQtdCameras.Location = new System.Drawing.Point(6, 99);
this.lblQtdCameras.Name = "lblQtdCameras";
this.lblQtdCameras.Size = new System.Drawing.Size(174, 20);
this.lblQtdCameras.TabIndex = 9;
this.lblQtdCameras.Text = "Qtde de câmeras solo";
//
// nudQtdBicos
//
this.nudQtdBicos.Location = new System.Drawing.Point(10, 67);
this.nudQtdBicos.Name = "nudQtdBicos";
this.nudQtdBicos.Size = new System.Drawing.Size(120, 29);
this.nudQtdBicos.TabIndex = 8;
this.nudQtdBicos.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// lblQtdBicos
//
this.lblQtdBicos.AutoSize = true;
this.lblQtdBicos.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblQtdBicos.Location = new System.Drawing.Point(6, 40);
this.lblQtdBicos.Name = "lblQtdBicos";
this.lblQtdBicos.Size = new System.Drawing.Size(113, 20);
this.lblQtdBicos.TabIndex = 6;
this.lblQtdBicos.Text = "Qtde de bicos";
//
// gpbP_Dir
//
this.gpbP_Dir.Controls.Add(this.nudAnguloMinimo);
this.gpbP_Dir.Controls.Add(this.nudVelocidadeMP);
this.gpbP_Dir.Controls.Add(this.lblVelocidadePercentual);
this.gpbP_Dir.Controls.Add(this.lblVelocidadeMP);
this.gpbP_Dir.Controls.Add(this.nudAnguloMaximo);
this.gpbP_Dir.Controls.Add(this.lblAngulo);
this.gpbP_Dir.Location = new System.Drawing.Point(204, 105);
this.gpbP_Dir.Name = "gpbP_Dir";
this.gpbP_Dir.Size = new System.Drawing.Size(190, 168);
this.gpbP_Dir.TabIndex = 12;
this.gpbP_Dir.TabStop = false;
this.gpbP_Dir.Text = "Ajustes";
//
// nudVelocidadeMP
//
this.nudVelocidadeMP.Location = new System.Drawing.Point(10, 126);
this.nudVelocidadeMP.Name = "nudVelocidadeMP";
this.nudVelocidadeMP.Size = new System.Drawing.Size(120, 29);
this.nudVelocidadeMP.TabIndex = 11;
this.nudVelocidadeMP.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// lblVelocidadePercentual
//
this.lblVelocidadePercentual.AutoSize = true;
this.lblVelocidadePercentual.Location = new System.Drawing.Point(136, 128);
this.lblVelocidadePercentual.Name = "lblVelocidadePercentual";
this.lblVelocidadePercentual.Size = new System.Drawing.Size(25, 24);
this.lblVelocidadePercentual.TabIndex = 10;
this.lblVelocidadePercentual.Text = "%";
//
// lblVelocidadeMP
//
this.lblVelocidadeMP.AutoSize = true;
this.lblVelocidadeMP.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblVelocidadeMP.Location = new System.Drawing.Point(6, 99);
this.lblVelocidadeMP.Name = "lblVelocidadeMP";
this.lblVelocidadeMP.Size = new System.Drawing.Size(91, 20);
this.lblVelocidadeMP.TabIndex = 9;
this.lblVelocidadeMP.Text = "Velocidade";
//
// nudAnguloMaximo
//
this.nudAnguloMaximo.Location = new System.Drawing.Point(10, 67);
this.nudAnguloMaximo.Maximum = new decimal(new int[] {
90,
0,
0,
0});
this.nudAnguloMaximo.Minimum = new decimal(new int[] {
90,
0,
0,
-2147483648});
this.nudAnguloMaximo.Name = "nudAnguloMaximo";
this.nudAnguloMaximo.Size = new System.Drawing.Size(72, 29);
this.nudAnguloMaximo.TabIndex = 8;
this.nudAnguloMaximo.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// lblAngulo
//
this.lblAngulo.AutoSize = true;
this.lblAngulo.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblAngulo.Location = new System.Drawing.Point(6, 40);
this.lblAngulo.Name = "lblAngulo";
this.lblAngulo.Size = new System.Drawing.Size(142, 20);
this.lblAngulo.TabIndex = 6;
this.lblAngulo.Text = "Angulo Máx e Mín";
//
// gpbP_Mov
//
this.gpbP_Mov.Controls.Add(this.nudVelocidadeComErvas);
this.gpbP_Mov.Controls.Add(this.lblKmhCErvas);
this.gpbP_Mov.Controls.Add(this.lblVelocidadeComErvas);
this.gpbP_Mov.Controls.Add(this.nudVelocidadeSemErvas);
this.gpbP_Mov.Controls.Add(this.lblKmhSErvas);
this.gpbP_Mov.Controls.Add(this.lblVelocidadeSemErvas);
this.gpbP_Mov.Location = new System.Drawing.Point(8, 105);
this.gpbP_Mov.Name = "gpbP_Mov";
this.gpbP_Mov.Size = new System.Drawing.Size(190, 168);
this.gpbP_Mov.TabIndex = 10;
this.gpbP_Mov.TabStop = false;
this.gpbP_Mov.Text = "Ajustes";
//
// nudVelocidadeComErvas
//
this.nudVelocidadeComErvas.Location = new System.Drawing.Point(10, 126);
this.nudVelocidadeComErvas.Name = "nudVelocidadeComErvas";
this.nudVelocidadeComErvas.Size = new System.Drawing.Size(73, 29);
this.nudVelocidadeComErvas.TabIndex = 11;
this.nudVelocidadeComErvas.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.nudVelocidadeComErvas.ValueChanged += new System.EventHandler(this.nudVelocidadeComErvas_ValueChanged);
//
// lblKmhCErvas
//
this.lblKmhCErvas.AutoSize = true;
this.lblKmhCErvas.Location = new System.Drawing.Point(89, 128);
this.lblKmhCErvas.Name = "lblKmhCErvas";
this.lblKmhCErvas.Size = new System.Drawing.Size(94, 24);
this.lblKmhCErvas.TabIndex = 10;
this.lblKmhCErvas.Text = "0,00 Km/h";
//
// lblVelocidadeComErvas
//
this.lblVelocidadeComErvas.AutoSize = true;
this.lblVelocidadeComErvas.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblVelocidadeComErvas.Location = new System.Drawing.Point(6, 99);
this.lblVelocidadeComErvas.Name = "lblVelocidadeComErvas";
this.lblVelocidadeComErvas.Size = new System.Drawing.Size(174, 20);
this.lblVelocidadeComErvas.TabIndex = 9;
this.lblVelocidadeComErvas.Text = "Velocidade com ervas";
//
// nudVelocidadeSemErvas
//
this.nudVelocidadeSemErvas.Location = new System.Drawing.Point(10, 67);
this.nudVelocidadeSemErvas.Name = "nudVelocidadeSemErvas";
this.nudVelocidadeSemErvas.Size = new System.Drawing.Size(73, 29);
this.nudVelocidadeSemErvas.TabIndex = 8;
this.nudVelocidadeSemErvas.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.nudVelocidadeSemErvas.ValueChanged += new System.EventHandler(this.nudVelocidadeSemErvas_ValueChanged);
//
// lblKmhSErvas
//
this.lblKmhSErvas.AutoSize = true;
this.lblKmhSErvas.Location = new System.Drawing.Point(89, 69);
this.lblKmhSErvas.Name = "lblKmhSErvas";
this.lblKmhSErvas.Size = new System.Drawing.Size(94, 24);
this.lblKmhSErvas.TabIndex = 7;
this.lblKmhSErvas.Text = "0,00 Km/h";
//
// lblVelocidadeSemErvas
//
this.lblVelocidadeSemErvas.AutoSize = true;
this.lblVelocidadeSemErvas.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblVelocidadeSemErvas.Location = new System.Drawing.Point(6, 40);
this.lblVelocidadeSemErvas.Name = "lblVelocidadeSemErvas";
this.lblVelocidadeSemErvas.Size = new System.Drawing.Size(174, 20);
this.lblVelocidadeSemErvas.TabIndex = 6;
this.lblVelocidadeSemErvas.Text = "Velocidade sem ervas";
//
// chbO_Gps
//
this.chbO_Gps.AutoSize = true;
this.chbO_Gps.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.chbO_Gps.Location = new System.Drawing.Point(802, 74);
this.chbO_Gps.Margin = new System.Windows.Forms.Padding(6);
this.chbO_Gps.Name = "chbO_Gps";
this.chbO_Gps.Size = new System.Drawing.Size(86, 22);
this.chbO_Gps.TabIndex = 9;
this.chbO_Gps.Text = "Opcional";
this.chbO_Gps.UseVisualStyleBackColor = true;
this.chbO_Gps.CheckedChanged += new System.EventHandler(this.chbO_CheckedChanged);
//
// chbO_Sen
//
this.chbO_Sen.AutoSize = true;
this.chbO_Sen.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.chbO_Sen.Location = new System.Drawing.Point(606, 74);
this.chbO_Sen.Margin = new System.Windows.Forms.Padding(6);
this.chbO_Sen.Name = "chbO_Sen";
this.chbO_Sen.Size = new System.Drawing.Size(86, 22);
this.chbO_Sen.TabIndex = 8;
this.chbO_Sen.Text = "Opcional";
this.chbO_Sen.UseVisualStyleBackColor = true;
this.chbO_Sen.CheckedChanged += new System.EventHandler(this.chbO_CheckedChanged);
//
// chbO_Atu
//
this.chbO_Atu.AutoSize = true;
this.chbO_Atu.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.chbO_Atu.Location = new System.Drawing.Point(410, 74);
this.chbO_Atu.Margin = new System.Windows.Forms.Padding(6);
this.chbO_Atu.Name = "chbO_Atu";
this.chbO_Atu.Size = new System.Drawing.Size(86, 22);
this.chbO_Atu.TabIndex = 7;
this.chbO_Atu.Text = "Opcional";
this.chbO_Atu.UseVisualStyleBackColor = true;
this.chbO_Atu.CheckedChanged += new System.EventHandler(this.chbO_CheckedChanged);
//
// chbO_Dir
//
this.chbO_Dir.AutoSize = true;
this.chbO_Dir.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.chbO_Dir.Location = new System.Drawing.Point(214, 74);
this.chbO_Dir.Margin = new System.Windows.Forms.Padding(6);
this.chbO_Dir.Name = "chbO_Dir";
this.chbO_Dir.Size = new System.Drawing.Size(86, 22);
this.chbO_Dir.TabIndex = 6;
this.chbO_Dir.Text = "Opcional";
this.chbO_Dir.UseVisualStyleBackColor = true;
this.chbO_Dir.CheckedChanged += new System.EventHandler(this.chbO_CheckedChanged);
//
// chbO_Mov
//
this.chbO_Mov.AutoSize = true;
this.chbO_Mov.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.chbO_Mov.Location = new System.Drawing.Point(18, 74);
this.chbO_Mov.Margin = new System.Windows.Forms.Padding(6);
this.chbO_Mov.Name = "chbO_Mov";
this.chbO_Mov.Size = new System.Drawing.Size(86, 22);
this.chbO_Mov.TabIndex = 5;
this.chbO_Mov.Text = "Opcional";
this.chbO_Mov.UseVisualStyleBackColor = true;
this.chbO_Mov.CheckedChanged += new System.EventHandler(this.chbO_CheckedChanged);
//
// chbD_Gps
//
this.chbD_Gps.AutoSize = true;
this.chbD_Gps.Location = new System.Drawing.Point(802, 34);
this.chbD_Gps.Margin = new System.Windows.Forms.Padding(6);
this.chbD_Gps.Name = "chbD_Gps";
this.chbD_Gps.Size = new System.Drawing.Size(67, 28);
this.chbD_Gps.TabIndex = 4;
this.chbD_Gps.Text = "GPS";
this.chbD_Gps.UseVisualStyleBackColor = true;
this.chbD_Gps.CheckedChanged += new System.EventHandler(this.chbD_CheckedChanged);
//
// chbD_Sen
//
this.chbD_Sen.AutoSize = true;
this.chbD_Sen.Location = new System.Drawing.Point(606, 34);
this.chbD_Sen.Margin = new System.Windows.Forms.Padding(6);
this.chbD_Sen.Name = "chbD_Sen";
this.chbD_Sen.Size = new System.Drawing.Size(156, 28);
this.chbD_Sen.TabIndex = 3;
this.chbD_Sen.Text = "Sensoriamento";
this.chbD_Sen.UseVisualStyleBackColor = true;
this.chbD_Sen.CheckedChanged += new System.EventHandler(this.chbD_CheckedChanged);
//
// chbD_Mov
//
this.chbD_Mov.AutoSize = true;
this.chbD_Mov.Location = new System.Drawing.Point(18, 34);
this.chbD_Mov.Margin = new System.Windows.Forms.Padding(6);
this.chbD_Mov.Name = "chbD_Mov";
this.chbD_Mov.Size = new System.Drawing.Size(152, 28);
this.chbD_Mov.TabIndex = 0;
this.chbD_Mov.Text = "Movimentação";
this.chbD_Mov.UseVisualStyleBackColor = true;
this.chbD_Mov.CheckedChanged += new System.EventHandler(this.chbD_CheckedChanged);
//
// chbD_Atu
//
this.chbD_Atu.AutoSize = true;
this.chbD_Atu.Location = new System.Drawing.Point(410, 34);
this.chbD_Atu.Margin = new System.Windows.Forms.Padding(6);
this.chbD_Atu.Name = "chbD_Atu";
this.chbD_Atu.Size = new System.Drawing.Size(95, 28);
this.chbD_Atu.TabIndex = 2;
this.chbD_Atu.Text = "Atuador";
this.chbD_Atu.UseVisualStyleBackColor = true;
this.chbD_Atu.CheckedChanged += new System.EventHandler(this.chbD_CheckedChanged);
//
// chbD_Dir
//
this.chbD_Dir.AutoSize = true;
this.chbD_Dir.Location = new System.Drawing.Point(214, 34);
this.chbD_Dir.Margin = new System.Windows.Forms.Padding(6);
this.chbD_Dir.Name = "chbD_Dir";
this.chbD_Dir.Size = new System.Drawing.Size(113, 28);
this.chbD_Dir.TabIndex = 1;
this.chbD_Dir.Text = "Direcional";
this.chbD_Dir.UseVisualStyleBackColor = true;
this.chbD_Dir.CheckedChanged += new System.EventHandler(this.chbD_CheckedChanged);
//
// btnCarregar
//
this.btnCarregar.Location = new System.Drawing.Point(569, 38);
this.btnCarregar.Margin = new System.Windows.Forms.Padding(6);
this.btnCarregar.Name = "btnCarregar";
this.btnCarregar.Size = new System.Drawing.Size(138, 32);
this.btnCarregar.TabIndex = 5;
this.btnCarregar.Text = "Carregar";
this.btnCarregar.UseVisualStyleBackColor = true;
this.btnCarregar.Click += new System.EventHandler(this.btnCarregar_Click);
//
// btnSalvar
//
this.btnSalvar.Location = new System.Drawing.Point(867, 38);
this.btnSalvar.Margin = new System.Windows.Forms.Padding(6);
this.btnSalvar.Name = "btnSalvar";
this.btnSalvar.Size = new System.Drawing.Size(138, 32);
this.btnSalvar.TabIndex = 6;
this.btnSalvar.Text = "Salvar";
this.btnSalvar.UseVisualStyleBackColor = true;
this.btnSalvar.Click += new System.EventHandler(this.btnSalvar_Click);
//
// nudAnguloMinimo
//
this.nudAnguloMinimo.Location = new System.Drawing.Point(102, 67);
this.nudAnguloMinimo.Maximum = new decimal(new int[] {
90,
0,
0,
0});
this.nudAnguloMinimo.Minimum = new decimal(new int[] {
90,
0,
0,
-2147483648});
this.nudAnguloMinimo.Name = "nudAnguloMinimo";
this.nudAnguloMinimo.Size = new System.Drawing.Size(72, 29);
this.nudAnguloMinimo.TabIndex = 12;
this.nudAnguloMinimo.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// chbSalvar
//
this.chbSalvar.AutoSize = true;
this.chbSalvar.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.chbSalvar.Location = new System.Drawing.Point(740, 44);
this.chbSalvar.Name = "chbSalvar";
this.chbSalvar.Size = new System.Drawing.Size(128, 24);
this.chbSalvar.TabIndex = 7;
this.chbSalvar.Text = "Personalizado";
this.chbSalvar.UseVisualStyleBackColor = true;
//
// frmParametrizacaoOperacao
//
this.AutoScaleDimensions = new System.Drawing.SizeF(11F, 24F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1020, 697);
this.Controls.Add(this.chbSalvar);
this.Controls.Add(this.btnSalvar);
this.Controls.Add(this.btnCarregar);
this.Controls.Add(this.gpbModulos);
this.Controls.Add(this.lblOperacao);
this.Controls.Add(this.cmbOperacao);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Margin = new System.Windows.Forms.Padding(6);
this.Name = "frmParametrizacaoOperacao";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Parametrização da Operação";
this.Load += new System.EventHandler(this.frmParametrizacaoOperacao_Load);
this.gpbModulos.ResumeLayout(false);
this.gpbModulos.PerformLayout();
this.gpbP_Atu.ResumeLayout(false);
this.gpbP_Atu.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.nudQtdCameras)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nudQtdBicos)).EndInit();
this.gpbP_Dir.ResumeLayout(false);
this.gpbP_Dir.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.nudVelocidadeMP)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nudAnguloMaximo)).EndInit();
this.gpbP_Mov.ResumeLayout(false);
this.gpbP_Mov.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.nudVelocidadeComErvas)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nudVelocidadeSemErvas)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nudAnguloMinimo)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox cmbOperacao;
private System.Windows.Forms.Label lblOperacao;
private System.Windows.Forms.GroupBox gpbModulos;
private System.Windows.Forms.CheckBox chbD_Gps;
private System.Windows.Forms.CheckBox chbD_Sen;
private System.Windows.Forms.CheckBox chbD_Atu;
private System.Windows.Forms.CheckBox chbD_Dir;
private System.Windows.Forms.CheckBox chbD_Mov;
private System.Windows.Forms.Button btnCarregar;
private System.Windows.Forms.Button btnSalvar;
private System.Windows.Forms.CheckBox chbO_Gps;
private System.Windows.Forms.CheckBox chbO_Sen;
private System.Windows.Forms.CheckBox chbO_Atu;
private System.Windows.Forms.CheckBox chbO_Dir;
private System.Windows.Forms.CheckBox chbO_Mov;
private System.Windows.Forms.GroupBox gpbP_Mov;
private System.Windows.Forms.NumericUpDown nudVelocidadeComErvas;
private System.Windows.Forms.Label lblKmhCErvas;
private System.Windows.Forms.Label lblVelocidadeComErvas;
private System.Windows.Forms.NumericUpDown nudVelocidadeSemErvas;
private System.Windows.Forms.Label lblKmhSErvas;
private System.Windows.Forms.Label lblVelocidadeSemErvas;
private System.Windows.Forms.GroupBox gpbP_Gps;
private System.Windows.Forms.GroupBox gpbP_Sen;
private System.Windows.Forms.GroupBox gpbP_Atu;
private System.Windows.Forms.NumericUpDown nudQtdCameras;
private System.Windows.Forms.Label lblQtdCameras;
private System.Windows.Forms.NumericUpDown nudQtdBicos;
private System.Windows.Forms.Label lblQtdBicos;
private System.Windows.Forms.GroupBox gpbP_Dir;
private System.Windows.Forms.NumericUpDown nudVelocidadeMP;
private System.Windows.Forms.Label lblVelocidadePercentual;
private System.Windows.Forms.Label lblVelocidadeMP;
private System.Windows.Forms.NumericUpDown nudAnguloMaximo;
private System.Windows.Forms.Label lblAngulo;
private System.Windows.Forms.NumericUpDown nudAnguloMinimo;
private System.Windows.Forms.CheckBox chbSalvar;
}
}

View File

@ -0,0 +1,143 @@
using AgroBase.Models;
using CefSharp.WinForms;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using static AgroBase.Models.Enuns;
namespace AgroBase.Forms.Operacoes
{
public partial class frmParametrizacaoOperacao : Form
{
List<OperacaoModulosMandatoriosModel> ModulosMandatorios = new List<OperacaoModulosMandatoriosModel>();
public frmParametrizacaoOperacao()
{
InitializeComponent();
}
private void frmParametrizacaoOperacao_Load(object sender, EventArgs e)
{
CarregarParametros();
}
void CarregarParametros()
{
ModulosMandatorios = Variaveis.OperacaoEmAndamento.ModulosMandatorios.ToList();
cmbOperacao.Items.Clear();
cmbOperacao.Items.AddRange(Enum.GetNames(typeof(ModoOperacao)));
cmbOperacao.SelectedIndex = (int)Variaveis.OperacaoEmAndamento.Modo;
var chbModulos = gpbModulos.Controls.OfType<CheckBox>().Where(x => x.Name.Contains("chbD_")).ToList();
chbModulos.ForEach(chb =>
{
T_Code chbDisp = (T_Code)Enum.Parse(typeof(T_Code), chb.Name.Replace("chbD_", ""), ignoreCase: true);
chb.Checked = ModulosMandatorios.Any(x => x.Dispositivo == chbDisp);
CheckBox chbO = gpbModulos.Controls.OfType<CheckBox>().FirstOrDefault(x => x.Name == chb.Name.Replace("chbD_", "chbO_"));
chbO.Enabled = ModulosMandatorios.Any(x => x.Dispositivo == chbDisp);
if (chbO.Enabled)
{
chbO.Checked = !ModulosMandatorios.First(x => x.Dispositivo == chbDisp).Mandatorio;
}
GroupBox gpb = gpbModulos.Controls.OfType<GroupBox>().FirstOrDefault(x => x.Name == chb.Name.Replace("chbD_", "gpbP_"));
if (gpb != null)
{
gpb.Enabled = chb.Checked;
}
});
nudVelocidadeComErvas.Value = Convert.ToInt32(Variaveis.OperacaoEmAndamento.Controle.RPM_Min);
nudVelocidadeSemErvas.Value = Convert.ToInt32(Variaveis.OperacaoEmAndamento.Controle.RPM_Max);
lblKmhCErvas.Text = MovimentacaoModel.CalculaVelocidadeRPM(Variaveis.OperacaoEmAndamento.Controle.RPM_Min).ToString("0.00") + " Km/h";
lblKmhSErvas.Text = MovimentacaoModel.CalculaVelocidadeRPM(Variaveis.OperacaoEmAndamento.Controle.RPM_Max).ToString("0.00") + " Km/h";
nudAnguloMaximo.Value = Convert.ToInt32(Variaveis.OperacaoEmAndamento.Controle.Angulo_Max);
nudAnguloMinimo.Value = Convert.ToInt32(Variaveis.OperacaoEmAndamento.Controle.Angulo_Min);
nudVelocidadeMP.Value = Convert.ToInt32(Variaveis.OperacaoEmAndamento.Controle.VelocidadeMP);
}
private void chbD_CheckedChanged(object sender, EventArgs e)
{
CheckBox chbD = (CheckBox)sender;
CheckBox chbO = gpbModulos.Controls.OfType<CheckBox>().FirstOrDefault(x => x.Name == chbD.Name.Replace("chbD_", "chbO_"));
if (chbO != null)
{
chbO.Enabled = chbD.Checked;
}
T_Code chbDisp = (T_Code)Enum.Parse(typeof(T_Code), chbD.Name.Replace("chbD_", ""), ignoreCase: true);
if (!ModulosMandatorios.Any(x => x.Dispositivo == chbDisp))
{
ModulosMandatorios.Add(new OperacaoModulosMandatoriosModel()
{
Dispositivo = chbDisp,
Mandatorio = !chbO.Checked,
});
}
ModulosMandatorios.First(x => x.Dispositivo == chbDisp).Utilizar = chbD.Checked;
GroupBox gpb = gpbModulos.Controls.OfType<GroupBox>().FirstOrDefault(x => x.Name == chbD.Name.Replace("chbD_", "gpbP_"));
if (gpb != null)
{
gpb.Enabled = chbD.Checked;
}
}
private void chbO_CheckedChanged(object sender, EventArgs e)
{
CheckBox chbO = (CheckBox)sender;
T_Code Disp = (T_Code)Enum.Parse(typeof(T_Code), chbO.Name.Replace("chbO_", ""), ignoreCase: true);
ModulosMandatorios.First(x => x.Dispositivo == Disp).Utilizar = true;
ModulosMandatorios.First(x => x.Dispositivo == Disp).Mandatorio = !chbO.Checked;
}
private void btnSalvar_Click(object sender, EventArgs e)
{
SalvarOperacao();
this.Close();
}
private void nudVelocidadeSemErvas_ValueChanged(object sender, EventArgs e)
{
lblKmhSErvas.Text = MovimentacaoModel.CalculaVelocidadeRPM((double)nudVelocidadeSemErvas.Value).ToString("0.00") + " Km/h";
}
private void nudVelocidadeComErvas_ValueChanged(object sender, EventArgs e)
{
lblKmhCErvas.Text = MovimentacaoModel.CalculaVelocidadeRPM((double)nudVelocidadeComErvas.Value).ToString("0.00") + " Km/h";
}
void SalvarOperacao()
{
Variaveis.OperacaoEmAndamento.ModulosMandatorios = ModulosMandatorios.Where(x => x.Utilizar).ToList();
Variaveis.OperacaoEmAndamento.Controle.RPM_Max = Convert.ToInt32(nudVelocidadeSemErvas.Value);
Variaveis.OperacaoEmAndamento.Controle.RPM_Min = Convert.ToInt32(nudVelocidadeComErvas.Value);
Variaveis.OperacaoEmAndamento.Controle.Angulo_Max = Convert.ToInt32(nudAnguloMaximo.Value);
Variaveis.OperacaoEmAndamento.Controle.Angulo_Min = Convert.ToInt32(nudAnguloMinimo.Value);
Variaveis.OperacaoEmAndamento.Controle.VelocidadeMP = Convert.ToInt32(nudVelocidadeMP.Value);
if (chbSalvar.Checked)
{
OperacaoModel.SalvarOperacaoPersonalizada(Variaveis.OperacaoEmAndamento);
MessageBox.Show("Operação " + Enum.GetName(typeof(ModoOperacao), Variaveis.OperacaoEmAndamento.Modo) + " salva com sucesso!", "Sucesso");
}
}
private void btnCarregar_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Arquivos de Operação|*.opr";
ofd.InitialDirectory = Application.StartupPath;
if (ofd.ShowDialog() == DialogResult.OK)
{
string operacaoPath = ofd.FileName;
Variaveis.OperacaoEmAndamento = OperacaoModel.CarregarOperacaoPersonalizada(operacaoPath);
MessageBox.Show("Operação " + Enum.GetName(typeof(ModoOperacao), Variaveis.OperacaoEmAndamento.Modo) + " carregada com sucesso!", "Sucesso");
CarregarParametros();
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -24,7 +24,7 @@ namespace AgroBase.Forms.Sensoriamento
private string VideoUrl = "line_angle";
private string SocketPorta = VariaveisPortas.SocketCaminho;
private bool MostrarDebug = true;
private string ArquivoLeitura = "leitura_angulo.json";
private string ArquivoLeitura = "leitura_angulo";
public frmSenCamera()
{

View File

@ -69,14 +69,14 @@ namespace AgroBase.Forms
this.pnlMapa.Controls.Add(chromiumWebBrowser);
chromiumWebBrowser.Dock = DockStyle.Fill;
InjectJavaScriptFunctionsAsync();
//InjectJavaScriptFunctionsAsync();
//tmrUpdate.Stop();
}
else if (!picLoading.Visible && GPSService.UltimaLeitura != null)
{
mapaService.AtualizarPosicaoMapaGPS(GPSService.UltimaLeitura.Latitude, GPSService.UltimaLeitura.Longitude);
//chromiumWebBrowser.Reload();
chromiumWebBrowser.Reload();
lblDatahora.Text = "Ultima Leitura: " + GPSService.UltimaLeitura.DataHora.ToString("dd/MM/yyyy HH:mm:ss");
lblLatitude.Text = "Latitude: " + GPSService.UltimaLeitura.Latitude;
@ -89,44 +89,5 @@ namespace AgroBase.Forms
}
private void InjectJavaScriptFunctionsAsync()
{
if (chromiumWebBrowser != null && chromiumWebBrowser.CanExecuteJavascriptInMainFrame)
{
string script = @"
// Esta função será chamada para atualizar a posição do marcador
function updateMarkerPosition(lat, lon) {
// Acesse o mapa do Folium e atualize o marcador
var map = window._leaflet_map; // Folium armazena o mapa na variável global _leaflet_map
if (map) {
var newLatLng = new L.LatLng(lat, lon);
if (window.gpsMarker) {
window.gpsMarker.setLatLng(newLatLng);
} else {
window.gpsMarker = L.marker(newLatLng).addTo(map);
}
map.panTo(newLatLng);
}
}
// Esta função busca a nova localização e atualiza o marcador
function fetchAndUpdateMarker() {
fetch('/marker_data')
.then(response => response.json())
.then(data => {
updateMarkerPosition(data.lat, data.lon);
})
.catch(error => console.error('Error fetching marker data:', error));
}
// Defina um intervalo para atualizar o marcador regularmente
setInterval(fetchAndUpdateMarker, 1000); // Atualiza a cada segundo
";
chromiumWebBrowser.ExecuteScriptAsync(script);
}
}
}
}

View File

@ -76,12 +76,15 @@ namespace AgroBase
this.gpbJoystick = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.gpbAtalhos = new System.Windows.Forms.GroupBox();
this.btnContornos = new System.Windows.Forms.Button();
this.btnGPS = new System.Windows.Forms.Button();
this.gpbOperacao = new System.Windows.Forms.GroupBox();
this.btnIHM = new System.Windows.Forms.Button();
this.btnConfigurarOperacao = new System.Windows.Forms.Button();
this.chbDebugMode = new System.Windows.Forms.CheckBox();
this.btnIniciarOperacao = new System.Windows.Forms.Button();
this.lblModoOperacao = new System.Windows.Forms.Label();
this.cmbModoOperacao = new System.Windows.Forms.ComboBox();
this.btnGPS = new System.Windows.Forms.Button();
this.gpbAcoes.SuspendLayout();
this.erroStrip.SuspendLayout();
this.pnlLateral.SuspendLayout();
@ -107,9 +110,9 @@ namespace AgroBase
this.gpbAcoes.Controls.Add(this.pnlLateral);
this.gpbAcoes.Dock = System.Windows.Forms.DockStyle.Right;
this.gpbAcoes.Location = new System.Drawing.Point(441, 0);
this.gpbAcoes.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbAcoes.Margin = new System.Windows.Forms.Padding(2);
this.gpbAcoes.Name = "gpbAcoes";
this.gpbAcoes.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbAcoes.Padding = new System.Windows.Forms.Padding(2);
this.gpbAcoes.Size = new System.Drawing.Size(617, 609);
this.gpbAcoes.TabIndex = 0;
this.gpbAcoes.TabStop = false;
@ -144,7 +147,7 @@ namespace AgroBase
this.pnlLateral.Controls.Add(this.btnNovoDispositivo);
this.pnlLateral.Dock = System.Windows.Forms.DockStyle.Fill;
this.pnlLateral.Location = new System.Drawing.Point(2, 15);
this.pnlLateral.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.pnlLateral.Margin = new System.Windows.Forms.Padding(2);
this.pnlLateral.Name = "pnlLateral";
this.pnlLateral.Size = new System.Drawing.Size(613, 592);
this.pnlLateral.TabIndex = 0;
@ -153,9 +156,9 @@ namespace AgroBase
//
this.gpbDispositivos.Controls.Add(this.lstDisponiveis);
this.gpbDispositivos.Location = new System.Drawing.Point(161, 78);
this.gpbDispositivos.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbDispositivos.Margin = new System.Windows.Forms.Padding(2);
this.gpbDispositivos.Name = "gpbDispositivos";
this.gpbDispositivos.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbDispositivos.Padding = new System.Windows.Forms.Padding(2);
this.gpbDispositivos.Size = new System.Drawing.Size(449, 133);
this.gpbDispositivos.TabIndex = 3;
this.gpbDispositivos.TabStop = false;
@ -165,7 +168,7 @@ namespace AgroBase
//
this.lstDisponiveis.HideSelection = false;
this.lstDisponiveis.Location = new System.Drawing.Point(11, 20);
this.lstDisponiveis.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.lstDisponiveis.Margin = new System.Windows.Forms.Padding(2);
this.lstDisponiveis.Name = "lstDisponiveis";
this.lstDisponiveis.Size = new System.Drawing.Size(252, 102);
this.lstDisponiveis.TabIndex = 0;
@ -175,7 +178,7 @@ namespace AgroBase
// btnRemover
//
this.btnRemover.Location = new System.Drawing.Point(87, 50);
this.btnRemover.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.btnRemover.Margin = new System.Windows.Forms.Padding(2);
this.btnRemover.Name = "btnRemover";
this.btnRemover.Size = new System.Drawing.Size(62, 23);
this.btnRemover.TabIndex = 12;
@ -198,7 +201,7 @@ namespace AgroBase
this.cmbDispositivos.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbDispositivos.FormattingEnabled = true;
this.cmbDispositivos.Location = new System.Drawing.Point(22, 26);
this.cmbDispositivos.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.cmbDispositivos.Margin = new System.Windows.Forms.Padding(2);
this.cmbDispositivos.Name = "cmbDispositivos";
this.cmbDispositivos.Size = new System.Drawing.Size(128, 21);
this.cmbDispositivos.TabIndex = 10;
@ -213,9 +216,9 @@ namespace AgroBase
this.gpbNovoDispositivo.Controls.Add(this.lblTipo);
this.gpbNovoDispositivo.Enabled = false;
this.gpbNovoDispositivo.Location = new System.Drawing.Point(16, 78);
this.gpbNovoDispositivo.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbNovoDispositivo.Margin = new System.Windows.Forms.Padding(2);
this.gpbNovoDispositivo.Name = "gpbNovoDispositivo";
this.gpbNovoDispositivo.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbNovoDispositivo.Padding = new System.Windows.Forms.Padding(2);
this.gpbNovoDispositivo.Size = new System.Drawing.Size(141, 133);
this.gpbNovoDispositivo.TabIndex = 9;
this.gpbNovoDispositivo.TabStop = false;
@ -226,7 +229,7 @@ namespace AgroBase
this.cmbTipos.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbTipos.FormattingEnabled = true;
this.cmbTipos.Location = new System.Drawing.Point(7, 37);
this.cmbTipos.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.cmbTipos.Margin = new System.Windows.Forms.Padding(2);
this.cmbTipos.Name = "cmbTipos";
this.cmbTipos.Size = new System.Drawing.Size(128, 21);
this.cmbTipos.TabIndex = 2;
@ -234,7 +237,7 @@ namespace AgroBase
// btnSalvar
//
this.btnSalvar.Location = new System.Drawing.Point(7, 101);
this.btnSalvar.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.btnSalvar.Margin = new System.Windows.Forms.Padding(2);
this.btnSalvar.Name = "btnSalvar";
this.btnSalvar.Size = new System.Drawing.Size(127, 20);
this.btnSalvar.TabIndex = 9;
@ -245,7 +248,7 @@ namespace AgroBase
// txtDescricao
//
this.txtDescricao.Location = new System.Drawing.Point(7, 76);
this.txtDescricao.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.txtDescricao.Margin = new System.Windows.Forms.Padding(2);
this.txtDescricao.Name = "txtDescricao";
this.txtDescricao.Size = new System.Drawing.Size(128, 20);
this.txtDescricao.TabIndex = 3;
@ -273,7 +276,7 @@ namespace AgroBase
// btnNovoDispositivo
//
this.btnNovoDispositivo.Location = new System.Drawing.Point(22, 50);
this.btnNovoDispositivo.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.btnNovoDispositivo.Margin = new System.Windows.Forms.Padding(2);
this.btnNovoDispositivo.Name = "btnNovoDispositivo";
this.btnNovoDispositivo.Size = new System.Drawing.Size(60, 23);
this.btnNovoDispositivo.TabIndex = 8;
@ -327,9 +330,9 @@ namespace AgroBase
this.gpbMovimentacao.Controls.Add(this.trkRPM);
this.gpbMovimentacao.Controls.Add(this.lblRPM);
this.gpbMovimentacao.Location = new System.Drawing.Point(9, 63);
this.gpbMovimentacao.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbMovimentacao.Margin = new System.Windows.Forms.Padding(2);
this.gpbMovimentacao.Name = "gpbMovimentacao";
this.gpbMovimentacao.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbMovimentacao.Padding = new System.Windows.Forms.Padding(2);
this.gpbMovimentacao.Size = new System.Drawing.Size(330, 85);
this.gpbMovimentacao.TabIndex = 2;
this.gpbMovimentacao.TabStop = false;
@ -348,7 +351,7 @@ namespace AgroBase
// trkKmh
//
this.trkKmh.Location = new System.Drawing.Point(168, 37);
this.trkKmh.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.trkKmh.Margin = new System.Windows.Forms.Padding(2);
this.trkKmh.Maximum = 34;
this.trkKmh.Name = "trkKmh";
this.trkKmh.Size = new System.Drawing.Size(158, 45);
@ -360,7 +363,7 @@ namespace AgroBase
// trkRPM
//
this.trkRPM.Location = new System.Drawing.Point(4, 37);
this.trkRPM.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.trkRPM.Margin = new System.Windows.Forms.Padding(2);
this.trkRPM.Maximum = 500;
this.trkRPM.Minimum = 5;
this.trkRPM.Name = "trkRPM";
@ -383,7 +386,7 @@ namespace AgroBase
// tkbAngulo
//
this.tkbAngulo.Location = new System.Drawing.Point(4, 95);
this.tkbAngulo.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.tkbAngulo.Margin = new System.Windows.Forms.Padding(2);
this.tkbAngulo.Maximum = 180;
this.tkbAngulo.Name = "tkbAngulo";
this.tkbAngulo.Size = new System.Drawing.Size(314, 45);
@ -414,7 +417,7 @@ namespace AgroBase
// tkbVelocidade
//
this.tkbVelocidade.Location = new System.Drawing.Point(4, 35);
this.tkbVelocidade.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.tkbVelocidade.Margin = new System.Windows.Forms.Padding(2);
this.tkbVelocidade.Maximum = 100;
this.tkbVelocidade.Minimum = 1;
this.tkbVelocidade.Name = "tkbVelocidade";
@ -427,7 +430,7 @@ namespace AgroBase
// btnVer
//
this.btnVer.Location = new System.Drawing.Point(256, 20);
this.btnVer.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.btnVer.Margin = new System.Windows.Forms.Padding(2);
this.btnVer.Name = "btnVer";
this.btnVer.Size = new System.Drawing.Size(63, 20);
this.btnVer.TabIndex = 13;
@ -438,7 +441,7 @@ namespace AgroBase
// btnJoyAtt
//
this.btnJoyAtt.Location = new System.Drawing.Point(121, 20);
this.btnJoyAtt.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.btnJoyAtt.Margin = new System.Windows.Forms.Padding(2);
this.btnJoyAtt.Name = "btnJoyAtt";
this.btnJoyAtt.Size = new System.Drawing.Size(63, 20);
this.btnJoyAtt.TabIndex = 12;
@ -449,7 +452,7 @@ namespace AgroBase
// btnJoyEdt
//
this.btnJoyEdt.Location = new System.Drawing.Point(188, 20);
this.btnJoyEdt.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.btnJoyEdt.Margin = new System.Windows.Forms.Padding(2);
this.btnJoyEdt.Name = "btnJoyEdt";
this.btnJoyEdt.Size = new System.Drawing.Size(63, 20);
this.btnJoyEdt.TabIndex = 11;
@ -462,7 +465,7 @@ namespace AgroBase
this.cmbJoysticks.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbJoysticks.FormattingEnabled = true;
this.cmbJoysticks.Location = new System.Drawing.Point(4, 21);
this.cmbJoysticks.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.cmbJoysticks.Margin = new System.Windows.Forms.Padding(2);
this.cmbJoysticks.Name = "cmbJoysticks";
this.cmbJoysticks.Size = new System.Drawing.Size(112, 21);
this.cmbJoysticks.TabIndex = 3;
@ -480,9 +483,9 @@ namespace AgroBase
this.gpbSensoriamento.Controls.Add(this.lblSenMotores);
this.gpbSensoriamento.Controls.Add(this.gridSenMotores);
this.gpbSensoriamento.Location = new System.Drawing.Point(9, 413);
this.gpbSensoriamento.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbSensoriamento.Margin = new System.Windows.Forms.Padding(2);
this.gpbSensoriamento.Name = "gpbSensoriamento";
this.gpbSensoriamento.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbSensoriamento.Padding = new System.Windows.Forms.Padding(2);
this.gpbSensoriamento.Size = new System.Drawing.Size(423, 184);
this.gpbSensoriamento.TabIndex = 13;
this.gpbSensoriamento.TabStop = false;
@ -505,7 +508,7 @@ namespace AgroBase
| System.Windows.Forms.AnchorStyles.Right)));
this.gridSenMotores.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.gridSenMotores.Location = new System.Drawing.Point(4, 35);
this.gridSenMotores.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gridSenMotores.Margin = new System.Windows.Forms.Padding(2);
this.gridSenMotores.Name = "gridSenMotores";
this.gridSenMotores.RowHeadersWidth = 51;
this.gridSenMotores.RowTemplate.Height = 24;
@ -515,7 +518,7 @@ namespace AgroBase
// btnDiagnosticos
//
this.btnDiagnosticos.Location = new System.Drawing.Point(4, 17);
this.btnDiagnosticos.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.btnDiagnosticos.Margin = new System.Windows.Forms.Padding(2);
this.btnDiagnosticos.Name = "btnDiagnosticos";
this.btnDiagnosticos.Size = new System.Drawing.Size(84, 20);
this.btnDiagnosticos.TabIndex = 14;
@ -526,7 +529,7 @@ namespace AgroBase
// btnAcompanhamento
//
this.btnAcompanhamento.Location = new System.Drawing.Point(4, 42);
this.btnAcompanhamento.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.btnAcompanhamento.Margin = new System.Windows.Forms.Padding(2);
this.btnAcompanhamento.Name = "btnAcompanhamento";
this.btnAcompanhamento.Size = new System.Drawing.Size(84, 20);
this.btnAcompanhamento.TabIndex = 15;
@ -537,7 +540,7 @@ namespace AgroBase
// btnAtuCamera
//
this.btnAtuCamera.Location = new System.Drawing.Point(4, 67);
this.btnAtuCamera.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.btnAtuCamera.Margin = new System.Windows.Forms.Padding(2);
this.btnAtuCamera.Name = "btnAtuCamera";
this.btnAtuCamera.Size = new System.Drawing.Size(84, 20);
this.btnAtuCamera.TabIndex = 16;
@ -548,7 +551,7 @@ namespace AgroBase
// btnMapas
//
this.btnMapas.Location = new System.Drawing.Point(4, 118);
this.btnMapas.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.btnMapas.Margin = new System.Windows.Forms.Padding(2);
this.btnMapas.Name = "btnMapas";
this.btnMapas.Size = new System.Drawing.Size(84, 20);
this.btnMapas.TabIndex = 17;
@ -559,7 +562,7 @@ namespace AgroBase
// btnSenCamera
//
this.btnSenCamera.Location = new System.Drawing.Point(4, 93);
this.btnSenCamera.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.btnSenCamera.Margin = new System.Windows.Forms.Padding(2);
this.btnSenCamera.Name = "btnSenCamera";
this.btnSenCamera.Size = new System.Drawing.Size(84, 20);
this.btnSenCamera.TabIndex = 18;
@ -574,9 +577,9 @@ namespace AgroBase
this.gpbJoystick.Controls.Add(this.btnJoyAtt);
this.gpbJoystick.Controls.Add(this.btnVer);
this.gpbJoystick.Location = new System.Drawing.Point(9, 10);
this.gpbJoystick.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbJoystick.Margin = new System.Windows.Forms.Padding(2);
this.gpbJoystick.Name = "gpbJoystick";
this.gpbJoystick.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbJoystick.Padding = new System.Windows.Forms.Padding(2);
this.gpbJoystick.Size = new System.Drawing.Size(330, 49);
this.gpbJoystick.TabIndex = 18;
this.gpbJoystick.TabStop = false;
@ -589,9 +592,9 @@ namespace AgroBase
this.groupBox2.Controls.Add(this.lblAngulo);
this.groupBox2.Controls.Add(this.lblVelocidade);
this.groupBox2.Location = new System.Drawing.Point(9, 154);
this.groupBox2.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.groupBox2.Margin = new System.Windows.Forms.Padding(2);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.groupBox2.Padding = new System.Windows.Forms.Padding(2);
this.groupBox2.Size = new System.Drawing.Size(330, 149);
this.groupBox2.TabIndex = 19;
this.groupBox2.TabStop = false;
@ -599,6 +602,7 @@ namespace AgroBase
//
// gpbAtalhos
//
this.gpbAtalhos.Controls.Add(this.btnContornos);
this.gpbAtalhos.Controls.Add(this.btnGPS);
this.gpbAtalhos.Controls.Add(this.btnDiagnosticos);
this.gpbAtalhos.Controls.Add(this.btnAcompanhamento);
@ -606,34 +610,80 @@ namespace AgroBase
this.gpbAtalhos.Controls.Add(this.btnAtuCamera);
this.gpbAtalhos.Controls.Add(this.btnMapas);
this.gpbAtalhos.Location = new System.Drawing.Point(344, 10);
this.gpbAtalhos.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbAtalhos.Margin = new System.Windows.Forms.Padding(2);
this.gpbAtalhos.Name = "gpbAtalhos";
this.gpbAtalhos.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbAtalhos.Padding = new System.Windows.Forms.Padding(2);
this.gpbAtalhos.Size = new System.Drawing.Size(93, 292);
this.gpbAtalhos.TabIndex = 20;
this.gpbAtalhos.TabStop = false;
this.gpbAtalhos.Text = "Atalhos";
//
// btnContornos
//
this.btnContornos.Location = new System.Drawing.Point(4, 166);
this.btnContornos.Margin = new System.Windows.Forms.Padding(2);
this.btnContornos.Name = "btnContornos";
this.btnContornos.Size = new System.Drawing.Size(84, 20);
this.btnContornos.TabIndex = 20;
this.btnContornos.Text = "Contornos";
this.btnContornos.UseVisualStyleBackColor = true;
this.btnContornos.Click += new System.EventHandler(this.btnContornos_Click);
//
// btnGPS
//
this.btnGPS.Location = new System.Drawing.Point(4, 142);
this.btnGPS.Margin = new System.Windows.Forms.Padding(2);
this.btnGPS.Name = "btnGPS";
this.btnGPS.Size = new System.Drawing.Size(84, 20);
this.btnGPS.TabIndex = 19;
this.btnGPS.Text = "GPS";
this.btnGPS.UseVisualStyleBackColor = true;
this.btnGPS.Click += new System.EventHandler(this.btnGPS_Click);
//
// gpbOperacao
//
this.gpbOperacao.Controls.Add(this.btnIHM);
this.gpbOperacao.Controls.Add(this.btnConfigurarOperacao);
this.gpbOperacao.Controls.Add(this.chbDebugMode);
this.gpbOperacao.Controls.Add(this.btnIniciarOperacao);
this.gpbOperacao.Controls.Add(this.lblModoOperacao);
this.gpbOperacao.Controls.Add(this.cmbModoOperacao);
this.gpbOperacao.Location = new System.Drawing.Point(9, 307);
this.gpbOperacao.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbOperacao.Margin = new System.Windows.Forms.Padding(2);
this.gpbOperacao.Name = "gpbOperacao";
this.gpbOperacao.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.gpbOperacao.Padding = new System.Windows.Forms.Padding(2);
this.gpbOperacao.Size = new System.Drawing.Size(428, 101);
this.gpbOperacao.TabIndex = 21;
this.gpbOperacao.TabStop = false;
this.gpbOperacao.Text = "Operação";
//
// btnIHM
//
this.btnIHM.Location = new System.Drawing.Point(296, 63);
this.btnIHM.Margin = new System.Windows.Forms.Padding(2);
this.btnIHM.Name = "btnIHM";
this.btnIHM.Size = new System.Drawing.Size(122, 33);
this.btnIHM.TabIndex = 16;
this.btnIHM.Text = "IHM";
this.btnIHM.UseVisualStyleBackColor = true;
this.btnIHM.Click += new System.EventHandler(this.btnIHM_Click);
//
// btnConfigurarOperacao
//
this.btnConfigurarOperacao.Location = new System.Drawing.Point(121, 63);
this.btnConfigurarOperacao.Margin = new System.Windows.Forms.Padding(2);
this.btnConfigurarOperacao.Name = "btnConfigurarOperacao";
this.btnConfigurarOperacao.Size = new System.Drawing.Size(122, 33);
this.btnConfigurarOperacao.TabIndex = 15;
this.btnConfigurarOperacao.Text = "Configurar Operação";
this.btnConfigurarOperacao.UseVisualStyleBackColor = true;
this.btnConfigurarOperacao.Click += new System.EventHandler(this.btnConfigurarOperacao_Click);
//
// chbDebugMode
//
this.chbDebugMode.AutoSize = true;
this.chbDebugMode.Location = new System.Drawing.Point(134, 40);
this.chbDebugMode.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.chbDebugMode.Margin = new System.Windows.Forms.Padding(2);
this.chbDebugMode.Name = "chbDebugMode";
this.chbDebugMode.Size = new System.Drawing.Size(109, 17);
this.chbDebugMode.TabIndex = 14;
@ -643,7 +693,7 @@ namespace AgroBase
// btnIniciarOperacao
//
this.btnIniciarOperacao.Location = new System.Drawing.Point(7, 63);
this.btnIniciarOperacao.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.btnIniciarOperacao.Margin = new System.Windows.Forms.Padding(2);
this.btnIniciarOperacao.Name = "btnIniciarOperacao";
this.btnIniciarOperacao.Size = new System.Drawing.Size(109, 33);
this.btnIniciarOperacao.TabIndex = 13;
@ -666,23 +716,12 @@ namespace AgroBase
this.cmbModoOperacao.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbModoOperacao.FormattingEnabled = true;
this.cmbModoOperacao.Location = new System.Drawing.Point(7, 38);
this.cmbModoOperacao.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.cmbModoOperacao.Margin = new System.Windows.Forms.Padding(2);
this.cmbModoOperacao.Name = "cmbModoOperacao";
this.cmbModoOperacao.Size = new System.Drawing.Size(110, 21);
this.cmbModoOperacao.TabIndex = 13;
this.cmbModoOperacao.SelectedIndexChanged += new System.EventHandler(this.cmbModoOperacao_SelectedIndexChanged);
//
// btnGPS
//
this.btnGPS.Location = new System.Drawing.Point(4, 142);
this.btnGPS.Margin = new System.Windows.Forms.Padding(2);
this.btnGPS.Name = "btnGPS";
this.btnGPS.Size = new System.Drawing.Size(84, 20);
this.btnGPS.TabIndex = 19;
this.btnGPS.Text = "GPS";
this.btnGPS.UseVisualStyleBackColor = true;
this.btnGPS.Click += new System.EventHandler(this.btnGPS_Click);
//
// frmPrincipal
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
@ -696,7 +735,7 @@ namespace AgroBase
this.Controls.Add(this.gpbSensoriamento);
this.Controls.Add(this.generalStrip);
this.Controls.Add(this.gpbAcoes);
this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.Margin = new System.Windows.Forms.Padding(2);
this.Name = "frmPrincipal";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Agro Base";
@ -788,6 +827,9 @@ namespace AgroBase
private System.Windows.Forms.ToolStripStatusLabel lblStripOperacao;
private System.Windows.Forms.ToolStripStatusLabel lblStripOperacaoStatus;
private System.Windows.Forms.Button btnGPS;
private System.Windows.Forms.Button btnConfigurarOperacao;
private System.Windows.Forms.Button btnIHM;
private System.Windows.Forms.Button btnContornos;
}
}

View File

@ -1,16 +1,21 @@
using AgroBase.Comum;
using AgroBase.Forms;
using AgroBase.Forms.IHM;
using AgroBase.Forms.Movimentacao;
using AgroBase.Forms.Operacoes;
using AgroBase.Forms.Sensoriamento;
using AgroBase.Models;
using AgroBase.Models.Modules;
using AgroBase.Services;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading;
using System.Windows.Forms;
using static AgroBase.Models.Enuns;
@ -120,13 +125,13 @@ namespace AgroBase
{
lstDisponiveis.Items.Clear();
lstDisponiveis.Items.AddRange(
SerialService.DispositivosConectados
SerialService.DispositivosMapeados
.Select(x => new ListViewItem()
{
Text = x.PortaCOM + " - " + Enum.GetName(typeof(T_Code), x.Dispositivo) + " - " + (Variaveis.DispositivosConectados.FirstOrDefault(y => y.PortaCOM() == x.PortaCOM)?.StatusPorta() ?? "Desconectado")
Text = x.PortaCOM + " - " + Enum.GetName(typeof(T_Code), x.Dispositivo) + " - " + (x.Dispositivo == T_Code.Gps ? (GPSService.PortaGPS != null && GPSService.PortaGPS.IsOpen ? "Conectado" : "Desconectado") : (Variaveis.DispositivosConectados.FirstOrDefault(y => y.PortaCOM() == x.PortaCOM)?.StatusPorta() ?? "Desconectado"))
}).ToArray()
);
if (SerialService.DispositivosConectados.Count == 0)
if (SerialService.DispositivosMapeados.Count == 0)
{
Variaveis.DispositivosConectados.Where(x => x.Dados.GetStatusConexao()).ToList().ForEach(x => x.AcaoDesconectar());
}
@ -305,6 +310,25 @@ namespace AgroBase
}
private void btnConfigurarOperacao_Click(object sender, EventArgs e)
{
frmParametrizacaoOperacao frmParametrizacaoOperacao = new frmParametrizacaoOperacao();
frmParametrizacaoOperacao.ShowDialog();
}
private void btnIHM_Click(object sender, EventArgs e)
{
frmIHM frmIHM = new frmIHM();
frmIHM.ShowDialog();
}
private void btnContornos_Click(object sender, EventArgs e)
{
frmMovCamera frmMovCamera = new frmMovCamera();
frmMovCamera.Show();
}
}
}

View File

@ -120,9 +120,6 @@
<metadata name="erroStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>11, 10</value>
</metadata>
<metadata name="erroStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>11, 10</value>
</metadata>
<metadata name="generalStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>133, 16</value>
</metadata>

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -42,4 +43,16 @@ namespace AgroBase.Models
public int distancia_direita { get; set; }
}
public class CameraDeepLabV3PlusModel
{
public double timestamp { get; set; }
public List<CameraDeepLabV3PlusClasseModel> Classes { get; set; }
}
public class CameraDeepLabV3PlusClasseModel
{
public string Classe { get; set; }
public int[][] Contornos { get; set; }
}
}

View File

@ -0,0 +1,27 @@
using AgroBase.Services;
using CefSharp.WinForms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AgroBase.Models
{
public class CameraSoloModel
{
public string Nome { get; set; }
public int Posicao { get; set; }
public CameraService<CameraCoordenadasFrameModel> camera { get; set; }
public ChromiumWebBrowser browser { get; set; }
public Panel panel { get;set; }
public ComboBox combo { get;set; }
public string ArquivoLeitura { get; set; }
public int MaxLeituras { get; set; }
public string VideoPorta { get; set; }
public string VideoUrl { get; set; }
public string SocketPorta { get; set; }
public string CameraSelecionada { get; set; }
}
}

View File

@ -23,7 +23,7 @@ namespace AgroBase.Models
public static double Kp { get; set; } = 1.75;
public static double Ki { get; set; } = 2.1;
public static double Kd { get; set; } = 0.08;
public static int _DelayBalanceamento { get; set; } = 2000;
public static int _DelayBalanceamento { get; set; } = 500;
public static int _MargemRPM { get; set; } = 5;
public static int _MaxOffsetRPM { get; set; } = 25;
public static double DiametroRoda { get; set; } = 0.3556;

View File

@ -370,6 +370,8 @@ namespace AgroBase.Models.Modules
public void AtualizaGridSensoriamento()
{
foreach (var Sensor in Sensores.Where(x => x.ID.Contains("MV")).ToList())
{
try
{
MovSensoriamentoMotor Motor =
Variaveis.DispositivosConectados.Any(x => x.Dispositivo == T_Code.Mov) ?
@ -379,6 +381,12 @@ namespace AgroBase.Models.Modules
{
frmInstancial.frmPrincipal.gridSenMotores.Rows[Motor.Canal].Cells[9].Value = Motor.Temperatura.ToString();
}
}
catch
{
}
}
}

View File

@ -1,8 +1,12 @@
using AgroBase.Comum;
using AgroBase.Forms;
using AgroBase.Forms.Operacoes;
using AgroBase.Models.Modules;
using AgroBase.Services;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
@ -15,7 +19,33 @@ namespace AgroBase.Models
public OperacaoModel(ModoOperacao Modo, DispositivosService<MovimentacaoModel> Mov = null, DispositivosService<DirecionalModel> Dir = null, DispositivosService<AtuadorModel> Atu = null)
{
this.Modo = Modo;
this.Controle = new OperacaoControleModel();
this.Controle = new OperacaoControleModel()
{
TiposControle = new List<OperacaoControleTipoModel>()
{
new OperacaoControleTipoModel()
{
Tipo = T_Code.Mov,
DelayEnvioComando = 500,
Comandos = new List<string>(),
UltimoComando = DateTime.Now
},
new OperacaoControleTipoModel()
{
Tipo = T_Code.Dir,
DelayEnvioComando = 1000,
Comandos = new List<string>(),
UltimoComando = DateTime.Now
},
new OperacaoControleTipoModel()
{
Tipo = T_Code.Atu,
DelayEnvioComando = 100,
Comandos = new List<string>(),
UltimoComando = DateTime.Now
},
},
};
this.ControleAnterior = new OperacaoControleModel();
this.DispMov = Mov;
@ -36,11 +66,14 @@ namespace AgroBase.Models
public DispositivosService<MovimentacaoModel> DispMov { get; set; }
public DispositivosService<DirecionalModel> DispDir { get; set; }
public DispositivosService<AtuadorModel> DispAtu { get; set; }
public Form frmOperacao { get; set; }
public string frmOperacaoNome { get; set; }
public bool Iniciado { get; set; }
public long TimestampInicio { get; set; }
public long TimestampFim { get; set; }
public OperacaoControleModel Controle { get; set; }
public OperacaoControleModel ControleAnterior { get; set; }
public List<OperacaoModulosMandatoriosModel> ModulosMandatorios { get; set; }
public int ErvasNoRadar { get; set; } = 0;
@ -53,6 +86,172 @@ namespace AgroBase.Models
public double DistanciaPercorrida { get; set; } = 0;
public double ProgressoPercurso { get; set; } = 0;
public static OperacaoModel CarregarParametrosOperacaoPadrao(ModoOperacao Modo)
{
var MovConectado = (DispositivosService<MovimentacaoModel>)Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == T_Code.Mov && (x._Porta.IsOpen));
var DirConectado = (DispositivosService<DirecionalModel>)Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == T_Code.Dir && (x._Porta.IsOpen));
var AtuConectado = (DispositivosService<AtuadorModel>)Variaveis.DispositivosConectados.FirstOrDefault(x => x.Dispositivo == T_Code.Atu && (x._Porta.IsOpen));
OperacaoModel OperacaoCarregar = new OperacaoModel(Modo)
{
Controle = new OperacaoControleModel(),
ControleAnterior = new OperacaoControleModel(),
AtuacoesPorBico = new List<int>(),
BateriaConsumida = 0,
DistanciaPercorrida = 0,
ErvasIdentificadas = 0,
ErvasNoRadar = 0,
HerbicidaConsumido = 0,
HerbicidaPorErva = 0,
Iniciado = false,
ProgressoPercurso = 0,
TimestampInicio = 0,
TimestampFim = 0,
VelocidadeMedia = 0,
DispAtu = AtuConectado,
DispDir = DirConectado,
DispMov = MovConectado,
};
switch (Modo)
{
case ModoOperacao.Manual:
OperacaoCarregar.frmOperacao = new frmAcompanhamento();
OperacaoCarregar.Controle = new OperacaoControleModel()
{
TiposControle = new List<OperacaoControleTipoModel>()
{
new OperacaoControleTipoModel()
{
Tipo = T_Code.Mov,
DelayEnvioComando = 10,
Comandos = new List<string>(),
UltimoComando = DateTime.Now
},
new OperacaoControleTipoModel()
{
Tipo = T_Code.Dir,
DelayEnvioComando = 10,
Comandos = new List<string>(),
UltimoComando = DateTime.Now
},
},
};
OperacaoCarregar.ModulosMandatorios = new List<OperacaoModulosMandatoriosModel>()
{
new OperacaoModulosMandatoriosModel()
{
Dispositivo = T_Code.Mov,
Mandatorio = false,
},
new OperacaoModulosMandatoriosModel()
{
Dispositivo = T_Code.Dir,
Mandatorio = false,
},
};
break;
case ModoOperacao.SeguidorDeLinha:
OperacaoCarregar.frmOperacao = new frmOperacaoSeguidorLinha();
OperacaoCarregar.Controle = new OperacaoControleModel()
{
RPM_Max = 45,
RPM_Min = 15,
Angulo_Max = 30,
Angulo_Min = -30,
VelocidadeMP = 50,
TiposControle = new List<OperacaoControleTipoModel>()
{
new OperacaoControleTipoModel()
{
Tipo = T_Code.Mov,
DelayEnvioComando = 500,
Comandos = new List<string>(),
UltimoComando = DateTime.Now
},
new OperacaoControleTipoModel()
{
Tipo = T_Code.Dir,
DelayEnvioComando = 1000,
Comandos = new List<string>(),
UltimoComando = DateTime.Now
},
new OperacaoControleTipoModel()
{
Tipo = T_Code.Atu,
DelayEnvioComando = 100,
Comandos = new List<string>(),
UltimoComando = DateTime.Now
},
},
};
OperacaoCarregar.ModulosMandatorios = new List<OperacaoModulosMandatoriosModel>()
{
new OperacaoModulosMandatoriosModel()
{
Dispositivo = T_Code.Mov,
Mandatorio = true,
},
new OperacaoModulosMandatoriosModel()
{
Dispositivo = T_Code.Dir,
Mandatorio = true,
},
new OperacaoModulosMandatoriosModel()
{
Dispositivo = T_Code.Atu,
Mandatorio = true,
},
};
break;
}
if (OperacaoCarregar.DispAtu != null)
{
for (int i = 0; i < OperacaoCarregar.DispAtu.Dados.QuantidadeBicos; i++)
{
OperacaoCarregar.AtuacoesPorBico.Add(0);
}
}
return OperacaoCarregar;
}
public static void SalvarOperacaoPersonalizada(OperacaoModel Operacao)
{
Form frm = Operacao.frmOperacao;
Operacao.frmOperacao = null;
Operacao.frmOperacaoNome = frm.Name;
File.WriteAllText("operacao" + Enum.GetName(typeof(ModoOperacao), Operacao.Modo) + ".opr", JsonConvert.SerializeObject(Operacao));
Operacao.frmOperacao = frm;
}
public static OperacaoModel CarregarOperacaoPersonalizada(string nomeArquivo)
{
string modoOpStr = nomeArquivo.Split('\\')[nomeArquivo.Split('\\').Length - 1].Replace("operacao", "").Split('.')[0];
ModoOperacao modo = (ModoOperacao)Enum.Parse(typeof(ModoOperacao), modoOpStr);
OperacaoModel Operacao = new OperacaoModel(modo);
if (!File.Exists(nomeArquivo))
{
Operacao = CarregarParametrosOperacaoPadrao(modo);
SalvarOperacaoPersonalizada(Operacao);
}
var operacaoText = File.ReadAllText(nomeArquivo);
Operacao = JsonConvert.DeserializeObject<OperacaoModel>(operacaoText);
Type tipoDoForm = Type.GetType(Operacao.frmOperacaoNome);
if (tipoDoForm != null)
{
Operacao.frmOperacao = (Form)Activator.CreateInstance(tipoDoForm);
}
return Operacao;
}
public void IniciarOperacao(OperacaoControleModel controle = null)
{
Iniciado = true;
@ -62,7 +261,7 @@ namespace AgroBase.Models
{
Controle = controle;
}
frmOperacao.Show();
}
public void FinalizarOperacao()
@ -77,23 +276,36 @@ namespace AgroBase.Models
public void AtualizarDadosControle()
{
if (Controle.RPM != ControleAnterior.RPM)
DateTime Agora = DateTime.Now;
OperacaoControleTipoModel ControleMov = Controle.TiposControle.FirstOrDefault(x => x.Tipo == T_Code.Mov);
OperacaoControleTipoModel ControleDir = Controle.TiposControle.FirstOrDefault(x => x.Tipo == T_Code.Dir);
OperacaoControleTipoModel ControleAtu = Controle.TiposControle.FirstOrDefault(x => x.Tipo == T_Code.Atu);
if (ControleMov != null && Controle.RPM != ControleAnterior.RPM && (Agora - ControleMov.UltimoComando).Milliseconds > ControleMov.DelayEnvioComando)
{
// Enviar comando MOV
EnviarProtocoloComando(DispMov);
var Protocolos = EnviarProtocoloComando(DispMov);
ControleMov.UltimoComando = Agora;
ControleMov.Comandos.AddRange(Protocolos);
}
if (Controle.Angulo != ControleAnterior.Angulo)
if (ControleDir != null && Controle.Angulo != ControleAnterior.Angulo && (Agora - ControleDir.UltimoComando).Milliseconds > ControleDir.DelayEnvioComando)
{
// Enviar comando
EnviarProtocoloComando(DispDir);
// Enviar comando DIR
var Protocolos = EnviarProtocoloComando(DispDir);
ControleDir.UltimoComando = Agora;
ControleDir.Comandos.AddRange(Protocolos);
}
if (Controle.BicosAtuados.Select(x => x.Atuado).ToList() != ControleAnterior.BicosAtuados.Select(x => x.Atuado).ToList())
if (ControleAtu != null && Controle.BicosAtuados.Select(x => x.Atuado).ToList() != ControleAnterior.BicosAtuados.Select(x => x.Atuado).ToList() && (Agora - ControleAtu.UltimoComando).Milliseconds > ControleAtu.DelayEnvioComando)
{
// Enviar comando ATU
EnviarProtocoloComando(DispAtu);
var Protocolos = EnviarProtocoloComando(DispAtu);
ControleAtu.UltimoComando = Agora;
ControleAtu.Comandos.AddRange(Protocolos);
}
ControleAnterior = Controle;
ControleAnterior.Angulo = Controle.Angulo;
ControleAnterior.RPM = Controle.RPM;
ControleAnterior.BicosAtuados = Controle.BicosAtuados.ToList();
AtualizarDadosOperacao();
}
@ -108,11 +320,11 @@ namespace AgroBase.Models
DistanciaPercorrida = DispMov.Dados.DistanciaPercorridaTotal;
}
public void EnviarProtocoloComando(IDispositivosService Dispositivo)
public List<string> EnviarProtocoloComando(IDispositivosService Dispositivo)
{
if (Dispositivo == null)
{
return;
return new List<string>();
}
Direcao DirecaoAtual = Direcao.Parado;
@ -126,6 +338,7 @@ namespace AgroBase.Models
else
{
GeneralJoystick.RPM = Controle.RPM;
DirecaoAtual = Direcao.Frente;
}
}
else if (Dispositivo.Dispositivo == T_Code.Dir)
@ -152,6 +365,8 @@ namespace AgroBase.Models
Dispositivo.EnviarDadosSerial(ProtocoloMotor);
Task.Delay(10);
}
return Protocolos.ToList();
}
}
@ -168,6 +383,16 @@ namespace AgroBase.Models
public Direcao Direcao { get; set; } = Direcao.Parado;
public double VelocidadeMP { get; set; } = 50;
public List<AtuadorBicoModel> BicosAtuados { get; set; } = new List<AtuadorBicoModel>();
public List<OperacaoControleTipoModel> TiposControle { get; set; }
}
public class OperacaoControleTipoModel
{
public T_Code Tipo { get; set; }
public int DelayEnvioComando { get; set; }
public DateTime UltimoComando { get; set; }
public List<string> Comandos { get; set; }
}
public class OperacaoGraficoModel
@ -175,4 +400,13 @@ namespace AgroBase.Models
public double Velocidade { get; set; }
public double Temperatura { get; set; }
}
public class OperacaoModulosMandatoriosModel
{
public T_Code Dispositivo { get; set; }
public bool Mandatorio { get; set; }
public bool Utilizar { get; set; }
public bool Conectado { get; set; }
}
}

View File

@ -40,8 +40,8 @@ namespace AgroBase.Models
public static string GPS { get; } = "6512";
public static string CameraSolo { get; } = "6513";
public static string CameraCaminho { get; } = "6514";
public static string SocketSolo { get; } = "6515";
public static string SocketCaminho { get; } = "6516";
public static string SocketSolo { get; } = "6360";
public static string SocketCaminho { get; } = "6365";
}
}

View File

@ -0,0 +1,2 @@
from .modeling import *
from ._deeplab import convert_to_separable_conv

View File

@ -0,0 +1,178 @@
import torch
from torch import nn
from torch.nn import functional as F
from .utils import _SimpleSegmentationModel
__all__ = ["DeepLabV3"]
class DeepLabV3(_SimpleSegmentationModel):
"""
Implements DeepLabV3 model from
`"Rethinking Atrous Convolution for Semantic Image Segmentation"
<https://arxiv.org/abs/1706.05587>`_.
Arguments:
backbone (nn.Module): the network used to compute the features for the model.
The backbone should return an OrderedDict[Tensor], with the key being
"out" for the last feature map used, and "aux" if an auxiliary classifier
is used.
classifier (nn.Module): module that takes the "out" element returned from
the backbone and returns a dense prediction.
aux_classifier (nn.Module, optional): auxiliary classifier used during training
"""
pass
class DeepLabHeadV3Plus(nn.Module):
def __init__(self, in_channels, low_level_channels, num_classes, aspp_dilate=[12, 24, 36]):
super(DeepLabHeadV3Plus, self).__init__()
self.project = nn.Sequential(
nn.Conv2d(low_level_channels, 48, 1, bias=False),
nn.BatchNorm2d(48),
nn.ReLU(inplace=True),
)
self.aspp = ASPP(in_channels, aspp_dilate)
self.classifier = nn.Sequential(
nn.Conv2d(304, 256, 3, padding=1, bias=False),
nn.BatchNorm2d(256),
nn.ReLU(inplace=True),
nn.Conv2d(256, num_classes, 1)
)
self._init_weight()
def forward(self, feature):
low_level_feature = self.project( feature['low_level'] )
output_feature = self.aspp(feature['out'])
output_feature = F.interpolate(output_feature, size=low_level_feature.shape[2:], mode='bilinear', align_corners=False)
return self.classifier( torch.cat( [ low_level_feature, output_feature ], dim=1 ) )
def _init_weight(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
class DeepLabHead(nn.Module):
def __init__(self, in_channels, num_classes, aspp_dilate=[12, 24, 36]):
super(DeepLabHead, self).__init__()
self.classifier = nn.Sequential(
ASPP(in_channels, aspp_dilate),
nn.Conv2d(256, 256, 3, padding=1, bias=False),
nn.BatchNorm2d(256),
nn.ReLU(inplace=True),
nn.Conv2d(256, num_classes, 1)
)
self._init_weight()
def forward(self, feature):
return self.classifier( feature['out'] )
def _init_weight(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
class AtrousSeparableConvolution(nn.Module):
""" Atrous Separable Convolution
"""
def __init__(self, in_channels, out_channels, kernel_size,
stride=1, padding=0, dilation=1, bias=True):
super(AtrousSeparableConvolution, self).__init__()
self.body = nn.Sequential(
# Separable Conv
nn.Conv2d( in_channels, in_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=bias, groups=in_channels ),
# PointWise Conv
nn.Conv2d( in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=bias),
)
self._init_weight()
def forward(self, x):
return self.body(x)
def _init_weight(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
class ASPPConv(nn.Sequential):
def __init__(self, in_channels, out_channels, dilation):
modules = [
nn.Conv2d(in_channels, out_channels, 3, padding=dilation, dilation=dilation, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
]
super(ASPPConv, self).__init__(*modules)
class ASPPPooling(nn.Sequential):
def __init__(self, in_channels, out_channels):
super(ASPPPooling, self).__init__(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(in_channels, out_channels, 1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True))
def forward(self, x):
size = x.shape[-2:]
x = super(ASPPPooling, self).forward(x)
return F.interpolate(x, size=size, mode='bilinear', align_corners=False)
class ASPP(nn.Module):
def __init__(self, in_channels, atrous_rates):
super(ASPP, self).__init__()
out_channels = 256
modules = []
modules.append(nn.Sequential(
nn.Conv2d(in_channels, out_channels, 1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)))
rate1, rate2, rate3 = tuple(atrous_rates)
modules.append(ASPPConv(in_channels, out_channels, rate1))
modules.append(ASPPConv(in_channels, out_channels, rate2))
modules.append(ASPPConv(in_channels, out_channels, rate3))
modules.append(ASPPPooling(in_channels, out_channels))
self.convs = nn.ModuleList(modules)
self.project = nn.Sequential(
nn.Conv2d(5 * out_channels, out_channels, 1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Dropout(0.1),)
def forward(self, x):
res = []
for conv in self.convs:
res.append(conv(x))
res = torch.cat(res, dim=1)
return self.project(res)
def convert_to_separable_conv(module):
new_module = module
if isinstance(module, nn.Conv2d) and module.kernel_size[0]>1:
new_module = AtrousSeparableConvolution(module.in_channels,
module.out_channels,
module.kernel_size,
module.stride,
module.padding,
module.dilation,
module.bias)
for name, child in module.named_children():
new_module.add_module(name, convert_to_separable_conv(child))
return new_module

View File

@ -0,0 +1,4 @@
from . import resnet
from . import mobilenetv2
from . import hrnetv2
from . import xception

View File

@ -0,0 +1,345 @@
import torch
from torch import nn
import torch.nn.functional as F
import os
__all__ = ['HRNet', 'hrnetv2_48', 'hrnetv2_32']
# Checkpoint path of pre-trained backbone (edit to your path). Download backbone pretrained model hrnetv2-32 @
# https://drive.google.com/file/d/1NxCK7Zgn5PmeS7W1jYLt5J9E0RRZ2oyF/view?usp=sharing .Personally, I added the backbone
# weights to the folder /checkpoints
model_urls = {
'hrnetv2_32': './checkpoints/model_best_epoch96_edit.pth',
'hrnetv2_48': None
}
def check_pth(arch):
CKPT_PATH = model_urls[arch]
if os.path.exists(CKPT_PATH):
print(f"Backbone HRNet Pretrained weights at: {CKPT_PATH}, only usable for HRNetv2-32")
else:
print("No backbone checkpoint found for HRNetv2, please set pretrained=False when calling model")
return CKPT_PATH
# HRNetv2-48 not available yet, but you can train the whole model from scratch.
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class StageModule(nn.Module):
def __init__(self, stage, output_branches, c):
super(StageModule, self).__init__()
self.number_of_branches = stage # number of branches is equivalent to the stage configuration.
self.output_branches = output_branches
self.branches = nn.ModuleList()
# Note: Resolution + Number of channels maintains the same throughout respective branch.
for i in range(self.number_of_branches): # Stage scales with the number of branches. Ex: Stage 2 -> 2 branch
channels = c * (2 ** i) # Scale channels by 2x for branch with lower resolution,
# Paper does x4 basic block for each forward sequence in each branch (x4 basic block considered as a block)
branch = nn.Sequential(*[BasicBlock(channels, channels) for _ in range(4)])
self.branches.append(branch) # list containing all forward sequence of individual branches.
# For each branch requires repeated fusion with all other branches after passing through x4 basic blocks.
self.fuse_layers = nn.ModuleList()
for branch_output_number in range(self.output_branches):
self.fuse_layers.append(nn.ModuleList())
for branch_number in range(self.number_of_branches):
if branch_number == branch_output_number:
self.fuse_layers[-1].append(nn.Sequential()) # Used in place of "None" because it is callable
elif branch_number > branch_output_number:
self.fuse_layers[-1].append(nn.Sequential(
nn.Conv2d(c * (2 ** branch_number), c * (2 ** branch_output_number), kernel_size=1, stride=1,
bias=False),
nn.BatchNorm2d(c * (2 ** branch_output_number), eps=1e-05, momentum=0.1, affine=True,
track_running_stats=True),
nn.Upsample(scale_factor=(2.0 ** (branch_number - branch_output_number)), mode='nearest'),
))
elif branch_number < branch_output_number:
downsampling_fusion = []
for _ in range(branch_output_number - branch_number - 1):
downsampling_fusion.append(nn.Sequential(
nn.Conv2d(c * (2 ** branch_number), c * (2 ** branch_number), kernel_size=3, stride=2,
padding=1,
bias=False),
nn.BatchNorm2d(c * (2 ** branch_number), eps=1e-05, momentum=0.1, affine=True,
track_running_stats=True),
nn.ReLU(inplace=True),
))
downsampling_fusion.append(nn.Sequential(
nn.Conv2d(c * (2 ** branch_number), c * (2 ** branch_output_number), kernel_size=3,
stride=2, padding=1,
bias=False),
nn.BatchNorm2d(c * (2 ** branch_output_number), eps=1e-05, momentum=0.1, affine=True,
track_running_stats=True),
))
self.fuse_layers[-1].append(nn.Sequential(*downsampling_fusion))
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
# input to each stage is a list of inputs for each branch
x = [branch(branch_input) for branch, branch_input in zip(self.branches, x)]
x_fused = []
for branch_output_index in range(
self.output_branches): # Amount of output branches == total length of fusion layers
for input_index in range(self.number_of_branches): # The inputs of other branches to be fused.
if input_index == 0:
x_fused.append(self.fuse_layers[branch_output_index][input_index](x[input_index]))
else:
x_fused[branch_output_index] = x_fused[branch_output_index] + self.fuse_layers[branch_output_index][
input_index](x[input_index])
# After fusing all streams together, you will need to pass the fused layers
for i in range(self.output_branches):
x_fused[i] = self.relu(x_fused[i])
return x_fused # returning a list of fused outputs
class HRNet(nn.Module):
def __init__(self, c=48, num_blocks=[1, 4, 3], num_classes=1000):
super(HRNet, self).__init__()
# Stem:
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64, eps=1e-05, affine=True, track_running_stats=True)
self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(64, eps=1e-05, affine=True, track_running_stats=True)
self.relu = nn.ReLU(inplace=True)
# Stage 1:
downsample = nn.Sequential(
nn.Conv2d(64, 256, kernel_size=1, stride=1, bias=False),
nn.BatchNorm2d(256, eps=1e-05, affine=True, track_running_stats=True),
)
# Note that bottleneck module will expand the output channels according to the output channels*block.expansion
bn_expansion = Bottleneck.expansion # The channel expansion is set in the bottleneck class.
self.layer1 = nn.Sequential(
Bottleneck(64, 64, downsample=downsample), # Input is 64 for first module connection
Bottleneck(bn_expansion * 64, 64),
Bottleneck(bn_expansion * 64, 64),
Bottleneck(bn_expansion * 64, 64),
)
# Transition 1 - Creation of the first two branches (one full and one half resolution)
# Need to transition into high resolution stream and mid resolution stream
self.transition1 = nn.ModuleList([
nn.Sequential(
nn.Conv2d(256, c, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(c, eps=1e-05, affine=True, track_running_stats=True),
nn.ReLU(inplace=True),
),
nn.Sequential(nn.Sequential( # Double Sequential to fit with official pretrained weights
nn.Conv2d(256, c * 2, kernel_size=3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(c * 2, eps=1e-05, affine=True, track_running_stats=True),
nn.ReLU(inplace=True),
)),
])
# Stage 2:
number_blocks_stage2 = num_blocks[0]
self.stage2 = nn.Sequential(
*[StageModule(stage=2, output_branches=2, c=c) for _ in range(number_blocks_stage2)])
# Transition 2 - Creation of the third branch (1/4 resolution)
self.transition2 = self._make_transition_layers(c, transition_number=2)
# Stage 3:
number_blocks_stage3 = num_blocks[1] # number blocks you want to create before fusion
self.stage3 = nn.Sequential(
*[StageModule(stage=3, output_branches=3, c=c) for _ in range(number_blocks_stage3)])
# Transition - Creation of the fourth branch (1/8 resolution)
self.transition3 = self._make_transition_layers(c, transition_number=3)
# Stage 4:
number_blocks_stage4 = num_blocks[2] # number blocks you want to create before fusion
self.stage4 = nn.Sequential(
*[StageModule(stage=4, output_branches=4, c=c) for _ in range(number_blocks_stage4)])
# Classifier (extra module if want to use for classification):
# pool, reduce dimensionality, flatten, connect to linear layer for classification:
out_channels = sum([c * 2 ** i for i in range(len(num_blocks)+1)]) # total output channels of HRNetV2
pool_feature_map = 8
self.bn_classifier = nn.Sequential(
nn.Conv2d(out_channels, out_channels // 4, kernel_size=1, bias=False),
nn.BatchNorm2d(out_channels // 4, eps=1e-05, affine=True, track_running_stats=True),
nn.ReLU(inplace=True),
nn.AdaptiveAvgPool2d(pool_feature_map),
nn.Flatten(),
nn.Linear(pool_feature_map * pool_feature_map * (out_channels // 4), num_classes),
)
@staticmethod
def _make_transition_layers(c, transition_number):
return nn.Sequential(
nn.Conv2d(c * (2 ** (transition_number - 1)), c * (2 ** transition_number), kernel_size=3, stride=2,
padding=1, bias=False),
nn.BatchNorm2d(c * (2 ** transition_number), eps=1e-05, affine=True,
track_running_stats=True),
nn.ReLU(inplace=True),
)
def forward(self, x):
# Stem:
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu(x)
# Stage 1
x = self.layer1(x)
x = [trans(x) for trans in self.transition1] # split to 2 branches, form a list.
# Stage 2
x = self.stage2(x)
x.append(self.transition2(x[-1]))
# Stage 3
x = self.stage3(x)
x.append(self.transition3(x[-1]))
# Stage 4
x = self.stage4(x)
# HRNetV2 Example: (follow paper, upsample via bilinear interpolation and to highest resolution size)
output_h, output_w = x[0].size(2), x[0].size(3) # Upsample to size of highest resolution stream
x1 = F.interpolate(x[1], size=(output_h, output_w), mode='bilinear', align_corners=False)
x2 = F.interpolate(x[2], size=(output_h, output_w), mode='bilinear', align_corners=False)
x3 = F.interpolate(x[3], size=(output_h, output_w), mode='bilinear', align_corners=False)
# Upsampling all the other resolution streams and then concatenate all (rather than adding/fusing like HRNetV1)
x = torch.cat([x[0], x1, x2, x3], dim=1)
x = self.bn_classifier(x)
return x
def _hrnet(arch, channels, num_blocks, pretrained, progress, **kwargs):
model = HRNet(channels, num_blocks, **kwargs)
if pretrained:
CKPT_PATH = check_pth(arch)
checkpoint = torch.load(CKPT_PATH)
model.load_state_dict(checkpoint['state_dict'])
return model
def hrnetv2_48(pretrained=False, progress=True, number_blocks=[1, 4, 3], **kwargs):
w_channels = 48
return _hrnet('hrnetv2_48', w_channels, number_blocks, pretrained, progress,
**kwargs)
def hrnetv2_32(pretrained=False, progress=True, number_blocks=[1, 4, 3], **kwargs):
w_channels = 32
return _hrnet('hrnetv2_32', w_channels, number_blocks, pretrained, progress,
**kwargs)
if __name__ == '__main__':
try:
CKPT_PATH = os.path.join(os.path.abspath("."), '../../checkpoints/hrnetv2_32_model_best_epoch96.pth')
print("--- Running file as MAIN ---")
print(f"Backbone HRNET Pretrained weights as __main__ at: {CKPT_PATH}")
except:
print("No backbone checkpoint found for HRNetv2, please set pretrained=False when calling model")
# Models
model = hrnetv2_32(pretrained=True)
#model = hrnetv2_48(pretrained=False)
if torch.cuda.is_available():
torch.backends.cudnn.deterministic = True
device = torch.device('cuda')
else:
device = torch.device('cpu')
model.to(device)
in_ = torch.ones(1, 3, 768, 768).to(device)
y = model(in_)
print(y.shape)
# Calculate total number of parameters:
# pytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
# print(pytorch_total_params)

View File

@ -0,0 +1,190 @@
from torch import nn
try: # for torchvision<0.4
from torchvision.models.utils import load_state_dict_from_url
except: # for torchvision>=0.4
from torch.hub import load_state_dict_from_url
import torch.nn.functional as F
__all__ = ['MobileNetV2', 'mobilenet_v2']
model_urls = {
'mobilenet_v2': 'https://download.pytorch.org/models/mobilenet_v2-b0353104.pth',
}
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:param v:
:param divisor:
:param min_value:
:return:
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v
class ConvBNReLU(nn.Sequential):
def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, dilation=1, groups=1):
#padding = (kernel_size - 1) // 2
super(ConvBNReLU, self).__init__(
nn.Conv2d(in_planes, out_planes, kernel_size, stride, 0, dilation=dilation, groups=groups, bias=False),
nn.BatchNorm2d(out_planes),
nn.ReLU6(inplace=True)
)
def fixed_padding(kernel_size, dilation):
kernel_size_effective = kernel_size + (kernel_size - 1) * (dilation - 1)
pad_total = kernel_size_effective - 1
pad_beg = pad_total // 2
pad_end = pad_total - pad_beg
return (pad_beg, pad_end, pad_beg, pad_end)
class InvertedResidual(nn.Module):
def __init__(self, inp, oup, stride, dilation, expand_ratio):
super(InvertedResidual, self).__init__()
self.stride = stride
assert stride in [1, 2]
hidden_dim = int(round(inp * expand_ratio))
self.use_res_connect = self.stride == 1 and inp == oup
layers = []
if expand_ratio != 1:
# pw
layers.append(ConvBNReLU(inp, hidden_dim, kernel_size=1))
layers.extend([
# dw
ConvBNReLU(hidden_dim, hidden_dim, stride=stride, dilation=dilation, groups=hidden_dim),
# pw-linear
nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
nn.BatchNorm2d(oup),
])
self.conv = nn.Sequential(*layers)
self.input_padding = fixed_padding( 3, dilation )
def forward(self, x):
x_pad = F.pad(x, self.input_padding)
if self.use_res_connect:
return x + self.conv(x_pad)
else:
return self.conv(x_pad)
class MobileNetV2(nn.Module):
def __init__(self, num_classes=1000, output_stride=8, width_mult=1.0, inverted_residual_setting=None, round_nearest=8):
"""
MobileNet V2 main class
Args:
num_classes (int): Number of classes
width_mult (float): Width multiplier - adjusts number of channels in each layer by this amount
inverted_residual_setting: Network structure
round_nearest (int): Round the number of channels in each layer to be a multiple of this number
Set to 1 to turn off rounding
"""
super(MobileNetV2, self).__init__()
block = InvertedResidual
input_channel = 32
last_channel = 1280
self.output_stride = output_stride
current_stride = 1
if inverted_residual_setting is None:
inverted_residual_setting = [
# t, c, n, s
[1, 16, 1, 1],
[6, 24, 2, 2],
[6, 32, 3, 2],
[6, 64, 4, 2],
[6, 96, 3, 1],
[6, 160, 3, 2],
[6, 320, 1, 1],
]
# only check the first element, assuming user knows t,c,n,s are required
if len(inverted_residual_setting) == 0 or len(inverted_residual_setting[0]) != 4:
raise ValueError("inverted_residual_setting should be non-empty "
"or a 4-element list, got {}".format(inverted_residual_setting))
# building first layer
input_channel = _make_divisible(input_channel * width_mult, round_nearest)
self.last_channel = _make_divisible(last_channel * max(1.0, width_mult), round_nearest)
features = [ConvBNReLU(3, input_channel, stride=2)]
current_stride *= 2
dilation=1
previous_dilation = 1
# building inverted residual blocks
for t, c, n, s in inverted_residual_setting:
output_channel = _make_divisible(c * width_mult, round_nearest)
previous_dilation = dilation
if current_stride == output_stride:
stride = 1
dilation *= s
else:
stride = s
current_stride *= s
output_channel = int(c * width_mult)
for i in range(n):
if i==0:
features.append(block(input_channel, output_channel, stride, previous_dilation, expand_ratio=t))
else:
features.append(block(input_channel, output_channel, 1, dilation, expand_ratio=t))
input_channel = output_channel
# building last several layers
features.append(ConvBNReLU(input_channel, self.last_channel, kernel_size=1))
# make it nn.Sequential
self.features = nn.Sequential(*features)
# building classifier
self.classifier = nn.Sequential(
nn.Dropout(0.2),
nn.Linear(self.last_channel, num_classes),
)
# weight initialization
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out')
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.BatchNorm2d):
nn.init.ones_(m.weight)
nn.init.zeros_(m.bias)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
nn.init.zeros_(m.bias)
def forward(self, x):
x = self.features(x)
x = x.mean([2, 3])
x = self.classifier(x)
return x
def mobilenet_v2(pretrained=False, progress=True, **kwargs):
"""
Constructs a MobileNetV2 architecture from
`"MobileNetV2: Inverted Residuals and Linear Bottlenecks" <https://arxiv.org/abs/1801.04381>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
model = MobileNetV2(**kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls['mobilenet_v2'],
progress=progress)
model.load_state_dict(state_dict)
return model

View File

@ -0,0 +1,346 @@
import torch
import torch.nn as nn
try: # for torchvision<0.4
from torchvision.models.utils import load_state_dict_from_url
except: # for torchvision>=0.4
from torch.hub import load_state_dict_from_url
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
'wide_resnet50_2', 'wide_resnet101_2']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
}
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(BasicBlock, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if groups != 1 or base_width != 64:
raise ValueError('BasicBlock only supports groups=1 and base_width=64')
if dilation > 1:
raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = norm_layer(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = norm_layer(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
width = int(planes * (base_width / 64.)) * groups
# Both self.conv2 and self.downsample layers downsample the input when stride != 1
self.conv1 = conv1x1(inplanes, width)
self.bn1 = norm_layer(width)
self.conv2 = conv3x3(width, width, stride, groups, dilation)
self.bn2 = norm_layer(width)
self.conv3 = conv1x1(width, planes * self.expansion)
self.bn3 = norm_layer(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None,
norm_layer=None):
super(ResNet, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
self._norm_layer = norm_layer
self.inplanes = 64
self.dilation = 1
if replace_stride_with_dilation is None:
# each element in the tuple indicates if we should replace
# the 2x2 stride with a dilated convolution instead
replace_stride_with_dilation = [False, False, False]
if len(replace_stride_with_dilation) != 3:
raise ValueError("replace_stride_with_dilation should be None "
"or a 3-element tuple, got {}".format(replace_stride_with_dilation))
self.groups = groups
self.base_width = width_per_group
self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = norm_layer(self.inplanes)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
dilate=replace_stride_with_dilation[0])
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
dilate=replace_stride_with_dilation[1])
self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
dilate=replace_stride_with_dilation[2])
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
# Zero-initialize the last BN in each residual branch,
# so that the residual branch starts with zeros, and each residual block behaves like an identity.
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
if zero_init_residual:
for m in self.modules():
if isinstance(m, Bottleneck):
nn.init.constant_(m.bn3.weight, 0)
elif isinstance(m, BasicBlock):
nn.init.constant_(m.bn2.weight, 0)
def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(self.inplanes, planes * block.expansion, stride),
norm_layer(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
self.base_width, previous_dilation, norm_layer))
self.inplanes = planes * block.expansion
for _ in range(1, blocks):
layers.append(block(self.inplanes, planes, groups=self.groups,
base_width=self.base_width, dilation=self.dilation,
norm_layer=norm_layer))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.fc(x)
return x
def _resnet(arch, block, layers, pretrained, progress, **kwargs):
model = ResNet(block, layers, **kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls[arch],
progress=progress)
model.load_state_dict(state_dict)
return model
def resnet18(pretrained=False, progress=True, **kwargs):
r"""ResNet-18 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
**kwargs)
def resnet34(pretrained=False, progress=True, **kwargs):
r"""ResNet-34 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
**kwargs)
def resnet50(pretrained=False, progress=True, **kwargs):
r"""ResNet-50 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
**kwargs)
def resnet101(pretrained=False, progress=True, **kwargs):
r"""ResNet-101 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress,
**kwargs)
def resnet152(pretrained=False, progress=True, **kwargs):
r"""ResNet-152 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress,
**kwargs)
def resnext50_32x4d(pretrained=False, progress=True, **kwargs):
r"""ResNeXt-50 32x4d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
kwargs['groups'] = 32
kwargs['width_per_group'] = 4
return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3],
pretrained, progress, **kwargs)
def resnext101_32x8d(pretrained=False, progress=True, **kwargs):
r"""ResNeXt-101 32x8d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
kwargs['groups'] = 32
kwargs['width_per_group'] = 8
return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3],
pretrained, progress, **kwargs)
def wide_resnet50_2(pretrained=False, progress=True, **kwargs):
r"""Wide ResNet-50-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels in outer 1x1
convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
channels, and in Wide ResNet-50-2 has 2048-1024-2048.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
kwargs['width_per_group'] = 64 * 2
return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3],
pretrained, progress, **kwargs)
def wide_resnet101_2(pretrained=False, progress=True, **kwargs):
r"""Wide ResNet-101-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels in outer 1x1
convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
channels, and in Wide ResNet-50-2 has 2048-1024-2048.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
kwargs['width_per_group'] = 64 * 2
return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3],
pretrained, progress, **kwargs)

View File

@ -0,0 +1,238 @@
"""
Xception is adapted from https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/xception.py
Ported to pytorch thanks to [tstandley](https://github.com/tstandley/Xception-PyTorch)
@author: tstandley
Adapted by cadene
Creates an Xception Model as defined in:
Francois Chollet
Xception: Deep Learning with Depthwise Separable Convolutions
https://arxiv.org/pdf/1610.02357.pdf
This weights ported from the Keras implementation. Achieves the following performance on the validation set:
Loss:0.9173 Prec@1:78.892 Prec@5:94.292
REMEMBER to set your image size to 3x299x299 for both test and validation
normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5])
The resize parameter of the validation transform should be 333, and make sure to center crop at 299x299
"""
from __future__ import print_function, division, absolute_import
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from torch.nn import init
__all__ = ['xception']
pretrained_settings = {
'xception': {
'imagenet': {
'url': 'http://data.lip6.fr/cadene/pretrainedmodels/xception-43020ad28.pth',
'input_space': 'RGB',
'input_size': [3, 299, 299],
'input_range': [0, 1],
'mean': [0.5, 0.5, 0.5],
'std': [0.5, 0.5, 0.5],
'num_classes': 1000,
'scale': 0.8975 # The resize parameter of the validation transform should be 333, and make sure to center crop at 299x299
}
}
}
class SeparableConv2d(nn.Module):
def __init__(self,in_channels,out_channels,kernel_size=1,stride=1,padding=0,dilation=1,bias=False):
super(SeparableConv2d,self).__init__()
self.conv1 = nn.Conv2d(in_channels,in_channels,kernel_size,stride,padding,dilation,groups=in_channels,bias=bias)
self.pointwise = nn.Conv2d(in_channels,out_channels,1,1,0,1,1,bias=bias)
def forward(self,x):
x = self.conv1(x)
x = self.pointwise(x)
return x
class Block(nn.Module):
def __init__(self,in_filters,out_filters,reps,strides=1,start_with_relu=True,grow_first=True, dilation=1):
super(Block, self).__init__()
if out_filters != in_filters or strides!=1:
self.skip = nn.Conv2d(in_filters,out_filters,1,stride=strides, bias=False)
self.skipbn = nn.BatchNorm2d(out_filters)
else:
self.skip=None
rep=[]
filters=in_filters
if grow_first:
rep.append(nn.ReLU(inplace=True))
rep.append(SeparableConv2d(in_filters,out_filters,3,stride=1,padding=dilation, dilation=dilation, bias=False))
rep.append(nn.BatchNorm2d(out_filters))
filters = out_filters
for i in range(reps-1):
rep.append(nn.ReLU(inplace=True))
rep.append(SeparableConv2d(filters,filters,3,stride=1,padding=dilation,dilation=dilation,bias=False))
rep.append(nn.BatchNorm2d(filters))
if not grow_first:
rep.append(nn.ReLU(inplace=True))
rep.append(SeparableConv2d(in_filters,out_filters,3,stride=1,padding=dilation,dilation=dilation,bias=False))
rep.append(nn.BatchNorm2d(out_filters))
if not start_with_relu:
rep = rep[1:]
else:
rep[0] = nn.ReLU(inplace=False)
if strides != 1:
rep.append(nn.MaxPool2d(3,strides,1))
self.rep = nn.Sequential(*rep)
def forward(self,inp):
x = self.rep(inp)
if self.skip is not None:
skip = self.skip(inp)
skip = self.skipbn(skip)
else:
skip = inp
x+=skip
return x
class Xception(nn.Module):
"""
Xception optimized for the ImageNet dataset, as specified in
https://arxiv.org/pdf/1610.02357.pdf
"""
def __init__(self, num_classes=1000, replace_stride_with_dilation=None):
""" Constructor
Args:
num_classes: number of classes
"""
super(Xception, self).__init__()
self.num_classes = num_classes
self.dilation = 1
if replace_stride_with_dilation is None:
# each element in the tuple indicates if we should replace
# the 2x2 stride with a dilated convolution instead
replace_stride_with_dilation = [False, False, False, False]
if len(replace_stride_with_dilation) != 4:
raise ValueError("replace_stride_with_dilation should be None "
"or a 4-element tuple, got {}".format(replace_stride_with_dilation))
self.conv1 = nn.Conv2d(3, 32, 3,2, 0, bias=False) # 1 / 2
self.bn1 = nn.BatchNorm2d(32)
self.relu1 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(32,64,3,bias=False)
self.bn2 = nn.BatchNorm2d(64)
self.relu2 = nn.ReLU(inplace=True)
#do relu here
self.block1=self._make_block(64,128,2,2,start_with_relu=False,grow_first=True, dilate=replace_stride_with_dilation[0]) # 1 / 4
self.block2=self._make_block(128,256,2,2,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[1]) # 1 / 8
self.block3=self._make_block(256,728,2,2,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2]) # 1 / 16
self.block4=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block5=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block6=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block7=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block8=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block9=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block10=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block11=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block12=self._make_block(728,1024,2,2,start_with_relu=True,grow_first=False, dilate=replace_stride_with_dilation[3]) # 1 / 32
self.conv3 = SeparableConv2d(1024,1536,3,1,1, dilation=self.dilation)
self.bn3 = nn.BatchNorm2d(1536)
self.relu3 = nn.ReLU(inplace=True)
#do relu here
self.conv4 = SeparableConv2d(1536,2048,3,1,1, dilation=self.dilation)
self.bn4 = nn.BatchNorm2d(2048)
self.fc = nn.Linear(2048, num_classes)
# #------- init weights --------
# for m in self.modules():
# if isinstance(m, nn.Conv2d):
# n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
# m.weight.data.normal_(0, math.sqrt(2. / n))
# elif isinstance(m, nn.BatchNorm2d):
# m.weight.data.fill_(1)
# m.bias.data.zero_()
# #-----------------------------
def _make_block(self, in_filters,out_filters,reps,strides=1,start_with_relu=True,grow_first=True, dilate=False):
if dilate:
self.dilation *= strides
strides = 1
return Block(in_filters,out_filters,reps,strides,start_with_relu=start_with_relu,grow_first=grow_first, dilation=self.dilation)
def features(self, input):
x = self.conv1(input)
x = self.bn1(x)
x = self.relu1(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu2(x)
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
x = self.block4(x)
x = self.block5(x)
x = self.block6(x)
x = self.block7(x)
x = self.block8(x)
x = self.block9(x)
x = self.block10(x)
x = self.block11(x)
x = self.block12(x)
x = self.conv3(x)
x = self.bn3(x)
x = self.relu3(x)
x = self.conv4(x)
x = self.bn4(x)
return x
def logits(self, features):
x = nn.ReLU(inplace=True)(features)
x = F.adaptive_avg_pool2d(x, (1, 1))
x = x.view(x.size(0), -1)
x = self.last_linear(x)
return x
def forward(self, input):
x = self.features(input)
x = self.logits(x)
return x
def xception(num_classes=1000, pretrained='imagenet', replace_stride_with_dilation=None):
model = Xception(num_classes=num_classes, replace_stride_with_dilation=replace_stride_with_dilation)
if pretrained:
settings = pretrained_settings['xception'][pretrained]
assert num_classes == settings['num_classes'], \
"num_classes should be {}, but is {}".format(settings['num_classes'], num_classes)
model = Xception(num_classes=num_classes, replace_stride_with_dilation=replace_stride_with_dilation)
model.load_state_dict(model_zoo.load_url(settings['url']))
# TODO: ugly
model.last_linear = model.fc
del model.fc
return model

View File

@ -0,0 +1,222 @@
from .utils import IntermediateLayerGetter
from ._deeplab import DeepLabHead, DeepLabHeadV3Plus, DeepLabV3
from .backbone import (
resnet,
mobilenetv2,
hrnetv2,
xception
)
def _segm_hrnet(name, backbone_name, num_classes, pretrained_backbone):
backbone = hrnetv2.__dict__[backbone_name](pretrained_backbone)
# HRNetV2 config:
# the final output channels is dependent on highest resolution channel config (c).
# output of backbone will be the inplanes to assp:
hrnet_channels = int(backbone_name.split('_')[-1])
inplanes = sum([hrnet_channels * 2 ** i for i in range(4)])
low_level_planes = 256 # all hrnet version channel output from bottleneck is the same
aspp_dilate = [12, 24, 36] # If follow paper trend, can put [24, 48, 72].
if name=='deeplabv3plus':
return_layers = {'stage4': 'out', 'layer1': 'low_level'}
classifier = DeepLabHeadV3Plus(inplanes, low_level_planes, num_classes, aspp_dilate)
elif name=='deeplabv3':
return_layers = {'stage4': 'out'}
classifier = DeepLabHead(inplanes, num_classes, aspp_dilate)
backbone = IntermediateLayerGetter(backbone, return_layers=return_layers, hrnet_flag=True)
model = DeepLabV3(backbone, classifier)
return model
def _segm_resnet(name, backbone_name, num_classes, output_stride, pretrained_backbone):
if output_stride==8:
replace_stride_with_dilation=[False, True, True]
aspp_dilate = [12, 24, 36]
else:
replace_stride_with_dilation=[False, False, True]
aspp_dilate = [6, 12, 18]
backbone = resnet.__dict__[backbone_name](
pretrained=pretrained_backbone,
replace_stride_with_dilation=replace_stride_with_dilation)
inplanes = 2048
low_level_planes = 256
if name=='deeplabv3plus':
return_layers = {'layer4': 'out', 'layer1': 'low_level'}
classifier = DeepLabHeadV3Plus(inplanes, low_level_planes, num_classes, aspp_dilate)
elif name=='deeplabv3':
return_layers = {'layer4': 'out'}
classifier = DeepLabHead(inplanes , num_classes, aspp_dilate)
backbone = IntermediateLayerGetter(backbone, return_layers=return_layers)
model = DeepLabV3(backbone, classifier)
return model
def _segm_xception(name, backbone_name, num_classes, output_stride, pretrained_backbone):
if output_stride==8:
replace_stride_with_dilation=[False, False, True, True]
aspp_dilate = [12, 24, 36]
else:
replace_stride_with_dilation=[False, False, False, True]
aspp_dilate = [6, 12, 18]
backbone = xception.xception(pretrained= 'imagenet' if pretrained_backbone else False, replace_stride_with_dilation=replace_stride_with_dilation)
inplanes = 2048
low_level_planes = 128
if name=='deeplabv3plus':
return_layers = {'conv4': 'out', 'block1': 'low_level'}
classifier = DeepLabHeadV3Plus(inplanes, low_level_planes, num_classes, aspp_dilate)
elif name=='deeplabv3':
return_layers = {'conv4': 'out'}
classifier = DeepLabHead(inplanes , num_classes, aspp_dilate)
backbone = IntermediateLayerGetter(backbone, return_layers=return_layers)
model = DeepLabV3(backbone, classifier)
return model
def _segm_mobilenet(name, backbone_name, num_classes, output_stride, pretrained_backbone):
if output_stride==8:
aspp_dilate = [12, 24, 36]
else:
aspp_dilate = [6, 12, 18]
backbone = mobilenetv2.mobilenet_v2(pretrained=pretrained_backbone, output_stride=output_stride)
# rename layers
backbone.low_level_features = backbone.features[0:4]
backbone.high_level_features = backbone.features[4:-1]
backbone.features = None
backbone.classifier = None
inplanes = 320
low_level_planes = 24
if name=='deeplabv3plus':
return_layers = {'high_level_features': 'out', 'low_level_features': 'low_level'}
classifier = DeepLabHeadV3Plus(inplanes, low_level_planes, num_classes, aspp_dilate)
elif name=='deeplabv3':
return_layers = {'high_level_features': 'out'}
classifier = DeepLabHead(inplanes , num_classes, aspp_dilate)
backbone = IntermediateLayerGetter(backbone, return_layers=return_layers)
model = DeepLabV3(backbone, classifier)
return model
def _load_model(arch_type, backbone, num_classes, output_stride, pretrained_backbone):
if backbone=='mobilenetv2':
model = _segm_mobilenet(arch_type, backbone, num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
elif backbone.startswith('resnet'):
model = _segm_resnet(arch_type, backbone, num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
elif backbone.startswith('hrnetv2'):
model = _segm_hrnet(arch_type, backbone, num_classes, pretrained_backbone=pretrained_backbone)
elif backbone=='xception':
model = _segm_xception(arch_type, backbone, num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
else:
raise NotImplementedError
return model
# Deeplab v3
def deeplabv3_hrnetv2_48(num_classes=21, output_stride=4, pretrained_backbone=False): # no pretrained backbone yet
return _load_model('deeplabv3', 'hrnetv2_48', output_stride, num_classes, pretrained_backbone=pretrained_backbone)
def deeplabv3_hrnetv2_32(num_classes=21, output_stride=4, pretrained_backbone=True):
return _load_model('deeplabv3', 'hrnetv2_32', output_stride, num_classes, pretrained_backbone=pretrained_backbone)
def deeplabv3_resnet50(num_classes=21, output_stride=8, pretrained_backbone=True):
"""Constructs a DeepLabV3 model with a ResNet-50 backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3', 'resnet50', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3_resnet101(num_classes=21, output_stride=8, pretrained_backbone=True):
"""Constructs a DeepLabV3 model with a ResNet-101 backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3', 'resnet101', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3_mobilenet(num_classes=21, output_stride=8, pretrained_backbone=True, **kwargs):
"""Constructs a DeepLabV3 model with a MobileNetv2 backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3', 'mobilenetv2', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3_xception(num_classes=21, output_stride=8, pretrained_backbone=True, **kwargs):
"""Constructs a DeepLabV3 model with a Xception backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3', 'xception', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
# Deeplab v3+
def deeplabv3plus_hrnetv2_48(num_classes=21, output_stride=4, pretrained_backbone=False): # no pretrained backbone yet
return _load_model('deeplabv3plus', 'hrnetv2_48', num_classes, output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3plus_hrnetv2_32(num_classes=21, output_stride=4, pretrained_backbone=True):
return _load_model('deeplabv3plus', 'hrnetv2_32', num_classes, output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3plus_resnet50(num_classes=21, output_stride=8, pretrained_backbone=True):
"""Constructs a DeepLabV3 model with a ResNet-50 backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3plus', 'resnet50', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3plus_resnet101(num_classes=21, output_stride=8, pretrained_backbone=True):
"""Constructs a DeepLabV3+ model with a ResNet-101 backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3plus', 'resnet101', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3plus_mobilenet(num_classes=21, output_stride=8, pretrained_backbone=True):
"""Constructs a DeepLabV3+ model with a MobileNetv2 backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3plus', 'mobilenetv2', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3plus_xception(num_classes=21, output_stride=8, pretrained_backbone=True):
"""Constructs a DeepLabV3+ model with a Xception backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3plus', 'xception', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)

View File

@ -0,0 +1,93 @@
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from collections import OrderedDict
class _SimpleSegmentationModel(nn.Module):
def __init__(self, backbone, classifier):
super(_SimpleSegmentationModel, self).__init__()
self.backbone = backbone
self.classifier = classifier
def forward(self, x):
input_shape = x.shape[-2:]
features = self.backbone(x)
x = self.classifier(features)
x = F.interpolate(x, size=input_shape, mode='bilinear', align_corners=False)
return x
class IntermediateLayerGetter(nn.ModuleDict):
"""
Module wrapper that returns intermediate layers from a model
It has a strong assumption that the modules have been registered
into the model in the same order as they are used.
This means that one should **not** reuse the same nn.Module
twice in the forward if you want this to work.
Additionally, it is only able to query submodules that are directly
assigned to the model. So if `model` is passed, `model.feature1` can
be returned, but not `model.feature1.layer2`.
Arguments:
model (nn.Module): model on which we will extract the features
return_layers (Dict[name, new_name]): a dict containing the names
of the modules for which the activations will be returned as
the key of the dict, and the value of the dict is the name
of the returned activation (which the user can specify).
Examples::
>>> m = torchvision.models.resnet18(pretrained=True)
>>> # extract layer1 and layer3, giving as names `feat1` and feat2`
>>> new_m = torchvision.models._utils.IntermediateLayerGetter(m,
>>> {'layer1': 'feat1', 'layer3': 'feat2'})
>>> out = new_m(torch.rand(1, 3, 224, 224))
>>> print([(k, v.shape) for k, v in out.items()])
>>> [('feat1', torch.Size([1, 64, 56, 56])),
>>> ('feat2', torch.Size([1, 256, 14, 14]))]
"""
def __init__(self, model, return_layers, hrnet_flag=False):
if not set(return_layers).issubset([name for name, _ in model.named_children()]):
raise ValueError("return_layers are not present in model")
self.hrnet_flag = hrnet_flag
orig_return_layers = return_layers
return_layers = {k: v for k, v in return_layers.items()}
layers = OrderedDict()
for name, module in model.named_children():
layers[name] = module
if name in return_layers:
del return_layers[name]
if not return_layers:
break
super(IntermediateLayerGetter, self).__init__(layers)
self.return_layers = orig_return_layers
def forward(self, x):
out = OrderedDict()
for name, module in self.named_children():
if self.hrnet_flag and name.startswith('transition'): # if using hrnet, you need to take care of transition
if name == 'transition1': # in transition1, you need to split the module to two streams first
x = [trans(x) for trans in module]
else: # all other transition is just an extra one stream split
x.append(module(x[-1]))
else: # other models (ex:resnet,mobilenet) are convolutions in series.
x = module(x)
if name in self.return_layers:
out_name = self.return_layers[name]
if name == 'stage4' and self.hrnet_flag: # In HRNetV2, we upsample and concat all outputs streams together
output_h, output_w = x[0].size(2), x[0].size(3) # Upsample to size of highest resolution stream
x1 = F.interpolate(x[1], size=(output_h, output_w), mode='bilinear', align_corners=False)
x2 = F.interpolate(x[2], size=(output_h, output_w), mode='bilinear', align_corners=False)
x3 = F.interpolate(x[3], size=(output_h, output_w), mode='bilinear', align_corners=False)
x = torch.cat([x[0], x1, x2, x3], dim=1)
out[out_name] = x
else:
out[out_name] = x
return out

View File

@ -0,0 +1,236 @@
import torch
from PIL import Image
import torchvision.transforms as T
import numpy as np
import cv2
import json
import time
from flask import Flask, Response, request
import threading
import socket
import os
import sys
json_reading_data = None
output_folder = 'Python/Output/'
model_folder = 'C:\\train\\DeepLabV3Plus-Pytorch\\'
max_readings = int(sys.argv[1])
port = sys.argv[2]
url = sys.argv[3]
output_file = sys.argv[4]
show_lines = sys.argv[5] == "1"
socket_port = int(sys.argv[6])
app = Flask(__name__)
script_dir = os.path.dirname(__file__) # Obtém o diretório onde o script está localizado
parent_dir = os.path.dirname(script_dir) # Obtém o diretório pai (Python/)
sys.path.append(parent_dir)
# Supondo que você tenha a estrutura do repositório e o módulo `network` conforme descrito no README
from Models.deeplabv3plus.modeling import deeplabv3plus_resnet50 as deeplabv3_model
# Configurações Iniciais
NUM_CLASSES = 4 # Pascal VOC possui 3 classes + 1 para o fundo
OUTPUT_STRIDE = 16 # Valor comum para DeepLab
MODEL_PATH = model_folder + 'backup/ruasModel_final.pth' # Caminho para o modelo pré-treinado
# Função para carregar o modelo
def load_model(model_path):
model = deeplabv3_model(num_classes=NUM_CLASSES, output_stride=OUTPUT_STRIDE)
model.load_state_dict(torch.load(model_path), strict=False)
model.eval() # Modo de avaliação
return model
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Carregar o modelo
model = load_model(MODEL_PATH)
model.to(device)
# Função modificada para processar um frame da câmera
def segment_frame(frame):
# Converte o frame do OpenCV (BGR) para o formato RGB
image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
transform = T.Compose([
T.Resize(520),
T.ToTensor(),
T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
input_tensor = transform(image).unsqueeze(0).to(device)
with torch.no_grad():
output = model(input_tensor)
output_predictions = output.max(1)[1].squeeze().detach().cpu().numpy()
generate_and_save_json(output_predictions)
return output_predictions
def read_labelmap(path):
label_colors = []
class_names = []
with open(path, 'r') as file:
for line in file.readlines():
# Ignora linhas comentadas
if line.startswith('#'):
continue
parts = line.strip().split(':')
if len(parts) >= 2:
label = parts[0].strip()
color = tuple(map(int, parts[1].split(',')))
class_names.append(label)
label_colors.append(color)
return np.array(label_colors), class_names
def generate_and_save_json(image):
label_colors, class_names = read_labelmap(model_folder + "dataset/labelmap.txt")
detected_classes = set(np.unique(image))
global json_reading_data
contours_info = []
output_path = output_folder + output_file
# Carregar os dados existentes se o arquivo já existir
if os.path.exists(output_path):
with open(output_path, 'r') as f:
try:
existing_data = json.load(f)
if type(existing_data) is list:
contours_info.extend(existing_data)
except json.JSONDecodeError:
print("Erro ao decodificar o JSON existente. Um novo arquivo será criado.")
timestamp = time.time()
json_data = {'timestamp': timestamp, 'Classes': []}
for l in detected_classes:
if l < len(label_colors): # Verifica se o índice está dentro do intervalo das cores definidas
class_entry = {'Classe': class_names[l], 'Contornos': []}
# Extrai a máscara para a classe atual
mask = (image == l).astype(np.uint8) * 255
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
# Verifica se o contorno não está vazio e tem a dimensão adequada
if contour.size > 0:
# Para cada ponto no contorno, adiciona diretamente ao array Contornos
for point in contour:
class_entry['Contornos'].append(point.squeeze().tolist())
json_data['Classes'].append(class_entry)
contours_info.append(json_data)
# Limita a quantidade de registros a serem salvos com base em max_readings
contours_info = contours_info[-max_readings:]
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Salva os dados em um arquivo JSON
with open(output_path, 'w') as f:
json.dump(contours_info, f, indent=4)
json_reading_data = json_data
# Função para decodificar e aplicar o mapa de segmentação em um frame
def apply_segmentation_overlay(frame, output_predictions):
label_colors, class_names = read_labelmap(model_folder + "dataset/labelmap.txt")
nc = len(label_colors)
height, width, _ = frame.shape
overlay = np.zeros((height, width, 3), dtype=np.uint8)
# Redimensiona as previsões do modelo para corresponder ao tamanho do frame
output_predictions_resized = cv2.resize(output_predictions, (width, height), interpolation=cv2.INTER_NEAREST)
for l in np.unique(output_predictions_resized):
if l < nc:
mask = output_predictions_resized == l
overlay[mask] = label_colors[l]
# Combinação do frame original com o overlay da segmentação
overlayed_frame = cv2.addWeighted(frame, 0.6, overlay, 0.4, 0)
return overlayed_frame
# Função para processar e transmitir o vídeo
def detect_and_stream(camera_index):
cap = cv2.VideoCapture(camera_index)
while True:
ret, frame = cap.read()
if not ret:
break
frame = cv2.imread(model_folder + "dataset/images/81.jpeg")
# Processa o frame com seu modelo
output_predictions = segment_frame(frame)
# Aplica a segmentação sobre o frame capturado
overlayed_frame = apply_segmentation_overlay(frame, output_predictions)
frame_saida = overlayed_frame if show_lines == 1 else frame
# Codifica o frame para JPEG e transmite
ret, buffer = cv2.imencode('.jpg', frame_saida)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
# Função para lidar com a conexão de cada cliente
def handle_client_connection(client_socket):
try:
while True:
# Enviar o dicionário serializado em JSON
client_socket.send(json.dumps(json_reading_data).encode('utf-8'))
# Aguardar um pouco antes de enviar os próximos dados
time.sleep(0.2)
except socket.error:
print(f"Cliente desconectado.")
finally:
# Fechar a conexão do socket ao sair do loop
client_socket.close()
# Configuração inicial do servidor de socket
def start_server(address='localhost', port=socket_port):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((address, socket_port))
server.listen()
print(f"Servidor iniciado. Aguardando conexões em {address}:{socket_port}...")
try:
while True:
client_sock, address = server.accept()
print(f"Aceitando conexão de {address[0]}:{address[1]}")
client_handler = threading.Thread(
target=handle_client_connection,
args=(client_sock,)
)
client_handler.start()
finally:
server.close()
# Esta função é para iniciar o servidor de socket em uma thread separada
def run_socket_server():
start_server()
@app.route('/' + url, methods=['GET'])
def stream():
camera_index = int(request.args.get('camera_index'))
return Response(detect_and_stream(camera_index),
mimetype='multipart/x-mixed-replace; boundary=frame')
def run_flask_server():
app.run(host='0.0.0.0', port=port, threaded=True, debug=False)
# Iniciar o servidor
if __name__ == '__main__':
# Inicia o servidor de socket em uma thread separada
socket_server_thread = threading.Thread(target=run_socket_server)
socket_server_thread.start()
# Inicia o servidor Flask na thread principal
run_flask_server()

View File

@ -0,0 +1,161 @@
import cv2
import numpy as np
from flask import Flask, Response, request
import json
import time
import socket
import threading
import sys
import os
# Adiciona as configurações do modelo YOLO
model_config = 'C:\\train\\models\\ervas\\ervas.cfg'
model_weights = 'C:\\train\\models\\ervas\\backup\\ervas_final.weights'
labels_path = 'C:\\train\\models\\ervas\\labels.txt'
# Carregar as classes
with open(labels_path, 'rt') as f:
classes = f.read().rstrip('\n').split('\n')
# Carregar o modelo YOLO
net = cv2.dnn.readNetFromDarknet(model_config, model_weights)
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL)
# Outras configurações
json_data = None
output_folder = 'Python/Output/'
max_readings = int(sys.argv[1])
porta = sys.argv[2]
url = sys.argv[3]
arquivoSaida = sys.argv[4]
mostrar_linhas = sys.argv[5] == "1"
socket_porta = int(sys.argv[6])
app = Flask(__name__)
# Função adaptada para detecção de ervas usando YOLO
def detect_objects(conf_threshold, nms_threshold, _camera_index):
cap = cv2.VideoCapture(_camera_index, cv2.CAP_DSHOW)
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
readings = []
while True:
ret, frame = cap.read()
if not ret:
break
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(net.getUnconnectedOutLayersNames())
current_readings = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > conf_threshold:
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
# Salvar as informações da detecção
detection_info = {
'id': int(class_id),
'descricao': classes[class_id],
'x': int(x),
'y': int(y),
'largura': int(w),
'altura': int(h),
'confianca': float(confidence)
}
current_readings.append(detection_info)
if mostrar_linhas:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(frame, f'{classes[class_id]} {confidence:.2f}', (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
global json_data
timestamp = time.time()
json_data = {'timestamp': timestamp, 'x_max': width, 'y_max': height, 'objetos': current_readings}
readings.append(json_data)
if not os.path.exists(output_folder):
os.makedirs(output_folder)
if len(readings) > max_readings:
readings.pop(0)
with open(output_folder + arquivoSaida, 'w') as file:
json.dump(readings, file, indent=4)
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
# Função para lidar com a conexão de cada cliente
def handle_client_connection(client_socket):
try:
while True:
# Enviar o dicionário serializado em JSON
client_socket.send(json.dumps(json_data).encode('utf-8'))
# Aguardar um pouco antes de enviar os próximos dados
time.sleep(0.2)
except socket.error:
print(f"Cliente desconectado.")
finally:
# Fechar a conexão do socket ao sair do loop
client_socket.close()
# Configuração inicial do servidor de socket
def start_server(address='localhost', port=socket_porta):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((address, port))
server.listen()
print(f"Servidor iniciado. Aguardando conexões em {address}:{port}...")
try:
while True:
client_sock, address = server.accept()
print(f"Aceitando conexão de {address[0]}:{address[1]}")
client_handler = threading.Thread(
target=handle_client_connection,
args=(client_sock,)
)
client_handler.start()
finally:
server.close()
# Esta função é para iniciar o servidor de socket em uma thread separada
def run_socket_server():
start_server()
# Iniciar o servidor Flask em uma thread separada
def run_flask_server():
app.run(host='0.0.0.0', port=porta, threaded=True, debug=False)
@app.route('/' + url, methods=['GET'])
def video_feed():
conf_threshold = float(request.args.get('conf_threshold'))
nms_threshold = float(request.args.get('nms_threshold'))
camera_index = int(request.args.get('camera_index'))
return Response(detect_objects(conf_threshold, nms_threshold, camera_index), mimetype='multipart/x-mixed-replace; boundary=frame')
# Iniciar o servidor
if __name__ == '__main__':
# Inicia o servidor de socket em uma thread separada
socket_server_thread = threading.Thread(target=run_socket_server)
socket_server_thread.start()
# Inicia o servidor Flask na thread principal
run_flask_server()

View File

@ -77,10 +77,13 @@ namespace AgroBase.Services
var camerasList = new Dictionary<string, string>();
using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE (PNPClass = 'Image' OR PNPClass = 'Camera')"))
{
int i = 0;
foreach (var device in searcher.Get())
{
camerasList.Add(device["DeviceID"].ToString(), device["Caption"].ToString());
cameraNames.Add(device["Caption"].ToString());
string cameraDesc = i.ToString() + " - " + device["Caption"].ToString();
camerasList.Add(device["DeviceID"].ToString(), cameraDesc);
cameraNames.Add(cameraDesc);
i++;
}
}

View File

@ -82,7 +82,7 @@ namespace AgroBase.Comum
{
cmbPorta.Items.Clear();
cmbPorta.Text = "";
var DispositivosTipo = SerialService.DispositivosConectados.Where(x => x.Dispositivo == Dispositivo).ToList();
var DispositivosTipo = SerialService.DispositivosMapeados.Where(x => x.Dispositivo == Dispositivo).ToList();
for (int i = 0; i < DispositivosTipo.Count(); i++)
{
string PortaCom = DispositivosTipo[i].PortaCOM;
@ -641,7 +641,7 @@ namespace AgroBase.Comum
}
}
private void btnConectar_Click(object sender, EventArgs e)
public void btnConectar_Click(object sender, EventArgs e)
{
List<string> Config = new List<string>();

View File

@ -32,6 +32,8 @@ namespace AgroBase.Services
}
public static void IniciarRecepcaoDados()
{
try
{
if (PortaGPS != null)
{
@ -43,6 +45,12 @@ namespace AgroBase.Services
}
}
}
catch
{
PortaGPS = null;
}
}
public static void PararRecepcaoDados()
{

View File

@ -28,5 +28,6 @@ namespace AgroBase.Services
void SalvarParametros(DispositivoBaseModel dados);
void LimparBufferSerial(bool LimparConsole);
void EnviarDadosSerial(string Protocolo);
void btnConectar_Click(object sender, EventArgs e);
}
}

View File

@ -13,7 +13,8 @@ namespace AgroBase.Services
public static string CaminhoScripts = "Scripts\\";
public static string CaminhoLeitura = "Output\\";
public static string ScriptGreenDetector = "green-detector.py";
public static string ScriptWeedDetector = "weed-detector.py";
public static string ScriptStreetDetector = "street-detector.py";
public static string ScriptMapConverter = "map-load.py";
public static string ScriptLineAngle = "line-angle2.py";
public static string ScriptMapGPS = "gps-viewer.py";

View File

@ -19,12 +19,12 @@ namespace AgroBase.Services
public T_Code Dispositivo { get; set; }
}
public static List<DispositivoDetalhesModel> DispositivosConectados = new List<DispositivoDetalhesModel>();
public static List<DispositivoDetalhesModel> DispositivosMapeados = new List<DispositivoDetalhesModel>();
public static void AtualizarDispositivos()
{
var Portas = SerialPort.GetPortNames();
var PortasNaoMapeadas = Portas.Where(x => !DispositivosConectados.Select(y => y.PortaCOM).Contains(x)).ToList();
var PortasNaoMapeadas = Portas.Where(x => !DispositivosMapeados.Select(y => y.PortaCOM).Contains(x)).ToList();
if (GPSService.PortaGPS != null)
{
PortasNaoMapeadas = PortasNaoMapeadas.Where(x => x != GPSService.PortaGPS.PortName).ToList();
@ -47,10 +47,10 @@ namespace AgroBase.Services
}
}
var DispositivosRemovidos = DispositivosConectados.Where(x => !Portas.Contains(x.PortaCOM)).ToList();
var DispositivosRemovidos = DispositivosMapeados.Where(x => !Portas.Contains(x.PortaCOM)).ToList();
foreach (var Dispositivo in DispositivosRemovidos)
{
DispositivosConectados.Remove(Dispositivo);
DispositivosMapeados.Remove(Dispositivo);
}
}
@ -82,7 +82,7 @@ namespace AgroBase.Services
if (Dispositivo != T_Code.Vzo)
{
DispositivosConectados.Add(new DispositivoDetalhesModel()
DispositivosMapeados.Add(new DispositivoDetalhesModel()
{
PortaCOM = Porta.PortName,
Dispositivo = Dispositivo

View File

@ -16,14 +16,25 @@ namespace AgroBase.Services
private byte[] buffer = new byte[1024];
public List<T> DadosRecebidos = new List<T>();
public void Connect(string host, int port, int _Registrar = 50)
public void Connect(string host, int port, int _Registrar = 50, int Tentativa = 0)
{
DadosRegistrar = _Registrar;
try
{
client = new TcpClient(host, port);
stream = client.GetStream();
stream.BeginRead(buffer, 0, buffer.Length, OnRead, null);
}
catch
{
if (Tentativa < 3)
{
Tentativa++;
Connect(host, port, Tentativa);
}
}
}
private void OnRead(IAsyncResult ar)
{

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
from .modeling import *
from ._deeplab import convert_to_separable_conv

View File

@ -0,0 +1,178 @@
import torch
from torch import nn
from torch.nn import functional as F
from .utils import _SimpleSegmentationModel
__all__ = ["DeepLabV3"]
class DeepLabV3(_SimpleSegmentationModel):
"""
Implements DeepLabV3 model from
`"Rethinking Atrous Convolution for Semantic Image Segmentation"
<https://arxiv.org/abs/1706.05587>`_.
Arguments:
backbone (nn.Module): the network used to compute the features for the model.
The backbone should return an OrderedDict[Tensor], with the key being
"out" for the last feature map used, and "aux" if an auxiliary classifier
is used.
classifier (nn.Module): module that takes the "out" element returned from
the backbone and returns a dense prediction.
aux_classifier (nn.Module, optional): auxiliary classifier used during training
"""
pass
class DeepLabHeadV3Plus(nn.Module):
def __init__(self, in_channels, low_level_channels, num_classes, aspp_dilate=[12, 24, 36]):
super(DeepLabHeadV3Plus, self).__init__()
self.project = nn.Sequential(
nn.Conv2d(low_level_channels, 48, 1, bias=False),
nn.BatchNorm2d(48),
nn.ReLU(inplace=True),
)
self.aspp = ASPP(in_channels, aspp_dilate)
self.classifier = nn.Sequential(
nn.Conv2d(304, 256, 3, padding=1, bias=False),
nn.BatchNorm2d(256),
nn.ReLU(inplace=True),
nn.Conv2d(256, num_classes, 1)
)
self._init_weight()
def forward(self, feature):
low_level_feature = self.project( feature['low_level'] )
output_feature = self.aspp(feature['out'])
output_feature = F.interpolate(output_feature, size=low_level_feature.shape[2:], mode='bilinear', align_corners=False)
return self.classifier( torch.cat( [ low_level_feature, output_feature ], dim=1 ) )
def _init_weight(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
class DeepLabHead(nn.Module):
def __init__(self, in_channels, num_classes, aspp_dilate=[12, 24, 36]):
super(DeepLabHead, self).__init__()
self.classifier = nn.Sequential(
ASPP(in_channels, aspp_dilate),
nn.Conv2d(256, 256, 3, padding=1, bias=False),
nn.BatchNorm2d(256),
nn.ReLU(inplace=True),
nn.Conv2d(256, num_classes, 1)
)
self._init_weight()
def forward(self, feature):
return self.classifier( feature['out'] )
def _init_weight(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
class AtrousSeparableConvolution(nn.Module):
""" Atrous Separable Convolution
"""
def __init__(self, in_channels, out_channels, kernel_size,
stride=1, padding=0, dilation=1, bias=True):
super(AtrousSeparableConvolution, self).__init__()
self.body = nn.Sequential(
# Separable Conv
nn.Conv2d( in_channels, in_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=bias, groups=in_channels ),
# PointWise Conv
nn.Conv2d( in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=bias),
)
self._init_weight()
def forward(self, x):
return self.body(x)
def _init_weight(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
class ASPPConv(nn.Sequential):
def __init__(self, in_channels, out_channels, dilation):
modules = [
nn.Conv2d(in_channels, out_channels, 3, padding=dilation, dilation=dilation, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
]
super(ASPPConv, self).__init__(*modules)
class ASPPPooling(nn.Sequential):
def __init__(self, in_channels, out_channels):
super(ASPPPooling, self).__init__(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(in_channels, out_channels, 1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True))
def forward(self, x):
size = x.shape[-2:]
x = super(ASPPPooling, self).forward(x)
return F.interpolate(x, size=size, mode='bilinear', align_corners=False)
class ASPP(nn.Module):
def __init__(self, in_channels, atrous_rates):
super(ASPP, self).__init__()
out_channels = 256
modules = []
modules.append(nn.Sequential(
nn.Conv2d(in_channels, out_channels, 1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)))
rate1, rate2, rate3 = tuple(atrous_rates)
modules.append(ASPPConv(in_channels, out_channels, rate1))
modules.append(ASPPConv(in_channels, out_channels, rate2))
modules.append(ASPPConv(in_channels, out_channels, rate3))
modules.append(ASPPPooling(in_channels, out_channels))
self.convs = nn.ModuleList(modules)
self.project = nn.Sequential(
nn.Conv2d(5 * out_channels, out_channels, 1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Dropout(0.1),)
def forward(self, x):
res = []
for conv in self.convs:
res.append(conv(x))
res = torch.cat(res, dim=1)
return self.project(res)
def convert_to_separable_conv(module):
new_module = module
if isinstance(module, nn.Conv2d) and module.kernel_size[0]>1:
new_module = AtrousSeparableConvolution(module.in_channels,
module.out_channels,
module.kernel_size,
module.stride,
module.padding,
module.dilation,
module.bias)
for name, child in module.named_children():
new_module.add_module(name, convert_to_separable_conv(child))
return new_module

View File

@ -0,0 +1,4 @@
from . import resnet
from . import mobilenetv2
from . import hrnetv2
from . import xception

View File

@ -0,0 +1,345 @@
import torch
from torch import nn
import torch.nn.functional as F
import os
__all__ = ['HRNet', 'hrnetv2_48', 'hrnetv2_32']
# Checkpoint path of pre-trained backbone (edit to your path). Download backbone pretrained model hrnetv2-32 @
# https://drive.google.com/file/d/1NxCK7Zgn5PmeS7W1jYLt5J9E0RRZ2oyF/view?usp=sharing .Personally, I added the backbone
# weights to the folder /checkpoints
model_urls = {
'hrnetv2_32': './checkpoints/model_best_epoch96_edit.pth',
'hrnetv2_48': None
}
def check_pth(arch):
CKPT_PATH = model_urls[arch]
if os.path.exists(CKPT_PATH):
print(f"Backbone HRNet Pretrained weights at: {CKPT_PATH}, only usable for HRNetv2-32")
else:
print("No backbone checkpoint found for HRNetv2, please set pretrained=False when calling model")
return CKPT_PATH
# HRNetv2-48 not available yet, but you can train the whole model from scratch.
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class StageModule(nn.Module):
def __init__(self, stage, output_branches, c):
super(StageModule, self).__init__()
self.number_of_branches = stage # number of branches is equivalent to the stage configuration.
self.output_branches = output_branches
self.branches = nn.ModuleList()
# Note: Resolution + Number of channels maintains the same throughout respective branch.
for i in range(self.number_of_branches): # Stage scales with the number of branches. Ex: Stage 2 -> 2 branch
channels = c * (2 ** i) # Scale channels by 2x for branch with lower resolution,
# Paper does x4 basic block for each forward sequence in each branch (x4 basic block considered as a block)
branch = nn.Sequential(*[BasicBlock(channels, channels) for _ in range(4)])
self.branches.append(branch) # list containing all forward sequence of individual branches.
# For each branch requires repeated fusion with all other branches after passing through x4 basic blocks.
self.fuse_layers = nn.ModuleList()
for branch_output_number in range(self.output_branches):
self.fuse_layers.append(nn.ModuleList())
for branch_number in range(self.number_of_branches):
if branch_number == branch_output_number:
self.fuse_layers[-1].append(nn.Sequential()) # Used in place of "None" because it is callable
elif branch_number > branch_output_number:
self.fuse_layers[-1].append(nn.Sequential(
nn.Conv2d(c * (2 ** branch_number), c * (2 ** branch_output_number), kernel_size=1, stride=1,
bias=False),
nn.BatchNorm2d(c * (2 ** branch_output_number), eps=1e-05, momentum=0.1, affine=True,
track_running_stats=True),
nn.Upsample(scale_factor=(2.0 ** (branch_number - branch_output_number)), mode='nearest'),
))
elif branch_number < branch_output_number:
downsampling_fusion = []
for _ in range(branch_output_number - branch_number - 1):
downsampling_fusion.append(nn.Sequential(
nn.Conv2d(c * (2 ** branch_number), c * (2 ** branch_number), kernel_size=3, stride=2,
padding=1,
bias=False),
nn.BatchNorm2d(c * (2 ** branch_number), eps=1e-05, momentum=0.1, affine=True,
track_running_stats=True),
nn.ReLU(inplace=True),
))
downsampling_fusion.append(nn.Sequential(
nn.Conv2d(c * (2 ** branch_number), c * (2 ** branch_output_number), kernel_size=3,
stride=2, padding=1,
bias=False),
nn.BatchNorm2d(c * (2 ** branch_output_number), eps=1e-05, momentum=0.1, affine=True,
track_running_stats=True),
))
self.fuse_layers[-1].append(nn.Sequential(*downsampling_fusion))
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
# input to each stage is a list of inputs for each branch
x = [branch(branch_input) for branch, branch_input in zip(self.branches, x)]
x_fused = []
for branch_output_index in range(
self.output_branches): # Amount of output branches == total length of fusion layers
for input_index in range(self.number_of_branches): # The inputs of other branches to be fused.
if input_index == 0:
x_fused.append(self.fuse_layers[branch_output_index][input_index](x[input_index]))
else:
x_fused[branch_output_index] = x_fused[branch_output_index] + self.fuse_layers[branch_output_index][
input_index](x[input_index])
# After fusing all streams together, you will need to pass the fused layers
for i in range(self.output_branches):
x_fused[i] = self.relu(x_fused[i])
return x_fused # returning a list of fused outputs
class HRNet(nn.Module):
def __init__(self, c=48, num_blocks=[1, 4, 3], num_classes=1000):
super(HRNet, self).__init__()
# Stem:
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64, eps=1e-05, affine=True, track_running_stats=True)
self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(64, eps=1e-05, affine=True, track_running_stats=True)
self.relu = nn.ReLU(inplace=True)
# Stage 1:
downsample = nn.Sequential(
nn.Conv2d(64, 256, kernel_size=1, stride=1, bias=False),
nn.BatchNorm2d(256, eps=1e-05, affine=True, track_running_stats=True),
)
# Note that bottleneck module will expand the output channels according to the output channels*block.expansion
bn_expansion = Bottleneck.expansion # The channel expansion is set in the bottleneck class.
self.layer1 = nn.Sequential(
Bottleneck(64, 64, downsample=downsample), # Input is 64 for first module connection
Bottleneck(bn_expansion * 64, 64),
Bottleneck(bn_expansion * 64, 64),
Bottleneck(bn_expansion * 64, 64),
)
# Transition 1 - Creation of the first two branches (one full and one half resolution)
# Need to transition into high resolution stream and mid resolution stream
self.transition1 = nn.ModuleList([
nn.Sequential(
nn.Conv2d(256, c, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(c, eps=1e-05, affine=True, track_running_stats=True),
nn.ReLU(inplace=True),
),
nn.Sequential(nn.Sequential( # Double Sequential to fit with official pretrained weights
nn.Conv2d(256, c * 2, kernel_size=3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(c * 2, eps=1e-05, affine=True, track_running_stats=True),
nn.ReLU(inplace=True),
)),
])
# Stage 2:
number_blocks_stage2 = num_blocks[0]
self.stage2 = nn.Sequential(
*[StageModule(stage=2, output_branches=2, c=c) for _ in range(number_blocks_stage2)])
# Transition 2 - Creation of the third branch (1/4 resolution)
self.transition2 = self._make_transition_layers(c, transition_number=2)
# Stage 3:
number_blocks_stage3 = num_blocks[1] # number blocks you want to create before fusion
self.stage3 = nn.Sequential(
*[StageModule(stage=3, output_branches=3, c=c) for _ in range(number_blocks_stage3)])
# Transition - Creation of the fourth branch (1/8 resolution)
self.transition3 = self._make_transition_layers(c, transition_number=3)
# Stage 4:
number_blocks_stage4 = num_blocks[2] # number blocks you want to create before fusion
self.stage4 = nn.Sequential(
*[StageModule(stage=4, output_branches=4, c=c) for _ in range(number_blocks_stage4)])
# Classifier (extra module if want to use for classification):
# pool, reduce dimensionality, flatten, connect to linear layer for classification:
out_channels = sum([c * 2 ** i for i in range(len(num_blocks)+1)]) # total output channels of HRNetV2
pool_feature_map = 8
self.bn_classifier = nn.Sequential(
nn.Conv2d(out_channels, out_channels // 4, kernel_size=1, bias=False),
nn.BatchNorm2d(out_channels // 4, eps=1e-05, affine=True, track_running_stats=True),
nn.ReLU(inplace=True),
nn.AdaptiveAvgPool2d(pool_feature_map),
nn.Flatten(),
nn.Linear(pool_feature_map * pool_feature_map * (out_channels // 4), num_classes),
)
@staticmethod
def _make_transition_layers(c, transition_number):
return nn.Sequential(
nn.Conv2d(c * (2 ** (transition_number - 1)), c * (2 ** transition_number), kernel_size=3, stride=2,
padding=1, bias=False),
nn.BatchNorm2d(c * (2 ** transition_number), eps=1e-05, affine=True,
track_running_stats=True),
nn.ReLU(inplace=True),
)
def forward(self, x):
# Stem:
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu(x)
# Stage 1
x = self.layer1(x)
x = [trans(x) for trans in self.transition1] # split to 2 branches, form a list.
# Stage 2
x = self.stage2(x)
x.append(self.transition2(x[-1]))
# Stage 3
x = self.stage3(x)
x.append(self.transition3(x[-1]))
# Stage 4
x = self.stage4(x)
# HRNetV2 Example: (follow paper, upsample via bilinear interpolation and to highest resolution size)
output_h, output_w = x[0].size(2), x[0].size(3) # Upsample to size of highest resolution stream
x1 = F.interpolate(x[1], size=(output_h, output_w), mode='bilinear', align_corners=False)
x2 = F.interpolate(x[2], size=(output_h, output_w), mode='bilinear', align_corners=False)
x3 = F.interpolate(x[3], size=(output_h, output_w), mode='bilinear', align_corners=False)
# Upsampling all the other resolution streams and then concatenate all (rather than adding/fusing like HRNetV1)
x = torch.cat([x[0], x1, x2, x3], dim=1)
x = self.bn_classifier(x)
return x
def _hrnet(arch, channels, num_blocks, pretrained, progress, **kwargs):
model = HRNet(channels, num_blocks, **kwargs)
if pretrained:
CKPT_PATH = check_pth(arch)
checkpoint = torch.load(CKPT_PATH)
model.load_state_dict(checkpoint['state_dict'])
return model
def hrnetv2_48(pretrained=False, progress=True, number_blocks=[1, 4, 3], **kwargs):
w_channels = 48
return _hrnet('hrnetv2_48', w_channels, number_blocks, pretrained, progress,
**kwargs)
def hrnetv2_32(pretrained=False, progress=True, number_blocks=[1, 4, 3], **kwargs):
w_channels = 32
return _hrnet('hrnetv2_32', w_channels, number_blocks, pretrained, progress,
**kwargs)
if __name__ == '__main__':
try:
CKPT_PATH = os.path.join(os.path.abspath("."), '../../checkpoints/hrnetv2_32_model_best_epoch96.pth')
print("--- Running file as MAIN ---")
print(f"Backbone HRNET Pretrained weights as __main__ at: {CKPT_PATH}")
except:
print("No backbone checkpoint found for HRNetv2, please set pretrained=False when calling model")
# Models
model = hrnetv2_32(pretrained=True)
#model = hrnetv2_48(pretrained=False)
if torch.cuda.is_available():
torch.backends.cudnn.deterministic = True
device = torch.device('cuda')
else:
device = torch.device('cpu')
model.to(device)
in_ = torch.ones(1, 3, 768, 768).to(device)
y = model(in_)
print(y.shape)
# Calculate total number of parameters:
# pytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
# print(pytorch_total_params)

View File

@ -0,0 +1,190 @@
from torch import nn
try: # for torchvision<0.4
from torchvision.models.utils import load_state_dict_from_url
except: # for torchvision>=0.4
from torch.hub import load_state_dict_from_url
import torch.nn.functional as F
__all__ = ['MobileNetV2', 'mobilenet_v2']
model_urls = {
'mobilenet_v2': 'https://download.pytorch.org/models/mobilenet_v2-b0353104.pth',
}
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:param v:
:param divisor:
:param min_value:
:return:
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v
class ConvBNReLU(nn.Sequential):
def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, dilation=1, groups=1):
#padding = (kernel_size - 1) // 2
super(ConvBNReLU, self).__init__(
nn.Conv2d(in_planes, out_planes, kernel_size, stride, 0, dilation=dilation, groups=groups, bias=False),
nn.BatchNorm2d(out_planes),
nn.ReLU6(inplace=True)
)
def fixed_padding(kernel_size, dilation):
kernel_size_effective = kernel_size + (kernel_size - 1) * (dilation - 1)
pad_total = kernel_size_effective - 1
pad_beg = pad_total // 2
pad_end = pad_total - pad_beg
return (pad_beg, pad_end, pad_beg, pad_end)
class InvertedResidual(nn.Module):
def __init__(self, inp, oup, stride, dilation, expand_ratio):
super(InvertedResidual, self).__init__()
self.stride = stride
assert stride in [1, 2]
hidden_dim = int(round(inp * expand_ratio))
self.use_res_connect = self.stride == 1 and inp == oup
layers = []
if expand_ratio != 1:
# pw
layers.append(ConvBNReLU(inp, hidden_dim, kernel_size=1))
layers.extend([
# dw
ConvBNReLU(hidden_dim, hidden_dim, stride=stride, dilation=dilation, groups=hidden_dim),
# pw-linear
nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
nn.BatchNorm2d(oup),
])
self.conv = nn.Sequential(*layers)
self.input_padding = fixed_padding( 3, dilation )
def forward(self, x):
x_pad = F.pad(x, self.input_padding)
if self.use_res_connect:
return x + self.conv(x_pad)
else:
return self.conv(x_pad)
class MobileNetV2(nn.Module):
def __init__(self, num_classes=1000, output_stride=8, width_mult=1.0, inverted_residual_setting=None, round_nearest=8):
"""
MobileNet V2 main class
Args:
num_classes (int): Number of classes
width_mult (float): Width multiplier - adjusts number of channels in each layer by this amount
inverted_residual_setting: Network structure
round_nearest (int): Round the number of channels in each layer to be a multiple of this number
Set to 1 to turn off rounding
"""
super(MobileNetV2, self).__init__()
block = InvertedResidual
input_channel = 32
last_channel = 1280
self.output_stride = output_stride
current_stride = 1
if inverted_residual_setting is None:
inverted_residual_setting = [
# t, c, n, s
[1, 16, 1, 1],
[6, 24, 2, 2],
[6, 32, 3, 2],
[6, 64, 4, 2],
[6, 96, 3, 1],
[6, 160, 3, 2],
[6, 320, 1, 1],
]
# only check the first element, assuming user knows t,c,n,s are required
if len(inverted_residual_setting) == 0 or len(inverted_residual_setting[0]) != 4:
raise ValueError("inverted_residual_setting should be non-empty "
"or a 4-element list, got {}".format(inverted_residual_setting))
# building first layer
input_channel = _make_divisible(input_channel * width_mult, round_nearest)
self.last_channel = _make_divisible(last_channel * max(1.0, width_mult), round_nearest)
features = [ConvBNReLU(3, input_channel, stride=2)]
current_stride *= 2
dilation=1
previous_dilation = 1
# building inverted residual blocks
for t, c, n, s in inverted_residual_setting:
output_channel = _make_divisible(c * width_mult, round_nearest)
previous_dilation = dilation
if current_stride == output_stride:
stride = 1
dilation *= s
else:
stride = s
current_stride *= s
output_channel = int(c * width_mult)
for i in range(n):
if i==0:
features.append(block(input_channel, output_channel, stride, previous_dilation, expand_ratio=t))
else:
features.append(block(input_channel, output_channel, 1, dilation, expand_ratio=t))
input_channel = output_channel
# building last several layers
features.append(ConvBNReLU(input_channel, self.last_channel, kernel_size=1))
# make it nn.Sequential
self.features = nn.Sequential(*features)
# building classifier
self.classifier = nn.Sequential(
nn.Dropout(0.2),
nn.Linear(self.last_channel, num_classes),
)
# weight initialization
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out')
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.BatchNorm2d):
nn.init.ones_(m.weight)
nn.init.zeros_(m.bias)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
nn.init.zeros_(m.bias)
def forward(self, x):
x = self.features(x)
x = x.mean([2, 3])
x = self.classifier(x)
return x
def mobilenet_v2(pretrained=False, progress=True, **kwargs):
"""
Constructs a MobileNetV2 architecture from
`"MobileNetV2: Inverted Residuals and Linear Bottlenecks" <https://arxiv.org/abs/1801.04381>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
model = MobileNetV2(**kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls['mobilenet_v2'],
progress=progress)
model.load_state_dict(state_dict)
return model

View File

@ -0,0 +1,346 @@
import torch
import torch.nn as nn
try: # for torchvision<0.4
from torchvision.models.utils import load_state_dict_from_url
except: # for torchvision>=0.4
from torch.hub import load_state_dict_from_url
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
'wide_resnet50_2', 'wide_resnet101_2']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
}
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=False, dilation=dilation)
def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(BasicBlock, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if groups != 1 or base_width != 64:
raise ValueError('BasicBlock only supports groups=1 and base_width=64')
if dilation > 1:
raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = norm_layer(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = norm_layer(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
width = int(planes * (base_width / 64.)) * groups
# Both self.conv2 and self.downsample layers downsample the input when stride != 1
self.conv1 = conv1x1(inplanes, width)
self.bn1 = norm_layer(width)
self.conv2 = conv3x3(width, width, stride, groups, dilation)
self.bn2 = norm_layer(width)
self.conv3 = conv1x1(width, planes * self.expansion)
self.bn3 = norm_layer(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None,
norm_layer=None):
super(ResNet, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
self._norm_layer = norm_layer
self.inplanes = 64
self.dilation = 1
if replace_stride_with_dilation is None:
# each element in the tuple indicates if we should replace
# the 2x2 stride with a dilated convolution instead
replace_stride_with_dilation = [False, False, False]
if len(replace_stride_with_dilation) != 3:
raise ValueError("replace_stride_with_dilation should be None "
"or a 3-element tuple, got {}".format(replace_stride_with_dilation))
self.groups = groups
self.base_width = width_per_group
self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = norm_layer(self.inplanes)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
dilate=replace_stride_with_dilation[0])
self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
dilate=replace_stride_with_dilation[1])
self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
dilate=replace_stride_with_dilation[2])
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
# Zero-initialize the last BN in each residual branch,
# so that the residual branch starts with zeros, and each residual block behaves like an identity.
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
if zero_init_residual:
for m in self.modules():
if isinstance(m, Bottleneck):
nn.init.constant_(m.bn3.weight, 0)
elif isinstance(m, BasicBlock):
nn.init.constant_(m.bn2.weight, 0)
def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(self.inplanes, planes * block.expansion, stride),
norm_layer(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
self.base_width, previous_dilation, norm_layer))
self.inplanes = planes * block.expansion
for _ in range(1, blocks):
layers.append(block(self.inplanes, planes, groups=self.groups,
base_width=self.base_width, dilation=self.dilation,
norm_layer=norm_layer))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.fc(x)
return x
def _resnet(arch, block, layers, pretrained, progress, **kwargs):
model = ResNet(block, layers, **kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls[arch],
progress=progress)
model.load_state_dict(state_dict)
return model
def resnet18(pretrained=False, progress=True, **kwargs):
r"""ResNet-18 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
**kwargs)
def resnet34(pretrained=False, progress=True, **kwargs):
r"""ResNet-34 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
**kwargs)
def resnet50(pretrained=False, progress=True, **kwargs):
r"""ResNet-50 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
**kwargs)
def resnet101(pretrained=False, progress=True, **kwargs):
r"""ResNet-101 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress,
**kwargs)
def resnet152(pretrained=False, progress=True, **kwargs):
r"""ResNet-152 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress,
**kwargs)
def resnext50_32x4d(pretrained=False, progress=True, **kwargs):
r"""ResNeXt-50 32x4d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
kwargs['groups'] = 32
kwargs['width_per_group'] = 4
return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3],
pretrained, progress, **kwargs)
def resnext101_32x8d(pretrained=False, progress=True, **kwargs):
r"""ResNeXt-101 32x8d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
kwargs['groups'] = 32
kwargs['width_per_group'] = 8
return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3],
pretrained, progress, **kwargs)
def wide_resnet50_2(pretrained=False, progress=True, **kwargs):
r"""Wide ResNet-50-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels in outer 1x1
convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
channels, and in Wide ResNet-50-2 has 2048-1024-2048.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
kwargs['width_per_group'] = 64 * 2
return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3],
pretrained, progress, **kwargs)
def wide_resnet101_2(pretrained=False, progress=True, **kwargs):
r"""Wide ResNet-101-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels in outer 1x1
convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
channels, and in Wide ResNet-50-2 has 2048-1024-2048.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
kwargs['width_per_group'] = 64 * 2
return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3],
pretrained, progress, **kwargs)

View File

@ -0,0 +1,238 @@
"""
Xception is adapted from https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/xception.py
Ported to pytorch thanks to [tstandley](https://github.com/tstandley/Xception-PyTorch)
@author: tstandley
Adapted by cadene
Creates an Xception Model as defined in:
Francois Chollet
Xception: Deep Learning with Depthwise Separable Convolutions
https://arxiv.org/pdf/1610.02357.pdf
This weights ported from the Keras implementation. Achieves the following performance on the validation set:
Loss:0.9173 Prec@1:78.892 Prec@5:94.292
REMEMBER to set your image size to 3x299x299 for both test and validation
normalize = transforms.Normalize(mean=[0.5, 0.5, 0.5],
std=[0.5, 0.5, 0.5])
The resize parameter of the validation transform should be 333, and make sure to center crop at 299x299
"""
from __future__ import print_function, division, absolute_import
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from torch.nn import init
__all__ = ['xception']
pretrained_settings = {
'xception': {
'imagenet': {
'url': 'http://data.lip6.fr/cadene/pretrainedmodels/xception-43020ad28.pth',
'input_space': 'RGB',
'input_size': [3, 299, 299],
'input_range': [0, 1],
'mean': [0.5, 0.5, 0.5],
'std': [0.5, 0.5, 0.5],
'num_classes': 1000,
'scale': 0.8975 # The resize parameter of the validation transform should be 333, and make sure to center crop at 299x299
}
}
}
class SeparableConv2d(nn.Module):
def __init__(self,in_channels,out_channels,kernel_size=1,stride=1,padding=0,dilation=1,bias=False):
super(SeparableConv2d,self).__init__()
self.conv1 = nn.Conv2d(in_channels,in_channels,kernel_size,stride,padding,dilation,groups=in_channels,bias=bias)
self.pointwise = nn.Conv2d(in_channels,out_channels,1,1,0,1,1,bias=bias)
def forward(self,x):
x = self.conv1(x)
x = self.pointwise(x)
return x
class Block(nn.Module):
def __init__(self,in_filters,out_filters,reps,strides=1,start_with_relu=True,grow_first=True, dilation=1):
super(Block, self).__init__()
if out_filters != in_filters or strides!=1:
self.skip = nn.Conv2d(in_filters,out_filters,1,stride=strides, bias=False)
self.skipbn = nn.BatchNorm2d(out_filters)
else:
self.skip=None
rep=[]
filters=in_filters
if grow_first:
rep.append(nn.ReLU(inplace=True))
rep.append(SeparableConv2d(in_filters,out_filters,3,stride=1,padding=dilation, dilation=dilation, bias=False))
rep.append(nn.BatchNorm2d(out_filters))
filters = out_filters
for i in range(reps-1):
rep.append(nn.ReLU(inplace=True))
rep.append(SeparableConv2d(filters,filters,3,stride=1,padding=dilation,dilation=dilation,bias=False))
rep.append(nn.BatchNorm2d(filters))
if not grow_first:
rep.append(nn.ReLU(inplace=True))
rep.append(SeparableConv2d(in_filters,out_filters,3,stride=1,padding=dilation,dilation=dilation,bias=False))
rep.append(nn.BatchNorm2d(out_filters))
if not start_with_relu:
rep = rep[1:]
else:
rep[0] = nn.ReLU(inplace=False)
if strides != 1:
rep.append(nn.MaxPool2d(3,strides,1))
self.rep = nn.Sequential(*rep)
def forward(self,inp):
x = self.rep(inp)
if self.skip is not None:
skip = self.skip(inp)
skip = self.skipbn(skip)
else:
skip = inp
x+=skip
return x
class Xception(nn.Module):
"""
Xception optimized for the ImageNet dataset, as specified in
https://arxiv.org/pdf/1610.02357.pdf
"""
def __init__(self, num_classes=1000, replace_stride_with_dilation=None):
""" Constructor
Args:
num_classes: number of classes
"""
super(Xception, self).__init__()
self.num_classes = num_classes
self.dilation = 1
if replace_stride_with_dilation is None:
# each element in the tuple indicates if we should replace
# the 2x2 stride with a dilated convolution instead
replace_stride_with_dilation = [False, False, False, False]
if len(replace_stride_with_dilation) != 4:
raise ValueError("replace_stride_with_dilation should be None "
"or a 4-element tuple, got {}".format(replace_stride_with_dilation))
self.conv1 = nn.Conv2d(3, 32, 3,2, 0, bias=False) # 1 / 2
self.bn1 = nn.BatchNorm2d(32)
self.relu1 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(32,64,3,bias=False)
self.bn2 = nn.BatchNorm2d(64)
self.relu2 = nn.ReLU(inplace=True)
#do relu here
self.block1=self._make_block(64,128,2,2,start_with_relu=False,grow_first=True, dilate=replace_stride_with_dilation[0]) # 1 / 4
self.block2=self._make_block(128,256,2,2,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[1]) # 1 / 8
self.block3=self._make_block(256,728,2,2,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2]) # 1 / 16
self.block4=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block5=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block6=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block7=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block8=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block9=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block10=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block11=self._make_block(728,728,3,1,start_with_relu=True,grow_first=True, dilate=replace_stride_with_dilation[2])
self.block12=self._make_block(728,1024,2,2,start_with_relu=True,grow_first=False, dilate=replace_stride_with_dilation[3]) # 1 / 32
self.conv3 = SeparableConv2d(1024,1536,3,1,1, dilation=self.dilation)
self.bn3 = nn.BatchNorm2d(1536)
self.relu3 = nn.ReLU(inplace=True)
#do relu here
self.conv4 = SeparableConv2d(1536,2048,3,1,1, dilation=self.dilation)
self.bn4 = nn.BatchNorm2d(2048)
self.fc = nn.Linear(2048, num_classes)
# #------- init weights --------
# for m in self.modules():
# if isinstance(m, nn.Conv2d):
# n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
# m.weight.data.normal_(0, math.sqrt(2. / n))
# elif isinstance(m, nn.BatchNorm2d):
# m.weight.data.fill_(1)
# m.bias.data.zero_()
# #-----------------------------
def _make_block(self, in_filters,out_filters,reps,strides=1,start_with_relu=True,grow_first=True, dilate=False):
if dilate:
self.dilation *= strides
strides = 1
return Block(in_filters,out_filters,reps,strides,start_with_relu=start_with_relu,grow_first=grow_first, dilation=self.dilation)
def features(self, input):
x = self.conv1(input)
x = self.bn1(x)
x = self.relu1(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu2(x)
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
x = self.block4(x)
x = self.block5(x)
x = self.block6(x)
x = self.block7(x)
x = self.block8(x)
x = self.block9(x)
x = self.block10(x)
x = self.block11(x)
x = self.block12(x)
x = self.conv3(x)
x = self.bn3(x)
x = self.relu3(x)
x = self.conv4(x)
x = self.bn4(x)
return x
def logits(self, features):
x = nn.ReLU(inplace=True)(features)
x = F.adaptive_avg_pool2d(x, (1, 1))
x = x.view(x.size(0), -1)
x = self.last_linear(x)
return x
def forward(self, input):
x = self.features(input)
x = self.logits(x)
return x
def xception(num_classes=1000, pretrained='imagenet', replace_stride_with_dilation=None):
model = Xception(num_classes=num_classes, replace_stride_with_dilation=replace_stride_with_dilation)
if pretrained:
settings = pretrained_settings['xception'][pretrained]
assert num_classes == settings['num_classes'], \
"num_classes should be {}, but is {}".format(settings['num_classes'], num_classes)
model = Xception(num_classes=num_classes, replace_stride_with_dilation=replace_stride_with_dilation)
model.load_state_dict(model_zoo.load_url(settings['url']))
# TODO: ugly
model.last_linear = model.fc
del model.fc
return model

View File

@ -0,0 +1,222 @@
from .utils import IntermediateLayerGetter
from ._deeplab import DeepLabHead, DeepLabHeadV3Plus, DeepLabV3
from .backbone import (
resnet,
mobilenetv2,
hrnetv2,
xception
)
def _segm_hrnet(name, backbone_name, num_classes, pretrained_backbone):
backbone = hrnetv2.__dict__[backbone_name](pretrained_backbone)
# HRNetV2 config:
# the final output channels is dependent on highest resolution channel config (c).
# output of backbone will be the inplanes to assp:
hrnet_channels = int(backbone_name.split('_')[-1])
inplanes = sum([hrnet_channels * 2 ** i for i in range(4)])
low_level_planes = 256 # all hrnet version channel output from bottleneck is the same
aspp_dilate = [12, 24, 36] # If follow paper trend, can put [24, 48, 72].
if name=='deeplabv3plus':
return_layers = {'stage4': 'out', 'layer1': 'low_level'}
classifier = DeepLabHeadV3Plus(inplanes, low_level_planes, num_classes, aspp_dilate)
elif name=='deeplabv3':
return_layers = {'stage4': 'out'}
classifier = DeepLabHead(inplanes, num_classes, aspp_dilate)
backbone = IntermediateLayerGetter(backbone, return_layers=return_layers, hrnet_flag=True)
model = DeepLabV3(backbone, classifier)
return model
def _segm_resnet(name, backbone_name, num_classes, output_stride, pretrained_backbone):
if output_stride==8:
replace_stride_with_dilation=[False, True, True]
aspp_dilate = [12, 24, 36]
else:
replace_stride_with_dilation=[False, False, True]
aspp_dilate = [6, 12, 18]
backbone = resnet.__dict__[backbone_name](
pretrained=pretrained_backbone,
replace_stride_with_dilation=replace_stride_with_dilation)
inplanes = 2048
low_level_planes = 256
if name=='deeplabv3plus':
return_layers = {'layer4': 'out', 'layer1': 'low_level'}
classifier = DeepLabHeadV3Plus(inplanes, low_level_planes, num_classes, aspp_dilate)
elif name=='deeplabv3':
return_layers = {'layer4': 'out'}
classifier = DeepLabHead(inplanes , num_classes, aspp_dilate)
backbone = IntermediateLayerGetter(backbone, return_layers=return_layers)
model = DeepLabV3(backbone, classifier)
return model
def _segm_xception(name, backbone_name, num_classes, output_stride, pretrained_backbone):
if output_stride==8:
replace_stride_with_dilation=[False, False, True, True]
aspp_dilate = [12, 24, 36]
else:
replace_stride_with_dilation=[False, False, False, True]
aspp_dilate = [6, 12, 18]
backbone = xception.xception(pretrained= 'imagenet' if pretrained_backbone else False, replace_stride_with_dilation=replace_stride_with_dilation)
inplanes = 2048
low_level_planes = 128
if name=='deeplabv3plus':
return_layers = {'conv4': 'out', 'block1': 'low_level'}
classifier = DeepLabHeadV3Plus(inplanes, low_level_planes, num_classes, aspp_dilate)
elif name=='deeplabv3':
return_layers = {'conv4': 'out'}
classifier = DeepLabHead(inplanes , num_classes, aspp_dilate)
backbone = IntermediateLayerGetter(backbone, return_layers=return_layers)
model = DeepLabV3(backbone, classifier)
return model
def _segm_mobilenet(name, backbone_name, num_classes, output_stride, pretrained_backbone):
if output_stride==8:
aspp_dilate = [12, 24, 36]
else:
aspp_dilate = [6, 12, 18]
backbone = mobilenetv2.mobilenet_v2(pretrained=pretrained_backbone, output_stride=output_stride)
# rename layers
backbone.low_level_features = backbone.features[0:4]
backbone.high_level_features = backbone.features[4:-1]
backbone.features = None
backbone.classifier = None
inplanes = 320
low_level_planes = 24
if name=='deeplabv3plus':
return_layers = {'high_level_features': 'out', 'low_level_features': 'low_level'}
classifier = DeepLabHeadV3Plus(inplanes, low_level_planes, num_classes, aspp_dilate)
elif name=='deeplabv3':
return_layers = {'high_level_features': 'out'}
classifier = DeepLabHead(inplanes , num_classes, aspp_dilate)
backbone = IntermediateLayerGetter(backbone, return_layers=return_layers)
model = DeepLabV3(backbone, classifier)
return model
def _load_model(arch_type, backbone, num_classes, output_stride, pretrained_backbone):
if backbone=='mobilenetv2':
model = _segm_mobilenet(arch_type, backbone, num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
elif backbone.startswith('resnet'):
model = _segm_resnet(arch_type, backbone, num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
elif backbone.startswith('hrnetv2'):
model = _segm_hrnet(arch_type, backbone, num_classes, pretrained_backbone=pretrained_backbone)
elif backbone=='xception':
model = _segm_xception(arch_type, backbone, num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
else:
raise NotImplementedError
return model
# Deeplab v3
def deeplabv3_hrnetv2_48(num_classes=21, output_stride=4, pretrained_backbone=False): # no pretrained backbone yet
return _load_model('deeplabv3', 'hrnetv2_48', output_stride, num_classes, pretrained_backbone=pretrained_backbone)
def deeplabv3_hrnetv2_32(num_classes=21, output_stride=4, pretrained_backbone=True):
return _load_model('deeplabv3', 'hrnetv2_32', output_stride, num_classes, pretrained_backbone=pretrained_backbone)
def deeplabv3_resnet50(num_classes=21, output_stride=8, pretrained_backbone=True):
"""Constructs a DeepLabV3 model with a ResNet-50 backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3', 'resnet50', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3_resnet101(num_classes=21, output_stride=8, pretrained_backbone=True):
"""Constructs a DeepLabV3 model with a ResNet-101 backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3', 'resnet101', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3_mobilenet(num_classes=21, output_stride=8, pretrained_backbone=True, **kwargs):
"""Constructs a DeepLabV3 model with a MobileNetv2 backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3', 'mobilenetv2', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3_xception(num_classes=21, output_stride=8, pretrained_backbone=True, **kwargs):
"""Constructs a DeepLabV3 model with a Xception backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3', 'xception', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
# Deeplab v3+
def deeplabv3plus_hrnetv2_48(num_classes=21, output_stride=4, pretrained_backbone=False): # no pretrained backbone yet
return _load_model('deeplabv3plus', 'hrnetv2_48', num_classes, output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3plus_hrnetv2_32(num_classes=21, output_stride=4, pretrained_backbone=True):
return _load_model('deeplabv3plus', 'hrnetv2_32', num_classes, output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3plus_resnet50(num_classes=21, output_stride=8, pretrained_backbone=True):
"""Constructs a DeepLabV3 model with a ResNet-50 backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3plus', 'resnet50', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3plus_resnet101(num_classes=21, output_stride=8, pretrained_backbone=True):
"""Constructs a DeepLabV3+ model with a ResNet-101 backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3plus', 'resnet101', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3plus_mobilenet(num_classes=21, output_stride=8, pretrained_backbone=True):
"""Constructs a DeepLabV3+ model with a MobileNetv2 backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3plus', 'mobilenetv2', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
def deeplabv3plus_xception(num_classes=21, output_stride=8, pretrained_backbone=True):
"""Constructs a DeepLabV3+ model with a Xception backbone.
Args:
num_classes (int): number of classes.
output_stride (int): output stride for deeplab.
pretrained_backbone (bool): If True, use the pretrained backbone.
"""
return _load_model('deeplabv3plus', 'xception', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)

View File

@ -0,0 +1,93 @@
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from collections import OrderedDict
class _SimpleSegmentationModel(nn.Module):
def __init__(self, backbone, classifier):
super(_SimpleSegmentationModel, self).__init__()
self.backbone = backbone
self.classifier = classifier
def forward(self, x):
input_shape = x.shape[-2:]
features = self.backbone(x)
x = self.classifier(features)
x = F.interpolate(x, size=input_shape, mode='bilinear', align_corners=False)
return x
class IntermediateLayerGetter(nn.ModuleDict):
"""
Module wrapper that returns intermediate layers from a model
It has a strong assumption that the modules have been registered
into the model in the same order as they are used.
This means that one should **not** reuse the same nn.Module
twice in the forward if you want this to work.
Additionally, it is only able to query submodules that are directly
assigned to the model. So if `model` is passed, `model.feature1` can
be returned, but not `model.feature1.layer2`.
Arguments:
model (nn.Module): model on which we will extract the features
return_layers (Dict[name, new_name]): a dict containing the names
of the modules for which the activations will be returned as
the key of the dict, and the value of the dict is the name
of the returned activation (which the user can specify).
Examples::
>>> m = torchvision.models.resnet18(pretrained=True)
>>> # extract layer1 and layer3, giving as names `feat1` and feat2`
>>> new_m = torchvision.models._utils.IntermediateLayerGetter(m,
>>> {'layer1': 'feat1', 'layer3': 'feat2'})
>>> out = new_m(torch.rand(1, 3, 224, 224))
>>> print([(k, v.shape) for k, v in out.items()])
>>> [('feat1', torch.Size([1, 64, 56, 56])),
>>> ('feat2', torch.Size([1, 256, 14, 14]))]
"""
def __init__(self, model, return_layers, hrnet_flag=False):
if not set(return_layers).issubset([name for name, _ in model.named_children()]):
raise ValueError("return_layers are not present in model")
self.hrnet_flag = hrnet_flag
orig_return_layers = return_layers
return_layers = {k: v for k, v in return_layers.items()}
layers = OrderedDict()
for name, module in model.named_children():
layers[name] = module
if name in return_layers:
del return_layers[name]
if not return_layers:
break
super(IntermediateLayerGetter, self).__init__(layers)
self.return_layers = orig_return_layers
def forward(self, x):
out = OrderedDict()
for name, module in self.named_children():
if self.hrnet_flag and name.startswith('transition'): # if using hrnet, you need to take care of transition
if name == 'transition1': # in transition1, you need to split the module to two streams first
x = [trans(x) for trans in module]
else: # all other transition is just an extra one stream split
x.append(module(x[-1]))
else: # other models (ex:resnet,mobilenet) are convolutions in series.
x = module(x)
if name in self.return_layers:
out_name = self.return_layers[name]
if name == 'stage4' and self.hrnet_flag: # In HRNetV2, we upsample and concat all outputs streams together
output_h, output_w = x[0].size(2), x[0].size(3) # Upsample to size of highest resolution stream
x1 = F.interpolate(x[1], size=(output_h, output_w), mode='bilinear', align_corners=False)
x2 = F.interpolate(x[2], size=(output_h, output_w), mode='bilinear', align_corners=False)
x3 = F.interpolate(x[3], size=(output_h, output_w), mode='bilinear', align_corners=False)
x = torch.cat([x[0], x1, x2, x3], dim=1)
out[out_name] = x
else:
out[out_name] = x
return out

View File

@ -1,61 +1,61 @@
[
{
"timestamp": 1706207157.286162,
"angulo": 71.05021207288564,
"timestamp": 1706880358.1525364,
"angulo": 87.70977125559801,
"distancia_esquerda": 0,
"distancia_direita": 0
},
{
"timestamp": 1706207157.3177145,
"angulo": 70.54673441821694,
"timestamp": 1706880358.187048,
"angulo": 88.078715127544,
"distancia_esquerda": 0,
"distancia_direita": 0
},
{
"timestamp": 1706207157.3347442,
"angulo": 70.54673441821694,
"timestamp": 1706880358.219048,
"angulo": 86.58086626250764,
"distancia_esquerda": 0,
"distancia_direita": 0
},
{
"timestamp": 1706207157.350775,
"angulo": 70.35967000187458,
"timestamp": 1706880358.250055,
"angulo": 87.94343067085526,
"distancia_esquerda": 0,
"distancia_direita": 0
},
{
"timestamp": 1706207157.3843591,
"angulo": 70.7433948934613,
"timestamp": 1706880358.2815716,
"angulo": 85.78628184333223,
"distancia_esquerda": 0,
"distancia_direita": 0
},
{
"timestamp": 1706207157.4129052,
"angulo": 71.39646382981618,
"timestamp": 1706880358.3130832,
"angulo": 88.35942134529364,
"distancia_esquerda": 0,
"distancia_direita": 0
},
{
"timestamp": 1706207157.4474494,
"angulo": 70.31913432628744,
"timestamp": 1706880358.3450816,
"angulo": 86.55045374535405,
"distancia_esquerda": 0,
"distancia_direita": 0
},
{
"timestamp": 1706207157.5130808,
"angulo": 70.1965576383513,
"timestamp": 1706880358.3786025,
"angulo": 86.5770408322993,
"distancia_esquerda": 0,
"distancia_direita": 0
},
{
"timestamp": 1706207157.5446432,
"angulo": 71.24957569783066,
"timestamp": 1706880358.4086025,
"angulo": 87.00165162526525,
"distancia_esquerda": 0,
"distancia_direita": 0
},
{
"timestamp": 1706207157.5737095,
"angulo": 70.41346870851675,
"timestamp": 1706880358.441602,
"angulo": 88.18265794687966,
"distancia_esquerda": 0,
"distancia_direita": 0
}

File diff suppressed because it is too large Load Diff

View File

@ -1,60 +1,60 @@
[
{
"timestamp": 1706207234.1478736,
"timestamp": 1706814334.1566775,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706207234.1804538,
"timestamp": 1706814334.1881938,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706207234.2275376,
"timestamp": 1706814334.2201939,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706207234.26012,
"timestamp": 1706814334.252192,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706207234.292677,
"timestamp": 1706814334.284705,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706207234.324238,
"timestamp": 1706814334.316218,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706207234.3568075,
"timestamp": 1706814334.348218,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706207234.3888829,
"timestamp": 1706814334.380732,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706207234.4204524,
"timestamp": 1706814334.4287317,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706207234.4525228,
"timestamp": 1706814334.4607384,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []

View File

@ -0,0 +1,62 @@
[
{
"timestamp": 1706880237.6169794,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706880237.6494894,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706880237.680491,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706880237.712496,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706880237.744011,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706880237.7760315,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706880237.8090327,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706880237.8405545,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706880237.8715544,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1706880237.9045656,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
}
]

View File

@ -0,0 +1,62 @@
[
{
"timestamp": 1707485821.8047965,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1707485821.990315,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1707485822.172832,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1707485822.358352,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1707485822.5488734,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1707485822.7363853,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1707485822.9339037,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1707485823.1304202,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1707485823.3329365,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
},
{
"timestamp": 1707485823.5494504,
"x_max": 640.0,
"y_max": 480.0,
"objetos": []
}
]

View File

@ -0,0 +1,236 @@
import torch
from PIL import Image
import torchvision.transforms as T
import numpy as np
import cv2
import json
import time
from flask import Flask, Response, request
import threading
import socket
import os
import sys
json_reading_data = None
output_folder = 'Python/Output/'
model_folder = 'C:\\train\\DeepLabV3Plus-Pytorch\\'
max_readings = int(sys.argv[1])
port = sys.argv[2]
url = sys.argv[3]
output_file = sys.argv[4]
show_lines = sys.argv[5] == "1"
socket_port = int(sys.argv[6])
app = Flask(__name__)
script_dir = os.path.dirname(__file__) # Obtém o diretório onde o script está localizado
parent_dir = os.path.dirname(script_dir) # Obtém o diretório pai (Python/)
sys.path.append(parent_dir)
# Supondo que você tenha a estrutura do repositório e o módulo `network` conforme descrito no README
from Models.deeplabv3plus.modeling import deeplabv3plus_resnet50 as deeplabv3_model
# Configurações Iniciais
NUM_CLASSES = 4 # Pascal VOC possui 3 classes + 1 para o fundo
OUTPUT_STRIDE = 16 # Valor comum para DeepLab
MODEL_PATH = model_folder + 'backup/ruasModel_final.pth' # Caminho para o modelo pré-treinado
# Função para carregar o modelo
def load_model(model_path):
model = deeplabv3_model(num_classes=NUM_CLASSES, output_stride=OUTPUT_STRIDE)
model.load_state_dict(torch.load(model_path), strict=False)
model.eval() # Modo de avaliação
return model
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Carregar o modelo
model = load_model(MODEL_PATH)
model.to(device)
# Função modificada para processar um frame da câmera
def segment_frame(frame):
# Converte o frame do OpenCV (BGR) para o formato RGB
image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
transform = T.Compose([
T.Resize(520),
T.ToTensor(),
T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
input_tensor = transform(image).unsqueeze(0).to(device)
with torch.no_grad():
output = model(input_tensor)
output_predictions = output.max(1)[1].squeeze().detach().cpu().numpy()
generate_and_save_json(output_predictions)
return output_predictions
def read_labelmap(path):
label_colors = []
class_names = []
with open(path, 'r') as file:
for line in file.readlines():
# Ignora linhas comentadas
if line.startswith('#'):
continue
parts = line.strip().split(':')
if len(parts) >= 2:
label = parts[0].strip()
color = tuple(map(int, parts[1].split(',')))
class_names.append(label)
label_colors.append(color)
return np.array(label_colors), class_names
def generate_and_save_json(image):
label_colors, class_names = read_labelmap(model_folder + "dataset/labelmap.txt")
detected_classes = set(np.unique(image))
global json_reading_data
contours_info = []
output_path = output_folder + output_file
# Carregar os dados existentes se o arquivo já existir
if os.path.exists(output_path):
with open(output_path, 'r') as f:
try:
existing_data = json.load(f)
if type(existing_data) is list:
contours_info.extend(existing_data)
except json.JSONDecodeError:
print("Erro ao decodificar o JSON existente. Um novo arquivo será criado.")
timestamp = time.time()
json_data = {'timestamp': timestamp, 'Classes': []}
for l in detected_classes:
if l < len(label_colors): # Verifica se o índice está dentro do intervalo das cores definidas
class_entry = {'Classe': class_names[l], 'Contornos': []}
# Extrai a máscara para a classe atual
mask = (image == l).astype(np.uint8) * 255
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
# Verifica se o contorno não está vazio e tem a dimensão adequada
if contour.size > 0:
# Para cada ponto no contorno, adiciona diretamente ao array Contornos
for point in contour:
class_entry['Contornos'].append(point.squeeze().tolist())
json_data['Classes'].append(class_entry)
contours_info.append(json_data)
# Limita a quantidade de registros a serem salvos com base em max_readings
contours_info = contours_info[-max_readings:]
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Salva os dados em um arquivo JSON
with open(output_path, 'w') as f:
json.dump(contours_info, f, indent=4)
json_reading_data = json_data
# Função para decodificar e aplicar o mapa de segmentação em um frame
def apply_segmentation_overlay(frame, output_predictions):
label_colors, class_names = read_labelmap(model_folder + "dataset/labelmap.txt")
nc = len(label_colors)
height, width, _ = frame.shape
overlay = np.zeros((height, width, 3), dtype=np.uint8)
# Redimensiona as previsões do modelo para corresponder ao tamanho do frame
output_predictions_resized = cv2.resize(output_predictions, (width, height), interpolation=cv2.INTER_NEAREST)
for l in np.unique(output_predictions_resized):
if l < nc:
mask = output_predictions_resized == l
overlay[mask] = label_colors[l]
# Combinação do frame original com o overlay da segmentação
overlayed_frame = cv2.addWeighted(frame, 0.6, overlay, 0.4, 0)
return overlayed_frame
# Função para processar e transmitir o vídeo
def detect_and_stream(camera_index):
cap = cv2.VideoCapture(camera_index)
while True:
ret, frame = cap.read()
if not ret:
break
frame = cv2.imread(model_folder + "dataset/images/81.jpeg")
# Processa o frame com seu modelo
output_predictions = segment_frame(frame)
# Aplica a segmentação sobre o frame capturado
overlayed_frame = apply_segmentation_overlay(frame, output_predictions)
frame_saida = overlayed_frame if show_lines == 1 else frame
# Codifica o frame para JPEG e transmite
ret, buffer = cv2.imencode('.jpg', frame_saida)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
# Função para lidar com a conexão de cada cliente
def handle_client_connection(client_socket):
try:
while True:
# Enviar o dicionário serializado em JSON
client_socket.send(json.dumps(json_reading_data).encode('utf-8'))
# Aguardar um pouco antes de enviar os próximos dados
time.sleep(0.2)
except socket.error:
print(f"Cliente desconectado.")
finally:
# Fechar a conexão do socket ao sair do loop
client_socket.close()
# Configuração inicial do servidor de socket
def start_server(address='localhost', port=socket_port):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((address, socket_port))
server.listen()
print(f"Servidor iniciado. Aguardando conexões em {address}:{socket_port}...")
try:
while True:
client_sock, address = server.accept()
print(f"Aceitando conexão de {address[0]}:{address[1]}")
client_handler = threading.Thread(
target=handle_client_connection,
args=(client_sock,)
)
client_handler.start()
finally:
server.close()
# Esta função é para iniciar o servidor de socket em uma thread separada
def run_socket_server():
start_server()
@app.route('/' + url, methods=['GET'])
def stream():
camera_index = int(request.args.get('camera_index'))
return Response(detect_and_stream(camera_index),
mimetype='multipart/x-mixed-replace; boundary=frame')
def run_flask_server():
app.run(host='0.0.0.0', port=port, threaded=True, debug=False)
# Iniciar o servidor
if __name__ == '__main__':
# Inicia o servidor de socket em uma thread separada
socket_server_thread = threading.Thread(target=run_socket_server)
socket_server_thread.start()
# Inicia o servidor Flask na thread principal
run_flask_server()

View File

@ -0,0 +1,161 @@
import cv2
import numpy as np
from flask import Flask, Response, request
import json
import time
import socket
import threading
import sys
import os
# Adiciona as configurações do modelo YOLO
model_config = 'C:\\train\\models\\ervas\\ervas.cfg'
model_weights = 'C:\\train\\models\\ervas\\backup\\ervas_final.weights'
labels_path = 'C:\\train\\models\\ervas\\labels.txt'
# Carregar as classes
with open(labels_path, 'rt') as f:
classes = f.read().rstrip('\n').split('\n')
# Carregar o modelo YOLO
net = cv2.dnn.readNetFromDarknet(model_config, model_weights)
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL)
# Outras configurações
json_data = None
output_folder = 'Python/Output/'
max_readings = int(sys.argv[1])
porta = sys.argv[2]
url = sys.argv[3]
arquivoSaida = sys.argv[4]
mostrar_linhas = sys.argv[5] == "1"
socket_porta = int(sys.argv[6])
app = Flask(__name__)
# Função adaptada para detecção de ervas usando YOLO
def detect_objects(conf_threshold, nms_threshold, _camera_index):
cap = cv2.VideoCapture(_camera_index, cv2.CAP_DSHOW)
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
readings = []
while True:
ret, frame = cap.read()
if not ret:
break
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(net.getUnconnectedOutLayersNames())
current_readings = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > conf_threshold:
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
# Salvar as informações da detecção
detection_info = {
'id': int(class_id),
'descricao': classes[class_id],
'x': int(x),
'y': int(y),
'largura': int(w),
'altura': int(h),
'confianca': float(confidence)
}
current_readings.append(detection_info)
if mostrar_linhas:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(frame, f'{classes[class_id]} {confidence:.2f}', (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
global json_data
timestamp = time.time()
json_data = {'timestamp': timestamp, 'x_max': width, 'y_max': height, 'objetos': current_readings}
readings.append(json_data)
if not os.path.exists(output_folder):
os.makedirs(output_folder)
if len(readings) > max_readings:
readings.pop(0)
with open(output_folder + arquivoSaida, 'w') as file:
json.dump(readings, file, indent=4)
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
# Função para lidar com a conexão de cada cliente
def handle_client_connection(client_socket):
try:
while True:
# Enviar o dicionário serializado em JSON
client_socket.send(json.dumps(json_data).encode('utf-8'))
# Aguardar um pouco antes de enviar os próximos dados
time.sleep(0.2)
except socket.error:
print(f"Cliente desconectado.")
finally:
# Fechar a conexão do socket ao sair do loop
client_socket.close()
# Configuração inicial do servidor de socket
def start_server(address='localhost', port=socket_porta):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((address, port))
server.listen()
print(f"Servidor iniciado. Aguardando conexões em {address}:{port}...")
try:
while True:
client_sock, address = server.accept()
print(f"Aceitando conexão de {address[0]}:{address[1]}")
client_handler = threading.Thread(
target=handle_client_connection,
args=(client_sock,)
)
client_handler.start()
finally:
server.close()
# Esta função é para iniciar o servidor de socket em uma thread separada
def run_socket_server():
start_server()
# Iniciar o servidor Flask em uma thread separada
def run_flask_server():
app.run(host='0.0.0.0', port=porta, threaded=True, debug=False)
@app.route('/' + url, methods=['GET'])
def video_feed():
conf_threshold = float(request.args.get('conf_threshold'))
nms_threshold = float(request.args.get('nms_threshold'))
camera_index = int(request.args.get('camera_index'))
return Response(detect_objects(conf_threshold, nms_threshold, camera_index), mimetype='multipart/x-mixed-replace; boundary=frame')
# Iniciar o servidor
if __name__ == '__main__':
# Inicia o servidor de socket em uma thread separada
socket_server_thread = threading.Thread(target=run_socket_server)
socket_server_thread.start()
# Inicia o servidor Flask na thread principal
run_flask_server()

View File

@ -0,0 +1 @@
{"Modo":0,"DispMov":null,"DispDir":null,"DispAtu":null,"frmOperacao":null,"frmOperacaoNome":"frmAcompanhamento","Iniciado":false,"TimestampInicio":0,"TimestampFim":0,"Controle":{"RPM_Max":45,"RPM_Min":15,"Angulo_Max":25.0,"Angulo_Min":-25.0,"Angulo":0.0,"RPM":0,"Direcao":0,"VelocidadeMP":50.0,"BicosAtuados":[],"TiposControle":[{"Tipo":100,"DelayEnvioComando":10,"UltimoComando":"2024-02-05T10:42:14.9647344-03:00","Comandos":[]},{"Tipo":101,"DelayEnvioComando":10,"UltimoComando":"2024-02-05T10:42:14.9647344-03:00","Comandos":[]}]},"ControleAnterior":{"RPM_Max":45,"RPM_Min":15,"Angulo_Max":30.0,"Angulo_Min":-30.0,"Angulo":0.0,"RPM":0,"Direcao":0,"VelocidadeMP":50.0,"BicosAtuados":[],"TiposControle":null},"ModulosMandatorios":[{"Dispositivo":100,"Mandatorio":false,"Utilizar":true,"Conectado":false},{"Dispositivo":101,"Mandatorio":false,"Utilizar":true,"Conectado":false},{"Dispositivo":102,"Mandatorio":false,"Utilizar":true,"Conectado":false}],"ErvasNoRadar":0,"VelocidadeMedia":0.0,"HerbicidaConsumido":0.0,"HerbicidaPorErva":0.0,"BateriaConsumida":0.0,"ErvasIdentificadas":0,"AtuacoesPorBico":[],"DistanciaPercorrida":0.0,"ProgressoPercurso":0.0}

View File

@ -0,0 +1 @@
{"Modo":1,"DispMov":null,"DispDir":null,"DispAtu":null,"frmOperacao":null,"frmOperacaoNome":"frmOperacaoSeguidorLinha","Iniciado":false,"TimestampInicio":0,"TimestampFim":0,"Controle":{"RPM_Max":45,"RPM_Min":23,"Angulo_Max":30.0,"Angulo_Min":-30.0,"Angulo":0.0,"RPM":0,"Direcao":0,"VelocidadeMP":60.0,"BicosAtuados":[],"TiposControle":[{"Tipo":100,"DelayEnvioComando":500,"UltimoComando":"2024-02-05T10:38:38.7605537-03:00","Comandos":[]},{"Tipo":101,"DelayEnvioComando":1000,"UltimoComando":"2024-02-05T10:38:38.7605537-03:00","Comandos":[]},{"Tipo":103,"DelayEnvioComando":100,"UltimoComando":"2024-02-05T10:38:38.7605537-03:00","Comandos":[]}]},"ControleAnterior":{"RPM_Max":45,"RPM_Min":15,"Angulo_Max":30.0,"Angulo_Min":-30.0,"Angulo":0.0,"RPM":0,"Direcao":0,"VelocidadeMP":50.0,"BicosAtuados":[],"TiposControle":null},"ModulosMandatorios":[{"Dispositivo":100,"Mandatorio":true,"Utilizar":true,"Conectado":false},{"Dispositivo":101,"Mandatorio":true,"Utilizar":true,"Conectado":false},{"Dispositivo":103,"Mandatorio":true,"Utilizar":true,"Conectado":false},{"Dispositivo":102,"Mandatorio":false,"Utilizar":true,"Conectado":false}],"ErvasNoRadar":0,"VelocidadeMedia":0.0,"HerbicidaConsumido":0.0,"HerbicidaPorErva":0.0,"BateriaConsumida":0.0,"ErvasIdentificadas":0,"AtuacoesPorBico":[],"DistanciaPercorrida":0.0,"ProgressoPercurso":0.0}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
{"Conectado":false,"Sensores":[{"LogGrafico":[],"ID":"TMVET","Prioridade":0,"Descricao":"Temperatura Motor Esquerdo Trás","Componente":411,"Aferir":true,"DelayAmostragem":200,"Inicializado":false,"Testando":false,"Funcoes":[12],"Parametros":[["V offset","-1.038"]],"UnidadeMedida":null,"Leituras":[17.12],"ValorMinimo":0.0,"ValorMaximo":125.27,"LimiteMaximo":150.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"TMVEF","Prioridade":0,"Descricao":"Temperatura Motor Esquerdo Frente","Componente":411,"Aferir":true,"DelayAmostragem":200,"Inicializado":false,"Testando":false,"Funcoes":[12],"Parametros":[["V offset","-1.038"]],"UnidadeMedida":null,"Leituras":[17.31],"ValorMinimo":0.0,"ValorMaximo":74.45,"LimiteMaximo":150.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"TMVDT","Prioridade":0,"Descricao":"Temperatura Motor Direito Trás","Componente":411,"Aferir":true,"DelayAmostragem":200,"Inicializado":false,"Testando":false,"Funcoes":[12],"Parametros":[["V offset","-1.038"]],"UnidadeMedida":null,"Leituras":[16.4],"ValorMinimo":0.0,"ValorMaximo":211.32,"LimiteMaximo":150.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"TMVDF","Prioridade":0,"Descricao":"Temperatura Motor Direito Frente","Componente":411,"Aferir":true,"DelayAmostragem":200,"Inicializado":false,"Testando":false,"Funcoes":[12],"Parametros":[["V offset","-1.038"]],"UnidadeMedida":null,"Leituras":[18.43],"ValorMinimo":0.0,"ValorMaximo":228.34,"LimiteMaximo":150.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"VBAT","Prioridade":20,"Descricao":"Tensão da bateria","Componente":112,"Aferir":true,"DelayAmostragem":500,"Inicializado":false,"Testando":false,"Funcoes":[28],"Parametros":[["V offset","-0.900"],["R1","120000"],["R2","010000"]],"UnidadeMedida":null,"Leituras":[42.0,4095.0,3.23],"ValorMinimo":0.0,"ValorMaximo":42.0,"LimiteMaximo":0.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"ABAT","Prioridade":10,"Descricao":"Corrente da bateria","Componente":322,"Aferir":true,"DelayAmostragem":500,"Inicializado":false,"Testando":false,"Funcoes":[29],"Parametros":[["V offset","00.413"],["Sensibilidade","000.35"]],"UnidadeMedida":null,"Leituras":[-1.18,0.0,0.0],"ValorMinimo":-1.18,"ValorMaximo":1.51,"LimiteMaximo":0.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"TBAT","Prioridade":5,"Descricao":"Temperatura da bateria","Componente":411,"Aferir":true,"DelayAmostragem":500,"Inicializado":false,"Testando":false,"Funcoes":[12],"Parametros":[["V offset","0.0000"]],"UnidadeMedida":null,"Leituras":[33.83],"ValorMinimo":-273.15,"ValorMaximo":5209.31,"LimiteMaximo":70.0,"LimiteMinimo":0.0}]}
{"Conectado":true,"Sensores":[{"LogGrafico":[],"ID":"TMVET","Prioridade":0,"Descricao":"Temperatura Motor Esquerdo Trás","Componente":411,"Aferir":true,"DelayAmostragem":200,"Inicializado":true,"Testando":false,"Funcoes":[12],"Parametros":[["V offset","-1.038"]],"UnidadeMedida":null,"Leituras":[0.0],"ValorMinimo":0.0,"ValorMaximo":125.27,"LimiteMaximo":150.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"TMVEF","Prioridade":0,"Descricao":"Temperatura Motor Esquerdo Frente","Componente":411,"Aferir":true,"DelayAmostragem":200,"Inicializado":true,"Testando":false,"Funcoes":[12],"Parametros":[["V offset","-1.038"]],"UnidadeMedida":null,"Leituras":[0.0],"ValorMinimo":0.0,"ValorMaximo":74.45,"LimiteMaximo":150.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"TMVDT","Prioridade":0,"Descricao":"Temperatura Motor Direito Trás","Componente":411,"Aferir":true,"DelayAmostragem":200,"Inicializado":true,"Testando":false,"Funcoes":[12],"Parametros":[["V offset","-1.038"]],"UnidadeMedida":null,"Leituras":[0.0],"ValorMinimo":0.0,"ValorMaximo":211.32,"LimiteMaximo":150.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"TMVDF","Prioridade":0,"Descricao":"Temperatura Motor Direito Frente","Componente":411,"Aferir":true,"DelayAmostragem":200,"Inicializado":true,"Testando":false,"Funcoes":[12],"Parametros":[["V offset","-1.038"]],"UnidadeMedida":null,"Leituras":[0.0],"ValorMinimo":0.0,"ValorMaximo":228.34,"LimiteMaximo":150.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"VBAT","Prioridade":20,"Descricao":"Tensão da bateria","Componente":112,"Aferir":true,"DelayAmostragem":500,"Inicializado":true,"Testando":false,"Funcoes":[28],"Parametros":[["V offset","-0.900"],["R1","120000"],["R2","010000"]],"UnidadeMedida":null,"Leituras":[-0.9,0.0,-0.07],"ValorMinimo":-0.9,"ValorMaximo":42.0,"LimiteMaximo":0.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"ABAT","Prioridade":10,"Descricao":"Corrente da bateria","Componente":322,"Aferir":true,"DelayAmostragem":500,"Inicializado":true,"Testando":false,"Funcoes":[29],"Parametros":[["V offset","00.413"],["Sensibilidade","000.35"]],"UnidadeMedida":null,"Leituras":[-1.18,0.0,0.0],"ValorMinimo":-1.18,"ValorMaximo":1.51,"LimiteMaximo":0.0,"LimiteMinimo":0.0},{"LogGrafico":[],"ID":"TBAT","Prioridade":5,"Descricao":"Temperatura da bateria","Componente":411,"Aferir":true,"DelayAmostragem":500,"Inicializado":true,"Testando":false,"Funcoes":[12],"Parametros":[["V offset","0.0000"]],"UnidadeMedida":null,"Leituras":[530.63],"ValorMinimo":-273.15,"ValorMaximo":5209.31,"LimiteMaximo":70.0,"LimiteMinimo":0.0}]}

View File

@ -1 +1 @@
f31026ee1ab1838ea7bbc4dcad4f992e0bcdfd14ca19bab7d19fd1cb0d18f15d
b391a3d1cae54e680b474aa3c6ea1b2a01691f787521f6aa219c9ff4da0ab7ea

View File

@ -363,3 +363,32 @@ C:\ZendionInc\agrobot_base\AgroBase\AgroBase\obj\Debug\AgroBase.Forms.frmGPS.res
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\obj\Debug\AgroBase.Forms.frmPinout.resources
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\obj\Debug\AgroBase.Forms.Sensoriamento.frmSenConfig.resources
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\obj\Debug\AgroBase.Forms.Atuador.frmAtuConfig.resources
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\obj\Debug\AgroBase.Forms.Operacoes.frmParametrizacaoOperacao.resources
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\obj\Debug\AgroBase.Forms.IHM.frmIHM.resources
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Scripts\weed-detector.py
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\obj\Debug\AgroBase.Forms.Movimentacao.frmMovCamera.resources
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\AForge.dll
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\AForge.Video.DirectShow.dll
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\AForge.Video.dll
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\AForge.xml
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\AForge.Video.xml
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\AForge.Video.DirectShow.xml
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Scripts\street-detector.py
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\backbone\hrnetv2.py
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\backbone\mobilenetv2.py
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\backbone\resnet.py
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\backbone\xception.py
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\backbone\__init__.py
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\modeling.py
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\utils.py
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\_deeplab.py
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\__init__.py
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\backbone\__pycache__\hrnetv2.cpython-311.pyc
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\backbone\__pycache__\mobilenetv2.cpython-311.pyc
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\backbone\__pycache__\resnet.cpython-311.pyc
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\backbone\__pycache__\xception.cpython-311.pyc
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\backbone\__pycache__\__init__.cpython-311.pyc
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\__pycache__\modeling.cpython-311.pyc
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\__pycache__\utils.cpython-311.pyc
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\__pycache__\_deeplab.cpython-311.pyc
C:\ZendionInc\agrobot_base\AgroBase\AgroBase\bin\Debug\Python\Models\deeplabv3plus\__pycache__\__init__.cpython-311.pyc

View File

@ -1,5 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="AForge" version="2.2.5" targetFramework="net472" />
<package id="AForge.Video" version="2.2.5" targetFramework="net472" />
<package id="AForge.Video.DirectShow" version="2.2.5" targetFramework="net472" />
<package id="cef.redist.x64" version="119.4.3" targetFramework="net472" />
<package id="cef.redist.x86" version="119.4.3" targetFramework="net472" />
<package id="CefSharp.Common" version="119.4.30" targetFramework="net472" />

Binary file not shown.

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More