commit 3c72adc00f7c25d8381bf9fd92dc24ff1afdf893 Author: xhm\HP <1173131411@qq.com> Date: Fri May 31 10:14:57 2024 +0800 firt commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..345c9f4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,190 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +build/ +bld/ +[Bb]in/ +[Oo]bj/ + +# Visual Studio 2015 cache/options directory +.vs/ +/.vs/ + +# Roslyn cache directories +*.ide/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +#NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding addin-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +## TODO: Comment the next line if you want to checkin your +## web deploy settings but do note that will include unencrypted +## passwords +*.pubxml + +# NuGet Packages +packages/* +*.nupkg +## TODO: If the tool you use requires repositories.config +## uncomment the next line +#!packages/repositories.config + +# Enable "build/" folder in the NuGet Packages folder since +# NuGet packages use it for MSBuild targets. +# This line needs to be after the ignore of the build folder +# (and the packages folder if the line above has been uncommented) +!packages/build/ + +# Windows Azure Build Output +csx/ +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +sql/ +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ diff --git a/HisenceYoloDetection.sln b/HisenceYoloDetection.sln new file mode 100644 index 0000000..66a5e2f --- /dev/null +++ b/HisenceYoloDetection.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.8.34316.72 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HisenceYoloDetection", "HisenceYoloDetection\HisenceYoloDetection.csproj", "{0DE28139-2917-4B58-8240-4B4E11114730}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|X64 = Debug|X64 + Release|Any CPU = Release|Any CPU + Release|X64 = Release|X64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0DE28139-2917-4B58-8240-4B4E11114730}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0DE28139-2917-4B58-8240-4B4E11114730}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0DE28139-2917-4B58-8240-4B4E11114730}.Debug|X64.ActiveCfg = Debug|X64 + {0DE28139-2917-4B58-8240-4B4E11114730}.Debug|X64.Build.0 = Debug|X64 + {0DE28139-2917-4B58-8240-4B4E11114730}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0DE28139-2917-4B58-8240-4B4E11114730}.Release|Any CPU.Build.0 = Release|Any CPU + {0DE28139-2917-4B58-8240-4B4E11114730}.Release|X64.ActiveCfg = Release|X64 + {0DE28139-2917-4B58-8240-4B4E11114730}.Release|X64.Build.0 = Release|X64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {323307B2-E1FD-47AE-B3FF-4BAAD1305BF6} + EndGlobalSection +EndGlobal diff --git a/HisenceYoloDetection/HisenceYoloDetection.csproj b/HisenceYoloDetection/HisenceYoloDetection.csproj new file mode 100644 index 0000000..5f6c63c --- /dev/null +++ b/HisenceYoloDetection/HisenceYoloDetection.csproj @@ -0,0 +1,51 @@ + + + + WinExe + net7.0-windows + enable + true + enable + AnyCPU;X64 + True + + + + + + + + + + + + + + + + + + + ..\libs\DVPCameraCS_Net6.0\x64\DVPCameraCS64.dll + + + ..\libs\HslCommunication.dll + + + bin\X64\Debug\net7.0-windows\PaddleOCRSharp.dll + + + + + + True + True + Resources.resx + + + + + + + + \ No newline at end of file diff --git a/HisenceYoloDetection/InsertSqlFrm.Designer.cs b/HisenceYoloDetection/InsertSqlFrm.Designer.cs new file mode 100644 index 0000000..d991067 --- /dev/null +++ b/HisenceYoloDetection/InsertSqlFrm.Designer.cs @@ -0,0 +1,394 @@ +namespace HisenceYoloDetection +{ + partial class InsertSqlFrm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + panel1 = new Panel(); + button1 = new Button(); + OpenTwoDirBtn = new Button(); + OpenDirBtn = new Button(); + Cam2MatCbx = new TextBox(); + label3 = new Label(); + Cam1MatCbx = new TextBox(); + label4 = new Label(); + QueryoneBtn = new Button(); + DetectBArMatbox = new TextBox(); + label11 = new Label(); + InsertBtn = new Button(); + moveTwoZbox = new TextBox(); + label5 = new Label(); + moveTwoYbox = new TextBox(); + label9 = new Label(); + moveTwoXbox = new TextBox(); + label10 = new Label(); + moveZbox = new TextBox(); + label6 = new Label(); + moveYbox = new TextBox(); + label7 = new Label(); + moveXbox = new TextBox(); + label8 = new Label(); + OcrBarBox = new TextBox(); + label2 = new Label(); + TypeBox = new TextBox(); + queryALLBtn = new Button(); + label1 = new Label(); + InsertDataDgv = new DataGridView(); + panel1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)InsertDataDgv).BeginInit(); + SuspendLayout(); + // + // panel1 + // + panel1.Controls.Add(button1); + panel1.Controls.Add(OpenTwoDirBtn); + panel1.Controls.Add(OpenDirBtn); + panel1.Controls.Add(Cam2MatCbx); + panel1.Controls.Add(label3); + panel1.Controls.Add(Cam1MatCbx); + panel1.Controls.Add(label4); + panel1.Controls.Add(QueryoneBtn); + panel1.Controls.Add(DetectBArMatbox); + panel1.Controls.Add(label11); + panel1.Controls.Add(InsertBtn); + panel1.Controls.Add(moveTwoZbox); + panel1.Controls.Add(label5); + panel1.Controls.Add(moveTwoYbox); + panel1.Controls.Add(label9); + panel1.Controls.Add(moveTwoXbox); + panel1.Controls.Add(label10); + panel1.Controls.Add(moveZbox); + panel1.Controls.Add(label6); + panel1.Controls.Add(moveYbox); + panel1.Controls.Add(label7); + panel1.Controls.Add(moveXbox); + panel1.Controls.Add(label8); + panel1.Controls.Add(OcrBarBox); + panel1.Controls.Add(label2); + panel1.Controls.Add(TypeBox); + panel1.Controls.Add(queryALLBtn); + panel1.Controls.Add(label1); + panel1.Controls.Add(InsertDataDgv); + panel1.Location = new Point(0, -3); + panel1.Name = "panel1"; + panel1.Size = new Size(934, 533); + panel1.TabIndex = 0; + // + // button1 + // + button1.Location = new Point(696, 152); + button1.Name = "button1"; + button1.Size = new Size(75, 23); + button1.TabIndex = 32; + button1.Text = "打开文件"; + button1.UseVisualStyleBackColor = true; + button1.Click += button1_Click; + // + // OpenTwoDirBtn + // + OpenTwoDirBtn.Location = new Point(696, 241); + OpenTwoDirBtn.Name = "OpenTwoDirBtn"; + OpenTwoDirBtn.Size = new Size(75, 23); + OpenTwoDirBtn.TabIndex = 31; + OpenTwoDirBtn.Text = "打开文件"; + OpenTwoDirBtn.UseVisualStyleBackColor = true; + OpenTwoDirBtn.Click += OpenTwoDirBtn_Click; + // + // OpenDirBtn + // + OpenDirBtn.Location = new Point(696, 193); + OpenDirBtn.Name = "OpenDirBtn"; + OpenDirBtn.Size = new Size(75, 23); + OpenDirBtn.TabIndex = 30; + OpenDirBtn.Text = "打开文件"; + OpenDirBtn.UseVisualStyleBackColor = true; + OpenDirBtn.Click += OpenDirBtn_Click; + // + // Cam2MatCbx + // + Cam2MatCbx.Location = new Point(478, 244); + Cam2MatCbx.Name = "Cam2MatCbx"; + Cam2MatCbx.Size = new Size(188, 23); + Cam2MatCbx.TabIndex = 29; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(371, 244); + label3.Name = "label3"; + label3.Size = new Size(80, 17); + label3.TabIndex = 28; + label3.Text = "面板第二张图"; + // + // Cam1MatCbx + // + Cam1MatCbx.Location = new Point(478, 193); + Cam1MatCbx.Name = "Cam1MatCbx"; + Cam1MatCbx.Size = new Size(188, 23); + Cam1MatCbx.TabIndex = 27; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(372, 199); + label4.Name = "label4"; + label4.Size = new Size(80, 17); + label4.TabIndex = 26; + label4.Text = "面板第一张图"; + // + // QueryoneBtn + // + QueryoneBtn.Location = new Point(827, 108); + QueryoneBtn.Name = "QueryoneBtn"; + QueryoneBtn.Size = new Size(93, 23); + QueryoneBtn.TabIndex = 25; + QueryoneBtn.Text = "条件查询"; + QueryoneBtn.UseVisualStyleBackColor = true; + QueryoneBtn.Click += QueryoneBtn_Click; + // + // DetectBArMatbox + // + DetectBArMatbox.Location = new Point(477, 152); + DetectBArMatbox.Name = "DetectBArMatbox"; + DetectBArMatbox.Size = new Size(188, 23); + DetectBArMatbox.TabIndex = 24; + // + // label11 + // + label11.AutoSize = true; + label11.Location = new Point(402, 158); + label11.Name = "label11"; + label11.Size = new Size(56, 17); + label11.TabIndex = 23; + label11.Text = "条码录入"; + // + // InsertBtn + // + InsertBtn.Location = new Point(827, 18); + InsertBtn.Name = "InsertBtn"; + InsertBtn.Size = new Size(93, 23); + InsertBtn.TabIndex = 22; + InsertBtn.Text = "插入"; + InsertBtn.UseVisualStyleBackColor = true; + InsertBtn.Click += InsertBtn_Click; + // + // moveTwoZbox + // + moveTwoZbox.Location = new Point(477, 101); + moveTwoZbox.Name = "moveTwoZbox"; + moveTwoZbox.Size = new Size(188, 23); + moveTwoZbox.TabIndex = 21; + // + // label5 + // + label5.AutoSize = true; + label5.Location = new Point(371, 107); + label5.Name = "label5"; + label5.Size = new Size(87, 17); + label5.TabIndex = 20; + label5.Text = "第二次拍照Z轴"; + // + // moveTwoYbox + // + moveTwoYbox.Location = new Point(477, 54); + moveTwoYbox.Name = "moveTwoYbox"; + moveTwoYbox.Size = new Size(188, 23); + moveTwoYbox.TabIndex = 19; + // + // label9 + // + label9.AutoSize = true; + label9.Location = new Point(371, 60); + label9.Name = "label9"; + label9.Size = new Size(87, 17); + label9.TabIndex = 18; + label9.Text = "第二次拍照Y轴"; + // + // moveTwoXbox + // + moveTwoXbox.Location = new Point(477, 12); + moveTwoXbox.Name = "moveTwoXbox"; + moveTwoXbox.Size = new Size(188, 23); + moveTwoXbox.TabIndex = 17; + // + // label10 + // + label10.AutoSize = true; + label10.Location = new Point(371, 18); + label10.Name = "label10"; + label10.Size = new Size(88, 17); + label10.TabIndex = 16; + label10.Text = "第二次拍照X轴"; + // + // moveZbox + // + moveZbox.Location = new Point(111, 193); + moveZbox.Name = "moveZbox"; + moveZbox.Size = new Size(188, 23); + moveZbox.TabIndex = 15; + // + // label6 + // + label6.AutoSize = true; + label6.Location = new Point(17, 199); + label6.Name = "label6"; + label6.Size = new Size(87, 17); + label6.TabIndex = 14; + label6.Text = "第一次拍照Z轴"; + // + // moveYbox + // + moveYbox.Location = new Point(111, 146); + moveYbox.Name = "moveYbox"; + moveYbox.Size = new Size(188, 23); + moveYbox.TabIndex = 13; + // + // label7 + // + label7.AutoSize = true; + label7.Location = new Point(17, 152); + label7.Name = "label7"; + label7.Size = new Size(87, 17); + label7.TabIndex = 12; + label7.Text = "第一次拍照Y轴"; + // + // moveXbox + // + moveXbox.Location = new Point(111, 104); + moveXbox.Name = "moveXbox"; + moveXbox.Size = new Size(188, 23); + moveXbox.TabIndex = 11; + // + // label8 + // + label8.AutoSize = true; + label8.Location = new Point(17, 110); + label8.Name = "label8"; + label8.Size = new Size(88, 17); + label8.TabIndex = 10; + label8.Text = "第一次拍照X轴"; + // + // OcrBarBox + // + OcrBarBox.Location = new Point(111, 54); + OcrBarBox.Name = "OcrBarBox"; + OcrBarBox.Size = new Size(188, 23); + OcrBarBox.TabIndex = 5; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(14, 60); + label2.Name = "label2"; + label2.Size = new Size(32, 17); + label2.TabIndex = 4; + label2.Text = "条码"; + // + // TypeBox + // + TypeBox.Location = new Point(111, 12); + TypeBox.Name = "TypeBox"; + TypeBox.Size = new Size(188, 23); + TypeBox.TabIndex = 3; + TypeBox.TextChanged += TypeBox_TextChanged; + // + // queryALLBtn + // + queryALLBtn.Location = new Point(827, 59); + queryALLBtn.Name = "queryALLBtn"; + queryALLBtn.Size = new Size(93, 23); + queryALLBtn.TabIndex = 2; + queryALLBtn.Text = "查询全部"; + queryALLBtn.UseVisualStyleBackColor = true; + queryALLBtn.Click += queryALLBtn_Click; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(14, 18); + label1.Name = "label1"; + label1.Size = new Size(32, 17); + label1.TabIndex = 1; + label1.Text = "类型"; + // + // InsertDataDgv + // + InsertDataDgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + InsertDataDgv.Location = new Point(12, 281); + InsertDataDgv.Name = "InsertDataDgv"; + InsertDataDgv.RowTemplate.Height = 25; + InsertDataDgv.Size = new Size(919, 235); + InsertDataDgv.TabIndex = 0; + // + // InsertSqlFrm + // + AutoScaleDimensions = new SizeF(7F, 17F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(946, 525); + Controls.Add(panel1); + Name = "InsertSqlFrm"; + Text = "InsertSqlFrm"; + panel1.ResumeLayout(false); + panel1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)InsertDataDgv).EndInit(); + ResumeLayout(false); + } + + #endregion + + private Panel panel1; + private Button queryALLBtn; + private Label label1; + private DataGridView InsertDataDgv; + private TextBox moveZbox; + private Label label6; + private TextBox moveYbox; + private Label label7; + private TextBox moveXbox; + private Label label8; + private TextBox OcrBarBox; + private Label label2; + private TextBox TypeBox; + private TextBox DetectBArMatbox; + private Label label11; + private Button InsertBtn; + private TextBox moveTwoZbox; + private Label label5; + private TextBox moveTwoYbox; + private Label label9; + private TextBox moveTwoXbox; + private Label label10; + private Button QueryoneBtn; + private TextBox Cam2MatCbx; + private Label label3; + private TextBox Cam1MatCbx; + private Label label4; + private Button button1; + private Button OpenTwoDirBtn; + private Button OpenDirBtn; + } +} \ No newline at end of file diff --git a/HisenceYoloDetection/InsertSqlFrm.cs b/HisenceYoloDetection/InsertSqlFrm.cs new file mode 100644 index 0000000..3096eee --- /dev/null +++ b/HisenceYoloDetection/InsertSqlFrm.cs @@ -0,0 +1,198 @@ +using OpenCvSharp; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.Xml.Linq; +using XKRS.Device.SimboVision.SimboHelper; + +namespace HisenceYoloDetection +{ + public partial class InsertSqlFrm : Form + { + public InsertSqlFrm() + { + InitializeComponent(); + } + public SimboObjectDetection simboObjectDetection; + public PaddleOcrModel paddleOcrModel ; + public PaddleOcrModelCountry paddleOcrModelCountry ; + private void TypeBox_TextChanged(object sender, EventArgs e) + { + + } + string BarPath = ""; + string Cam1OnePath = ""; + string Cam1TwoPath = ""; + + + private void InsertBtn_Click(object sender, EventArgs e) + { + try + { + string type = TypeBox.Text; + string OcrBar = OcrBarBox.Text; + string moveX = moveXbox.Text; + string moveY = moveYbox.Text; + string moveZ = moveZbox.Text; + string Detect = DetectBArMatbox.Text; + string movetwoX = moveTwoXbox.Text; + string movetwoY = moveTwoYbox.Text; + string movetwoZ = moveTwoZbox.Text; + + if (!Regex.IsMatch(moveX, @"^[0-9]+$")) + { + MessageBox.Show("第一次拍照移动的X只能是数字"); + return; + } + if (!Regex.IsMatch(moveY, @"^[0-9]+$")) + { + MessageBox.Show("第一次拍照移动的Y只能是数字"); + return; + } + if (!Regex.IsMatch(moveZ, @"^[0-9]+$")) + { + MessageBox.Show("第一次拍照移动的Z只能是数字"); + return; + } + if (!Regex.IsMatch(movetwoX, @"^[0-9]+$")) + { + MessageBox.Show("第二次拍照移动的X只能是数字"); + return; + } + if (!Regex.IsMatch(movetwoY, @"^[0-9]+$")) + { + MessageBox.Show("第二次拍照移动的Y只能是数字"); + return; + } + if (!Regex.IsMatch(movetwoZ, @"^[0-9]+$")) + { + MessageBox.Show("第二次拍照移动的Z只能是数字"); + return; + } + + if (OcrBar != "" && Detect != "") + { + + + string sql = "insert into XK_Hisence VALUES('" + type + "','" + OcrBar + "',null,null," + moveX + "," + moveY + "," + moveZ + ",'" + Detect + "',null," + movetwoX + "," + movetwoY + "," + movetwoZ + ")"; + SQLiteHelper.ExecuteSql(sql); + } + else + { + MessageBox.Show("插入的数据不能为NULL"); + } + + } + catch (Exception es) + { + } + + } + + private void queryALLBtn_Click(object sender, EventArgs e) + { + try + { + DataSet dataSet = SQLiteHelper.Query("select * from XK_Hisence"); + InsertDataDgv.DataSource = dataSet.Tables[0]; + + + } + catch (Exception es) + { + } + } + + private void QueryoneBtn_Click(object sender, EventArgs e) + { + try + { + string type = TypeBox.Text; + string OcrBar = OcrBarBox.Text; + string moveX = moveXbox.Text; + string moveY = moveYbox.Text; + string moveZ = moveZbox.Text; + string Detect = DetectBArMatbox.Text; + string movetwoX = moveTwoXbox.Text; + string movetwoY = moveTwoYbox.Text; + string movetwoZ = moveTwoZbox.Text; + + + string sql = "select * from XK_Hisence where type='" + type + "' or OcrBar='" + OcrBar + "'"; + DataSet dataSet = SQLiteHelper.Query(sql); + InsertDataDgv.DataSource = dataSet.Tables[0]; + + } + catch (Exception es) + { + } + } + /// + /// 打开条码的图片 + /// + /// + /// + private void button1_Click(object sender, EventArgs e) + { + OpenFileDialog openFileDialog = new OpenFileDialog(); + openFileDialog.Title = "请打开图片"; + + + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + string fName = openFileDialog.FileName; + //File fileOpen = new File(fName); + //isFileHaveName = true; + //richTextBox1.Text = fileOpen.ReadFile(); + //richTextBox1.AppendText(""); + DetectBArMatbox.Text = fName; + BarPath = fName; + } + + } + + private void OpenDirBtn_Click(object sender, EventArgs e) + { + OpenFileDialog openFileDialog = new OpenFileDialog(); + openFileDialog.Title = "请打开图片"; + + + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + string fName = openFileDialog.FileName; + //File fileOpen = new File(fName); + //isFileHaveName = true; + //richTextBox1.Text = fileOpen.ReadFile(); + //richTextBox1.AppendText(""); + Cam1MatCbx.Text = fName; + Cam1OnePath = fName; + } + } + + private void OpenTwoDirBtn_Click(object sender, EventArgs e) + { + OpenFileDialog openFileDialog = new OpenFileDialog(); + openFileDialog.Title = "请打开图片"; + + + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + string fName = openFileDialog.FileName; + //File fileOpen = new File(fName); + //isFileHaveName = true; + //richTextBox1.Text = fileOpen.ReadFile(); + //richTextBox1.AppendText(""); + Cam2MatCbx.Text = fName; + Cam1TwoPath = fName; + } + + } + } +} diff --git a/HisenceYoloDetection/InsertSqlFrm.resx b/HisenceYoloDetection/InsertSqlFrm.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/HisenceYoloDetection/InsertSqlFrm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/HisenceYoloDetection/MGSCameraDriver.cs b/HisenceYoloDetection/MGSCameraDriver.cs new file mode 100644 index 0000000..7985f5f --- /dev/null +++ b/HisenceYoloDetection/MGSCameraDriver.cs @@ -0,0 +1,713 @@ + +using DVPCameraType; +using OpenCvSharp; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net.NetworkInformation; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Xml.Linq; +using static DVPCameraType.DVPCamera; +using static System.Windows.Forms.VisualStyles.VisualStyleElement; + + + +public class MGSCameraDriver +{ + private uint m_handle = 0; + private dvpCameraInfo stDevInfo = new dvpCameraInfo(); + private dvpStatus nRet = dvpStatus.DVP_STATUS_OK; + private DVPCamera.dvpEventCallback pCallBackFunc; + + /// + /// 相机拍照计数 + /// + public volatile int SnapshotCount = 0; + + + /// + /// 当前相机的配置 + /// + + + public bool IfSuccess=false; + private float _lastExposure = 0; + private float _lastGain = 0; + + + #region CameraBase + + public bool IsValidHandle(uint handle) + { + bool bValidHandle = false; + dvpStatus status = DVPCamera.dvpIsValid(handle, ref bValidHandle); + if (status == dvpStatus.DVP_STATUS_OK) + { + return bValidHandle; + } + return false; + } + /// + /// 获取曝光 + /// + /// + public double dvpGetExposure() + { + dvpStatus status; + double exposure = 0; + float gain = 0; + if (IsValidHandle(m_handle)) + { + // 读取曝光 + status = DVPCamera.dvpGetExposure(m_handle, ref exposure); + if (status == dvpStatus.DVP_STATUS_OK) + { + //opConfig.Exposure = (float)exposure; + return exposure; + } + } + return exposure; + } + /// + /// 获取增益 + /// + /// + public float dvpGetAnalogGain() + { + dvpStatus status; + double exposure = 0; + float gain = 0; + if (IsValidHandle(m_handle)) + { + // 读取曝光 + status = DVPCamera.dvpGetAnalogGain(m_handle, ref gain); + if (status == dvpStatus.DVP_STATUS_OK) + { + //opConfig.Exposure = (float)exposure; + return gain; + } + } + return gain; + } + //public override IOperationConfig GetOperationConfigFromDevice() + //{ + // MGSCameraOperationConfig opConfig = new MGSCameraOperationConfig(); + + // dvpStatus status; + // double exposure = 0; + // float gain = 0; + // if (IsValidHandle(m_handle)) + // { + // // 读取曝光 + // status = DVPCamera.dvpGetExposure(m_handle, ref exposure); + // if (status == dvpStatus.DVP_STATUS_OK) + // { + // opConfig.Exposure = (float)exposure; + // } + // // 读取增益 + // status = DVPCamera.dvpGetAnalogGain(m_handle, ref gain); + // if (status == dvpStatus.DVP_STATUS_OK) + // { + // opConfig.Gain = gain; + // } + // } + // return opConfig; + //} + + + + + //public override void UploadOperationConfig(IOperationConfig config) + //{ + // if (CurrentState != DeviceState.DSOpen) + // { + // return; + // } + + // if (!IsValidHandle(m_handle)) + // { + // return; + // } + + // CameraOprerationConfigBase opConfig = config as CameraOprerationConfigBase; + + // if (opConfig.Exposure != 0 && opConfig.Exposure != _lastExposure) + // { + // SetExposure(opConfig.Exposure); + // _lastExposure = opConfig.Exposure; + // } + + // if (opConfig.Gain != 0 && opConfig.Gain != _lastGain) + // { + // SetGain(opConfig.Gain); + // _lastGain = opConfig.Gain; + // } + //} + + + public void Init() + { + DVPCamera.dvpGetCameraInfo(m_handle, ref stDevInfo); + + _bufferImgSet = new Mat(); + + pCallBackFunc = new DVPCamera.dvpEventCallback(cbExceptiondelegate); + } + + + protected void Pause() + { + + } + + protected void Resume() + { + + } + public class CamConfig + { + public string CameraName = "Cam1"; + public double DefaultExposure; + public float Gain; + public bool IsDirectHardwareTrigger = true; + } + public CamConfig IIConfig; + public void Start(string DeviceName) + { + try + { + + DVPCamera.dvpGetCameraInfo(m_handle, ref stDevInfo); + + _bufferImgSet = new Mat(); + + pCallBackFunc = new DVPCamera.dvpEventCallback(cbExceptiondelegate); + + + nRet = DVPCamera.dvpOpenByUserId(DeviceName, + dvpOpenMode.OPEN_NORMAL, + ref m_handle); + + // ch:打开设备 | en:Open device + if (dvpStatus.DVP_STATUS_OK != nRet) + { + throw new Exception($"Create device failed:{nRet:x8}"); + } + + nRet = DVPCamera.dvpSetTargetFormat(m_handle, (dvpStreamFormat)dvpImageFormat.FORMAT_BGR24); + if (dvpStatus.DVP_STATUS_OK != nRet) + { + throw new Exception($"Set image format failed:{nRet:x8}"); + } + + + // ch:注册异常回调函数 | en:Register Exception Callback + nRet = DVPCamera.dvpRegisterEventCallback(m_handle, pCallBackFunc, dvpEvent.EVENT_DISCONNECTED, IntPtr.Zero); + if (nRet != dvpStatus.DVP_STATUS_OK) + { + throw new Exception($"Register expection callback failed:{nRet}"); + } + GC.KeepAlive(pCallBackFunc); + dvpStatus status; + double exposure = 0; + float gain = 0; + if (IsValidHandle(m_handle)) + { + // 读取曝光 + //status = DVPCamera.dvpGetExposure(m_handle, ref exposure); + //if (status == dvpStatus.DVP_STATUS_OK) + //{ + // IIConfig.DefaultExposure = (float)exposure; + //} + //// 读取增益 + //status = DVPCamera.dvpGetAnalogGain(m_handle, ref gain); + //if (status == dvpStatus.DVP_STATUS_OK) + //{ + // IIConfig.Gain = gain; + //} + } + + // ch:设置采集连续模式 | en:Set Continues Aquisition Mode + if (false)//IIConfig.IsContinueMode) + { + // ch:设置触发模式为off || en:set trigger mode as off + nRet = DVPCamera.dvpSetTriggerState(m_handle, false); + if (dvpStatus.DVP_STATUS_OK != nRet) + { + throw new Exception("Set TriggerMode failed!"); + } + } + else + { + // ch:设置触发模式为on || en:set trigger mode as on + nRet = DVPCamera.dvpSetTriggerState(m_handle, true); + if (dvpStatus.DVP_STATUS_OK != nRet) + { + throw new Exception("Set TriggerMode failed!"); + } + + // 硬触发 + if (false)//IIConfig.IsHardwareTrigger) + { + // ch:触发源选择:1 - Line1; | en:Trigger source select:1 - Line1; + nRet = DVPCamera.dvpSetTriggerSource(m_handle, dvpTriggerSource.TRIGGER_SOURCE_LINE1); + if (dvpStatus.DVP_STATUS_OK != nRet) + { + throw new Exception("Set Line1 Trigger failed!"); + } + + // ch:注册回调函数 | en:Register image callback + ImageCallback = new DVPCamera.dvpStreamCallback(ImageCallbackFunc); + nRet = DVPCamera.dvpRegisterStreamCallback(m_handle, ImageCallback, dvpStreamEvent.STREAM_EVENT_PROCESSED, IntPtr.Zero); + if (dvpStatus.DVP_STATUS_OK != nRet) + { + throw new Exception("Register image callback failed!"); + } + } + else // 软触发 + { + nRet = DVPCamera.dvpSetTriggerSource(m_handle, dvpTriggerSource.TRIGGER_SOURCE_SOFTWARE); + if (dvpStatus.DVP_STATUS_OK != nRet) + { + throw new Exception("Set Software Trigger failed!"); + } + //_proc = _dvpStreamCallback; + //nRet = DVPCamera.dvpRegisterStreamCallback(m_handle, _proc, dvpStreamEvent.STREAM_EVENT_PROCESSED, IntPtr.Zero); + //if (dvpStatus.DVP_STATUS_OK != nRet) + //{ + // throw new Exception("Register image callback failed!"); + //} + // ch:注册回调函数 | en:Register image callback + ImageCallback = new DVPCamera.dvpStreamCallback(ImageCallbackFunc); + nRet = DVPCamera.dvpRegisterStreamCallback(m_handle, ImageCallback, dvpStreamEvent.STREAM_EVENT_PROCESSED, IntPtr.Zero); + if (dvpStatus.DVP_STATUS_OK != nRet) + { + throw new Exception("Register image callback failed!"); + } + using (Process curProcess = Process.GetCurrentProcess()) + using (ProcessModule curModule = curProcess.MainModule) + { + status = DVPCamera.dvpRegisterStreamCallback(m_handle, _proc, dvpStreamEvent.STREAM_EVENT_PROCESSED, IntPtr.Zero); + //Debug.Assert(status == dvpStatus.DVP_STATUS_OK); + } + } + m_dfDisplayCount = 0; + + if (IsValidHandle(m_handle)) + { + dvpStreamState state = new dvpStreamState(); + + + // Implement a button to start and stop according to the current video's status. + status = DVPCamera.dvpGetStreamState(m_handle, ref state); + + if (state == dvpStreamState.STATE_STARTED) + { + nRet = DVPCamera.dvpStop(m_handle); + } + else + { + + + nRet = DVPCamera.dvpStart(m_handle); + } + Debug.Assert(status == dvpStatus.DVP_STATUS_OK); + nRet = DVPCamera.dvpSetTriggerSource(m_handle, dvpTriggerSource.TRIGGER_SOURCE_SOFTWARE); + if (dvpStatus.DVP_STATUS_OK != nRet) + { + throw new Exception("Set Software Trigger failed!"); + } + else + { + IfSuccess = true; + } + } + // ch:开启抓图 || en: start grab image + //nRet = DVPCamera.dvpStart(m_handle); + //if (dvpStatus.DVP_STATUS_OK != nRet) + //{ + // throw new Exception($"Start grabbing failed:{nRet:x8}"); + //} + // 曝光 + //if (IIConfig.DefaultExposure != 0) + //{ + // SetExposure(IIConfig.DefaultExposure); + //} + //// 增益 + //if (IIConfig.Gain >= 0) + //{ + // SetGain(IIConfig.Gain); + //} + + // 设置 触发延迟 + //if (IIConfig.TriggerDelay > 0) + //{ + // nRet = DVPCamera.dvpSetTriggerDelay(m_handle, IIConfig.TriggerDelay); + // if (nRet != dvpStatus.DVP_STATUS_OK) + // { + // throw new Exception("Set TriggerDelay failed!"); + // } + //} + + // 信号消抖 + //if (IIConfig.LineDebouncerTime > 0) + //{ + // nRet = DVPCamera.dvpSetTriggerJitterFilter(m_handle, IIConfig.LineDebouncerTime); + // if (nRet != dvpStatus.DVP_STATUS_OK) + // { + // throw new Exception($"LineDebouncerTime set failed:{nRet}"); + // } + //} + + + + } + + } + catch (Exception e) + { + + } + + } + + + + public void Stop() + { + + + // ch:停止抓图 | en:Stop grab image + // check camear + dvpStreamState StreamState = new dvpStreamState(); + nRet = DVPCamera.dvpGetStreamState(m_handle, ref StreamState); + Debug.Assert(nRet == dvpStatus.DVP_STATUS_OK); + if (StreamState == dvpStreamState.STATE_STARTED) + { + // stop camera + nRet = DVPCamera.dvpStop(m_handle); + Debug.Assert(nRet == dvpStatus.DVP_STATUS_OK); + if (nRet != dvpStatus.DVP_STATUS_OK) + { + throw new Exception($"Stop grabbing failed{nRet:x8}"); + } + } + + nRet = DVPCamera.dvpUnregisterEventCallback(m_handle, pCallBackFunc, dvpEvent.EVENT_DISCONNECTED, IntPtr.Zero); + if (nRet != dvpStatus.DVP_STATUS_OK) + { + throw new Exception($"Unregister expection callback failed:{nRet}"); + } + + // ch:关闭设备 | en:Close device + nRet = DVPCamera.dvpClose(m_handle); + if (nRet != dvpStatus.DVP_STATUS_OK) + { + throw new Exception($"Close device failed{nRet:x8}"); + } + + m_handle = 0; + } + + + #endregion + + + #region MGSCamera + + + private DVPCamera.dvpStreamCallback ImageCallback; + private DVPCamera.dvpStreamCallback _proc; + private dvpFrameBuffer _frame = new dvpFrameBuffer(); + private readonly ManualResetEvent _snapHandle = new ManualResetEvent(false); + private bool _snapFlag = false; + + private Mat _bufferImgSet = null; + private readonly ManualResetEvent _bufferHandle = new ManualResetEvent(false); + public Action OnHImageOutput { get; set; } + + public static bool m_bTriggerMode = false; + + // Display param + public static Stopwatch m_Stopwatch = new Stopwatch(); + public static Double m_dfDisplayCount = 0; + + public static dvpCameraInfo[] m_info = new dvpCameraInfo[16]; + public static int m_CamCount = 0; + /// + /// 设置曝光值 + /// + /// 曝光值 + /// + private void SetExposure(double exposure) + { + // 使用自动曝光 + if (false) + { + // 设置自动曝光 + //nRet = DVPCamera.dvpSetAeOperation(m_handle, dvpAeOperation.AE_OP_CONTINUOUS); + + if (nRet != dvpStatus.DVP_STATUS_OK) + { + throw new Exception($"Exposure set failed:{nRet}"); + } + // 设置曝光值 + nRet = DVPCamera.dvpSetAeTarget(m_handle, (int)exposure); + if (nRet != dvpStatus.DVP_STATUS_OK) + { + throw new Exception($"Exposure set failed:{nRet}"); + } + } + else // 不适用自动曝光 + { + // 关闭自动曝光 + nRet = DVPCamera.dvpSetAeOperation(m_handle, dvpAeOperation.AE_OP_OFF); + if (nRet != dvpStatus.DVP_STATUS_OK) + { + throw new Exception($"Exposure set failed:{nRet}"); + } + // 设置曝光值 + nRet = DVPCamera.dvpSetExposure(m_handle, exposure); + if (nRet != dvpStatus.DVP_STATUS_OK) + { + throw new Exception($"Exposure set failed:{nRet}"); + } + } + } + + + /// + /// 设置增益 + /// + /// + /// + private void SetGain(float gain) + { + // 设置增益 + nRet = DVPCamera.dvpSetAnalogGain(m_handle, gain); + + if (nRet != dvpStatus.DVP_STATUS_OK) + { + throw new Exception($"Gain set failed:{nRet}"); + } + } + + + public int ImageCallbackFunc(uint handle, dvpStreamEvent _event, IntPtr pContext, ref dvpFrame refFrame, IntPtr pBuffer) + { + try + { + if (true)//硬触发 + { + + + int nWidth = refFrame.iWidth; + int nHeight = refFrame.iHeight; + MatType matType = MatType.CV_8UC1; + + + if (refFrame.format == dvpImageFormat.FORMAT_RGB24) + { + IntPtr pTemp = pBuffer; + + } + else if (refFrame.format == dvpImageFormat.FORMAT_BGR24) + { + IntPtr pTemp = pBuffer; + matType = MatType.CV_8UC3; + + } + Mat _mat = new Mat( nHeight,nWidth, matType, pBuffer); + //加入内部队列 + + //if (IIConfig.IsDirectHardwareTrigger) + //{ + // 传感器直接触发 收到图片后 传出 + OnHImageOutput?.Invoke(DateTime.Now, _mat, SnapshotCount); + // } + //else + //{ + // _bufferImgSet = _mat; + // // _bufferImgSetQueue.Enqueue(outImgSet); + // _bufferHandle.Set(); + //} + //处理完图片 会清理内部队列的图像 + //DisplayAndSaveOriginImage(imgSet.Id); + } + else if (_snapFlag) + { + _snapFlag = false; + _frame = new dvpFrameBuffer + { + frame = refFrame, + pData = pBuffer, + }; + _snapHandle.Set(); + } + + + } + catch (Exception ex) + { + + return dvpStatus.DVP_STATUS_GRAB_FAILED.ToInt(); + } + return dvpStatus.DVP_STATUS_OK.ToInt(); + } + + + + + + + private object _bufferLock = new object(); + + + + + public void Snapshot() + { + try + { + Stopwatch sw = new Stopwatch(); + sw.Start(); + // ImageSet set = new ImageSet(); + + + dvpFrameBuffer frameInfo = new dvpFrameBuffer(); + + nRet = dvpStatus.DVP_STATUS_OK; + if (true)//如果不是持续模式 + { + // ch: 触发命令 || en: Trigger command + nRet = DVPCamera.dvpTriggerFire(m_handle); + if (dvpStatus.DVP_STATUS_OK != nRet) + { + throw new Exception($"相机拍照触发失败:{nRet}"); + } + + } + else + { + _snapHandle.Reset(); + _snapFlag = true; + _snapHandle.WaitOne(); + //lock (_imgCallBackLock) + { + frameInfo.frame = _frame.frame; + frameInfo.pData = _frame.pData; + } + } + + // ch:获取一帧图像 | en:Get one image + if (dvpStatus.DVP_STATUS_OK == nRet) + { + Interlocked.Increment(ref SnapshotCount); + if (frameInfo.pData != IntPtr.Zero) + { + if (nRet == dvpStatus.DVP_STATUS_OK) + { + dvpFrame pFrameInfo = frameInfo.frame; + MatType matType = MatType.CV_8UC1; + if (pFrameInfo.format == dvpImageFormat.FORMAT_RGB24) + { + + } + else if (pFrameInfo.format == dvpImageFormat.FORMAT_BGR24) + { + + matType = MatType.CV_8UC3; + + } + + //HImage hImage = new HImage(); + //hImage.GenImage1("byte", pFrameInfo.iWidth, pFrameInfo.iHeight, frameInfo.pData); + Mat _mat = new Mat(pFrameInfo.iHeight, pFrameInfo.iWidth, matType, frameInfo.pData); + OnHImageOutput?.Invoke(DateTime.Now, _mat,SnapshotCount); + //_mat.ImWrite("D://123.jpg"); + } + } + } + else + { + throw new Exception($"Grap Image Failed:{nRet:x8}"); + } + + sw.Stop(); + // LogAsync(DateTime.Now, LogLevel.Information, $"取像耗时:{sw.ElapsedMilliseconds} ms"); + + } + catch (Exception ex) { + } + + + + } + + + + + + + /// + /// 回调函数 + /// + /// + /// + /// + /// + /// + /// + public int cbExceptiondelegate(uint handle, dvpEvent _event, IntPtr pContext, int param, ref dvpVariant refVariant) + { + + if (_event == dvpEvent.EVENT_DISCONNECTED) + { + + int reTryTimes = 3; + do + { + try + { + Task.Delay(1000).Wait(); + Stop(); + + //Start(); + reTryTimes = -1; + } + catch (Exception ex) + { + reTryTimes--; + + if (reTryTimes > 0) + { + // LogAsync(DateTime.Now, LogLevel.Information, $"{Name}重新连接异常,{ex.GetExceptionMessage()}"); + } + else + { + throw ex; + } + } + } while (reTryTimes > 0); + + } + + + return dvpStatus.DVP_STATUS_OK.ToInt(); + } + + + + + #endregion + + + + +} + diff --git a/HisenceYoloDetection/MainForm.Designer.cs b/HisenceYoloDetection/MainForm.Designer.cs new file mode 100644 index 0000000..6b4c77b --- /dev/null +++ b/HisenceYoloDetection/MainForm.Designer.cs @@ -0,0 +1,1899 @@ +namespace HisenceYoloDetection +{ + partial class MainForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + tabPage2 = new TabPage(); + panel1 = new Panel(); + groupBox5 = new GroupBox(); + DistanceShow = new TextBox(); + label21 = new Label(); + txtSetValue = new TextBox(); + groupBox4 = new GroupBox(); + SetAutoSpeed = new Button(); + SetHandleSpeed = new Button(); + SetlnEditmiZOP = new TextBox(); + SetlnEditmiYOP = new TextBox(); + SetlnEditmiXOP = new TextBox(); + SetlnEditmiZH = new TextBox(); + SetlnEditmiYH = new TextBox(); + SetlnEditmiXH = new TextBox(); + lnEditmiZOP = new TextBox(); + lnEditmiYOP = new TextBox(); + lnEditmiXOP = new TextBox(); + label17 = new Label(); + lnEditmiZS = new TextBox(); + lnEditmiYS = new TextBox(); + lnEditmiXS = new TextBox(); + label16 = new Label(); + lnEditmiZHS = new TextBox(); + lnEditmiYHS = new TextBox(); + lnEditmiXHS = new TextBox(); + label15 = new Label(); + ZPostion = new Label(); + YPostion = new Label(); + XPostion = new Label(); + XCurrentPostion = new Label(); + label14 = new Label(); + label13 = new Label(); + label12 = new Label(); + label11 = new Label(); + ModeleShow = new GroupBox(); + ZBackwardrbx = new RadioButton(); + YBackwardrbx = new RadioButton(); + XBackwardrbx = new RadioButton(); + ZForwardrbx = new RadioButton(); + YForwardrbx = new RadioButton(); + XForwardrbx = new RadioButton(); + ZZerorbx = new RadioButton(); + YZerorbx = new RadioButton(); + XZerorbx = new RadioButton(); + PLCPostion = new Button(); + PLCDiskZero = new Button(); + PLCPowerON = new Button(); + writePLCValue = new TextBox(); + label9 = new Label(); + label10 = new Label(); + wirteAdressBtn = new Button(); + PLCValue = new TextBox(); + WriteAdress = new TextBox(); + label6 = new Label(); + label3 = new Label(); + ConnectPLC = new Button(); + readAdress = new Button(); + showPLC = new TextBox(); + readPLc = new TextBox(); + tabPage1 = new TabPage(); + groupBox3 = new GroupBox(); + SnapshotCam2 = new Button(); + button3 = new Button(); + bnSetParam2 = new Button(); + label5 = new Label(); + Cam2OpenBtn = new Button(); + bnGetParam2 = new Button(); + tbGain2 = new TextBox(); + tbExposure2 = new TextBox(); + label7 = new Label(); + label8 = new Label(); + pictureBox2 = new PictureBox(); + groupBox1 = new GroupBox(); + SnapshotCam1 = new Button(); + button2 = new Button(); + bnSetParam = new Button(); + label1 = new Label(); + Cam1OpenBtn = new Button(); + bnGetParam = new Button(); + tbGain = new TextBox(); + tbExposure = new TextBox(); + label2 = new Label(); + label4 = new Label(); + pictureBox1 = new PictureBox(); + tabControl1 = new TabControl(); + tabPage5 = new TabPage(); + panel4 = new Panel(); + panel5 = new Panel(); + panel8 = new Panel(); + RefeshData = new Button(); + 实时显示 = new Label(); + OKOrNGShow = new PictureBox(); + OKDNum = new TextBox(); + label20 = new Label(); + NGDNum = new TextBox(); + label19 = new Label(); + AllDSum = new TextBox(); + label18 = new Label(); + InsertSqlBtn = new Button(); + StartDecBtn = new Button(); + ScanDevList = new Button(); + DevNameCombo = new ComboBox(); + InitMachine = new Button(); + panel6 = new Panel(); + groupBox2 = new GroupBox(); + ResultMat2Show = new PictureBox(); + originMat2Show = new PictureBox(); + ResultMatShow2 = new PictureBox(); + originMatShow2 = new PictureBox(); + originMatShow = new PictureBox(); + ResultMatShow = new PictureBox(); + tabPage3 = new TabPage(); + panel2 = new Panel(); + openModelBtn = new Button(); + modelChangeCbx = new TextBox(); + label34 = new Label(); + button4 = new Button(); + OpenTwoDirBtn = new Button(); + OpenDirBtn = new Button(); + Cam2MatCbx = new TextBox(); + label22 = new Label(); + Cam1MatCbx = new TextBox(); + label23 = new Label(); + QueryoneBtn = new Button(); + DetectBArMatbox = new TextBox(); + label24 = new Label(); + InsertBtn = new Button(); + moveTwoZbox = new TextBox(); + label25 = new Label(); + moveTwoYbox = new TextBox(); + label26 = new Label(); + moveTwoXbox = new TextBox(); + label27 = new Label(); + moveZbox = new TextBox(); + label28 = new Label(); + moveYbox = new TextBox(); + label29 = new Label(); + moveXbox = new TextBox(); + label30 = new Label(); + OcrBarBox = new TextBox(); + label31 = new Label(); + TypeBox = new TextBox(); + queryALLBtn = new Button(); + label32 = new Label(); + InsertDataDgv = new DataGridView(); + timer1 = new System.Windows.Forms.Timer(components); + timer2 = new System.Windows.Forms.Timer(components); + timer3 = new System.Windows.Forms.Timer(components); + timer4 = new System.Windows.Forms.Timer(components); + timer5 = new System.Windows.Forms.Timer(components); + timer6 = new System.Windows.Forms.Timer(components); + richTextBox1 = new RichTextBox(); + contextMenuStrip1 = new ContextMenuStrip(components); + dataGridView1 = new DataGridView(); + backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); + tabPage2.SuspendLayout(); + panel1.SuspendLayout(); + groupBox5.SuspendLayout(); + groupBox4.SuspendLayout(); + ModeleShow.SuspendLayout(); + tabPage1.SuspendLayout(); + groupBox3.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox2).BeginInit(); + groupBox1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit(); + tabControl1.SuspendLayout(); + tabPage5.SuspendLayout(); + panel4.SuspendLayout(); + panel5.SuspendLayout(); + panel8.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)OKOrNGShow).BeginInit(); + panel6.SuspendLayout(); + groupBox2.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)ResultMat2Show).BeginInit(); + ((System.ComponentModel.ISupportInitialize)originMat2Show).BeginInit(); + ((System.ComponentModel.ISupportInitialize)ResultMatShow2).BeginInit(); + ((System.ComponentModel.ISupportInitialize)originMatShow2).BeginInit(); + ((System.ComponentModel.ISupportInitialize)originMatShow).BeginInit(); + ((System.ComponentModel.ISupportInitialize)ResultMatShow).BeginInit(); + tabPage3.SuspendLayout(); + panel2.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)InsertDataDgv).BeginInit(); + ((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit(); + SuspendLayout(); + // + // tabPage2 + // + tabPage2.Controls.Add(panel1); + tabPage2.Location = new Point(4, 26); + tabPage2.Name = "tabPage2"; + tabPage2.Padding = new Padding(3); + tabPage2.Size = new Size(1276, 499); + tabPage2.TabIndex = 1; + tabPage2.Text = "PLC"; + tabPage2.UseVisualStyleBackColor = true; + // + // panel1 + // + panel1.Controls.Add(groupBox5); + panel1.Controls.Add(txtSetValue); + panel1.Controls.Add(groupBox4); + panel1.Controls.Add(ModeleShow); + panel1.Controls.Add(writePLCValue); + panel1.Controls.Add(label9); + panel1.Controls.Add(label10); + panel1.Controls.Add(wirteAdressBtn); + panel1.Controls.Add(PLCValue); + panel1.Controls.Add(WriteAdress); + panel1.Controls.Add(label6); + panel1.Controls.Add(label3); + panel1.Controls.Add(ConnectPLC); + panel1.Controls.Add(readAdress); + panel1.Controls.Add(showPLC); + panel1.Controls.Add(readPLc); + panel1.Location = new Point(6, 6); + panel1.Name = "panel1"; + panel1.Size = new Size(1171, 489); + panel1.TabIndex = 4; + // + // groupBox5 + // + groupBox5.Controls.Add(DistanceShow); + groupBox5.Controls.Add(label21); + groupBox5.Location = new Point(806, 10); + groupBox5.Name = "groupBox5"; + groupBox5.Size = new Size(356, 100); + groupBox5.TabIndex = 15; + groupBox5.TabStop = false; + groupBox5.Text = "实时显示"; + // + // DistanceShow + // + DistanceShow.Location = new Point(86, 30); + DistanceShow.Name = "DistanceShow"; + DistanceShow.ReadOnly = true; + DistanceShow.Size = new Size(100, 23); + DistanceShow.TabIndex = 10; + // + // label21 + // + label21.AutoSize = true; + label21.Location = new Point(28, 33); + label21.Name = "label21"; + label21.Size = new Size(32, 17); + label21.TabIndex = 0; + label21.Text = "测距"; + // + // txtSetValue + // + txtSetValue.Location = new Point(670, 78); + txtSetValue.Name = "txtSetValue"; + txtSetValue.Size = new Size(100, 23); + txtSetValue.TabIndex = 14; + // + // groupBox4 + // + groupBox4.Controls.Add(SetAutoSpeed); + groupBox4.Controls.Add(SetHandleSpeed); + groupBox4.Controls.Add(SetlnEditmiZOP); + groupBox4.Controls.Add(SetlnEditmiYOP); + groupBox4.Controls.Add(SetlnEditmiXOP); + groupBox4.Controls.Add(SetlnEditmiZH); + groupBox4.Controls.Add(SetlnEditmiYH); + groupBox4.Controls.Add(SetlnEditmiXH); + groupBox4.Controls.Add(lnEditmiZOP); + groupBox4.Controls.Add(lnEditmiYOP); + groupBox4.Controls.Add(lnEditmiXOP); + groupBox4.Controls.Add(label17); + groupBox4.Controls.Add(lnEditmiZS); + groupBox4.Controls.Add(lnEditmiYS); + groupBox4.Controls.Add(lnEditmiXS); + groupBox4.Controls.Add(label16); + groupBox4.Controls.Add(lnEditmiZHS); + groupBox4.Controls.Add(lnEditmiYHS); + groupBox4.Controls.Add(lnEditmiXHS); + groupBox4.Controls.Add(label15); + groupBox4.Controls.Add(ZPostion); + groupBox4.Controls.Add(YPostion); + groupBox4.Controls.Add(XPostion); + groupBox4.Controls.Add(XCurrentPostion); + groupBox4.Controls.Add(label14); + groupBox4.Controls.Add(label13); + groupBox4.Controls.Add(label12); + groupBox4.Controls.Add(label11); + groupBox4.Location = new Point(611, 107); + groupBox4.Name = "groupBox4"; + groupBox4.Size = new Size(557, 373); + groupBox4.TabIndex = 13; + groupBox4.TabStop = false; + groupBox4.Text = "位置显示"; + // + // SetAutoSpeed + // + SetAutoSpeed.Location = new Point(8, 315); + SetAutoSpeed.Name = "SetAutoSpeed"; + SetAutoSpeed.Size = new Size(88, 23); + SetAutoSpeed.TabIndex = 29; + SetAutoSpeed.Text = "设置自动速度"; + SetAutoSpeed.UseVisualStyleBackColor = true; + SetAutoSpeed.Click += SetAutoSpeed_Click; + // + // SetHandleSpeed + // + SetHandleSpeed.Location = new Point(8, 258); + SetHandleSpeed.Name = "SetHandleSpeed"; + SetHandleSpeed.Size = new Size(88, 23); + SetHandleSpeed.TabIndex = 28; + SetHandleSpeed.Text = "设置手动速度"; + SetHandleSpeed.UseVisualStyleBackColor = true; + SetHandleSpeed.Click += SetHandleSpeed_Click; + // + // SetlnEditmiZOP + // + SetlnEditmiZOP.Location = new Point(409, 315); + SetlnEditmiZOP.Name = "SetlnEditmiZOP"; + SetlnEditmiZOP.Size = new Size(100, 23); + SetlnEditmiZOP.TabIndex = 27; + // + // SetlnEditmiYOP + // + SetlnEditmiYOP.Location = new Point(256, 315); + SetlnEditmiYOP.Name = "SetlnEditmiYOP"; + SetlnEditmiYOP.Size = new Size(100, 23); + SetlnEditmiYOP.TabIndex = 26; + // + // SetlnEditmiXOP + // + SetlnEditmiXOP.Location = new Point(107, 315); + SetlnEditmiXOP.Name = "SetlnEditmiXOP"; + SetlnEditmiXOP.Size = new Size(100, 23); + SetlnEditmiXOP.TabIndex = 25; + // + // SetlnEditmiZH + // + SetlnEditmiZH.Location = new Point(409, 258); + SetlnEditmiZH.Name = "SetlnEditmiZH"; + SetlnEditmiZH.Size = new Size(100, 23); + SetlnEditmiZH.TabIndex = 23; + // + // SetlnEditmiYH + // + SetlnEditmiYH.Location = new Point(256, 258); + SetlnEditmiYH.Name = "SetlnEditmiYH"; + SetlnEditmiYH.Size = new Size(100, 23); + SetlnEditmiYH.TabIndex = 22; + // + // SetlnEditmiXH + // + SetlnEditmiXH.Location = new Point(107, 258); + SetlnEditmiXH.Name = "SetlnEditmiXH"; + SetlnEditmiXH.Size = new Size(100, 23); + SetlnEditmiXH.TabIndex = 21; + // + // lnEditmiZOP + // + lnEditmiZOP.Location = new Point(409, 200); + lnEditmiZOP.Name = "lnEditmiZOP"; + lnEditmiZOP.Size = new Size(100, 23); + lnEditmiZOP.TabIndex = 19; + // + // lnEditmiYOP + // + lnEditmiYOP.Location = new Point(256, 200); + lnEditmiYOP.Name = "lnEditmiYOP"; + lnEditmiYOP.Size = new Size(100, 23); + lnEditmiYOP.TabIndex = 18; + // + // lnEditmiXOP + // + lnEditmiXOP.Location = new Point(107, 200); + lnEditmiXOP.Name = "lnEditmiXOP"; + lnEditmiXOP.Size = new Size(100, 23); + lnEditmiXOP.TabIndex = 17; + // + // label17 + // + label17.AutoSize = true; + label17.Location = new Point(32, 203); + label17.Name = "label17"; + label17.Size = new Size(56, 17); + label17.TabIndex = 16; + label17.Text = "定位位置"; + // + // lnEditmiZS + // + lnEditmiZS.Location = new Point(409, 144); + lnEditmiZS.Name = "lnEditmiZS"; + lnEditmiZS.ReadOnly = true; + lnEditmiZS.Size = new Size(100, 23); + lnEditmiZS.TabIndex = 15; + // + // lnEditmiYS + // + lnEditmiYS.Location = new Point(256, 144); + lnEditmiYS.Name = "lnEditmiYS"; + lnEditmiYS.ReadOnly = true; + lnEditmiYS.Size = new Size(100, 23); + lnEditmiYS.TabIndex = 14; + // + // lnEditmiXS + // + lnEditmiXS.Location = new Point(107, 144); + lnEditmiXS.Name = "lnEditmiXS"; + lnEditmiXS.ReadOnly = true; + lnEditmiXS.Size = new Size(100, 23); + lnEditmiXS.TabIndex = 13; + // + // label16 + // + label16.AutoSize = true; + label16.Location = new Point(8, 147); + label16.Name = "label16"; + label16.Size = new Size(80, 17); + label16.TabIndex = 12; + label16.Text = "当前定位速度"; + // + // lnEditmiZHS + // + lnEditmiZHS.Location = new Point(409, 87); + lnEditmiZHS.Name = "lnEditmiZHS"; + lnEditmiZHS.ReadOnly = true; + lnEditmiZHS.Size = new Size(100, 23); + lnEditmiZHS.TabIndex = 11; + // + // lnEditmiYHS + // + lnEditmiYHS.Location = new Point(256, 87); + lnEditmiYHS.Name = "lnEditmiYHS"; + lnEditmiYHS.ReadOnly = true; + lnEditmiYHS.Size = new Size(100, 23); + lnEditmiYHS.TabIndex = 10; + // + // lnEditmiXHS + // + lnEditmiXHS.Location = new Point(107, 87); + lnEditmiXHS.Name = "lnEditmiXHS"; + lnEditmiXHS.ReadOnly = true; + lnEditmiXHS.Size = new Size(100, 23); + lnEditmiXHS.TabIndex = 9; + // + // label15 + // + label15.AutoSize = true; + label15.Location = new Point(8, 90); + label15.Name = "label15"; + label15.Size = new Size(80, 17); + label15.TabIndex = 8; + label15.Text = "当前手动速度"; + // + // ZPostion + // + ZPostion.AutoSize = true; + ZPostion.Location = new Point(451, 45); + ZPostion.Name = "ZPostion"; + ZPostion.Size = new Size(15, 17); + ZPostion.TabIndex = 7; + ZPostion.Text = "0"; + // + // YPostion + // + YPostion.AutoSize = true; + YPostion.Location = new Point(300, 45); + YPostion.Name = "YPostion"; + YPostion.Size = new Size(15, 17); + YPostion.TabIndex = 6; + YPostion.Text = "0"; + // + // XPostion + // + XPostion.AutoSize = true; + XPostion.Location = new Point(144, 45); + XPostion.Name = "XPostion"; + XPostion.Size = new Size(15, 17); + XPostion.TabIndex = 5; + XPostion.Text = "0"; + // + // XCurrentPostion + // + XCurrentPostion.AutoSize = true; + XCurrentPostion.Location = new Point(132, 45); + XCurrentPostion.Name = "XCurrentPostion"; + XCurrentPostion.Size = new Size(0, 17); + XCurrentPostion.TabIndex = 4; + // + // label14 + // + label14.AutoSize = true; + label14.Location = new Point(451, 22); + label14.Name = "label14"; + label14.Size = new Size(15, 17); + label14.TabIndex = 3; + label14.Text = "Z"; + // + // label13 + // + label13.AutoSize = true; + label13.Location = new Point(300, 19); + label13.Name = "label13"; + label13.Size = new Size(15, 17); + label13.TabIndex = 2; + label13.Text = "Y"; + // + // label12 + // + label12.AutoSize = true; + label12.Location = new Point(143, 19); + label12.Name = "label12"; + label12.Size = new Size(16, 17); + label12.TabIndex = 1; + label12.Text = "X"; + // + // label11 + // + label11.AutoSize = true; + label11.Location = new Point(32, 45); + label11.Name = "label11"; + label11.Size = new Size(56, 17); + label11.TabIndex = 0; + label11.Text = "当前位置"; + // + // ModeleShow + // + ModeleShow.Controls.Add(ZBackwardrbx); + ModeleShow.Controls.Add(YBackwardrbx); + ModeleShow.Controls.Add(XBackwardrbx); + ModeleShow.Controls.Add(ZForwardrbx); + ModeleShow.Controls.Add(YForwardrbx); + ModeleShow.Controls.Add(XForwardrbx); + ModeleShow.Controls.Add(ZZerorbx); + ModeleShow.Controls.Add(YZerorbx); + ModeleShow.Controls.Add(XZerorbx); + ModeleShow.Controls.Add(PLCPostion); + ModeleShow.Controls.Add(PLCDiskZero); + ModeleShow.Controls.Add(PLCPowerON); + ModeleShow.Location = new Point(14, 107); + ModeleShow.Name = "ModeleShow"; + ModeleShow.Size = new Size(579, 373); + ModeleShow.TabIndex = 12; + ModeleShow.TabStop = false; + ModeleShow.Text = "模组显示"; + // + // ZBackwardrbx + // + ZBackwardrbx.Appearance = Appearance.Button; + ZBackwardrbx.Location = new Point(410, 180); + ZBackwardrbx.Name = "ZBackwardrbx"; + ZBackwardrbx.Size = new Size(125, 62); + ZBackwardrbx.TabIndex = 21; + ZBackwardrbx.Text = "Z反向"; + ZBackwardrbx.TextAlign = ContentAlignment.MiddleCenter; + ZBackwardrbx.UseVisualStyleBackColor = true; + ZBackwardrbx.Click += ZBackwardrbx_Click; + // + // YBackwardrbx + // + YBackwardrbx.Appearance = Appearance.Button; + YBackwardrbx.Location = new Point(266, 180); + YBackwardrbx.Name = "YBackwardrbx"; + YBackwardrbx.Size = new Size(125, 62); + YBackwardrbx.TabIndex = 20; + YBackwardrbx.Text = "Y反向"; + YBackwardrbx.TextAlign = ContentAlignment.MiddleCenter; + YBackwardrbx.UseVisualStyleBackColor = true; + YBackwardrbx.Click += YBackwardrbx_Click; + // + // XBackwardrbx + // + XBackwardrbx.Appearance = Appearance.Button; + XBackwardrbx.Location = new Point(126, 180); + XBackwardrbx.Name = "XBackwardrbx"; + XBackwardrbx.Size = new Size(125, 62); + XBackwardrbx.TabIndex = 19; + XBackwardrbx.Text = "X反向"; + XBackwardrbx.TextAlign = ContentAlignment.MiddleCenter; + XBackwardrbx.UseVisualStyleBackColor = true; + XBackwardrbx.Click += XBackwardrbx_Click; + // + // ZForwardrbx + // + ZForwardrbx.Appearance = Appearance.Button; + ZForwardrbx.Location = new Point(410, 105); + ZForwardrbx.Name = "ZForwardrbx"; + ZForwardrbx.Size = new Size(125, 62); + ZForwardrbx.TabIndex = 18; + ZForwardrbx.Text = "Z正向"; + ZForwardrbx.TextAlign = ContentAlignment.MiddleCenter; + ZForwardrbx.UseVisualStyleBackColor = true; + ZForwardrbx.Click += ZForwardrbx_Click; + // + // YForwardrbx + // + YForwardrbx.Appearance = Appearance.Button; + YForwardrbx.Location = new Point(266, 102); + YForwardrbx.Name = "YForwardrbx"; + YForwardrbx.Size = new Size(125, 62); + YForwardrbx.TabIndex = 17; + YForwardrbx.Text = "Y正向"; + YForwardrbx.TextAlign = ContentAlignment.MiddleCenter; + YForwardrbx.UseVisualStyleBackColor = true; + YForwardrbx.Click += YForwardrbx_Click; + // + // XForwardrbx + // + XForwardrbx.Appearance = Appearance.Button; + XForwardrbx.Location = new Point(126, 105); + XForwardrbx.Name = "XForwardrbx"; + XForwardrbx.Size = new Size(125, 62); + XForwardrbx.TabIndex = 16; + XForwardrbx.Text = "X正向"; + XForwardrbx.TextAlign = ContentAlignment.MiddleCenter; + XForwardrbx.UseVisualStyleBackColor = true; + XForwardrbx.Click += XForwardrbx_Click; + // + // ZZerorbx + // + ZZerorbx.Appearance = Appearance.Button; + ZZerorbx.Location = new Point(410, 22); + ZZerorbx.Name = "ZZerorbx"; + ZZerorbx.Size = new Size(125, 62); + ZZerorbx.TabIndex = 15; + ZZerorbx.Text = "Z归零"; + ZZerorbx.TextAlign = ContentAlignment.MiddleCenter; + ZZerorbx.UseVisualStyleBackColor = true; + ZZerorbx.Click += ZZerorbx_Click; + // + // YZerorbx + // + YZerorbx.Appearance = Appearance.Button; + YZerorbx.Location = new Point(266, 22); + YZerorbx.Name = "YZerorbx"; + YZerorbx.Size = new Size(125, 62); + YZerorbx.TabIndex = 14; + YZerorbx.Text = "Y归零"; + YZerorbx.TextAlign = ContentAlignment.MiddleCenter; + YZerorbx.UseVisualStyleBackColor = true; + YZerorbx.Click += YZerorbx_Click; + // + // XZerorbx + // + XZerorbx.Appearance = Appearance.Button; + XZerorbx.Location = new Point(126, 22); + XZerorbx.Name = "XZerorbx"; + XZerorbx.Size = new Size(125, 62); + XZerorbx.TabIndex = 13; + XZerorbx.Text = "X归零"; + XZerorbx.TextAlign = ContentAlignment.MiddleCenter; + XZerorbx.UseVisualStyleBackColor = true; + XZerorbx.Click += radioButton1_Click; + // + // PLCPostion + // + PLCPostion.Location = new Point(6, 258); + PLCPostion.Name = "PLCPostion"; + PLCPostion.Size = new Size(97, 101); + PLCPostion.TabIndex = 2; + PLCPostion.Text = "定位"; + PLCPostion.UseVisualStyleBackColor = true; + PLCPostion.Click += PLCPostion_Click; + // + // PLCDiskZero + // + PLCDiskZero.Location = new Point(6, 141); + PLCDiskZero.Name = "PLCDiskZero"; + PLCDiskZero.Size = new Size(97, 101); + PLCDiskZero.TabIndex = 1; + PLCDiskZero.Text = "归零"; + PLCDiskZero.UseVisualStyleBackColor = true; + PLCDiskZero.Click += PLCDiskZero_Click; + // + // PLCPowerON + // + PLCPowerON.Location = new Point(6, 22); + PLCPowerON.Name = "PLCPowerON"; + PLCPowerON.Size = new Size(97, 101); + PLCPowerON.TabIndex = 0; + PLCPowerON.Text = "使能ON"; + PLCPowerON.UseVisualStyleBackColor = true; + PLCPowerON.Click += PLCPowerON_Click; + // + // writePLCValue + // + writePLCValue.Location = new Point(670, 10); + writePLCValue.Name = "writePLCValue"; + writePLCValue.Size = new Size(100, 23); + writePLCValue.TabIndex = 11; + // + // label9 + // + label9.AutoSize = true; + label9.Location = new Point(400, 52); + label9.Name = "label9"; + label9.Size = new Size(20, 17); + label9.TabIndex = 10; + label9.Text = "值"; + // + // label10 + // + label10.AutoSize = true; + label10.Location = new Point(400, 16); + label10.Name = "label10"; + label10.Size = new Size(32, 17); + label10.TabIndex = 9; + label10.Text = "地址"; + // + // wirteAdressBtn + // + wirteAdressBtn.Location = new Point(574, 13); + wirteAdressBtn.Name = "wirteAdressBtn"; + wirteAdressBtn.Size = new Size(75, 23); + wirteAdressBtn.TabIndex = 7; + wirteAdressBtn.Text = "写地址INT"; + wirteAdressBtn.UseVisualStyleBackColor = true; + wirteAdressBtn.Click += wirteAdress_Click; + // + // PLCValue + // + PLCValue.Location = new Point(449, 46); + PLCValue.Name = "PLCValue"; + PLCValue.Size = new Size(100, 23); + PLCValue.TabIndex = 8; + // + // WriteAdress + // + WriteAdress.Location = new Point(449, 13); + WriteAdress.Name = "WriteAdress"; + WriteAdress.Size = new Size(100, 23); + WriteAdress.TabIndex = 6; + // + // label6 + // + label6.AutoSize = true; + label6.Location = new Point(126, 55); + label6.Name = "label6"; + label6.Size = new Size(20, 17); + label6.TabIndex = 5; + label6.Text = "值"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(126, 19); + label3.Name = "label3"; + label3.Size = new Size(32, 17); + label3.TabIndex = 4; + label3.Text = "地址"; + // + // ConnectPLC + // + ConnectPLC.Location = new Point(14, 16); + ConnectPLC.Name = "ConnectPLC"; + ConnectPLC.Size = new Size(99, 56); + ConnectPLC.TabIndex = 0; + ConnectPLC.Text = "链接PLC"; + ConnectPLC.UseVisualStyleBackColor = true; + ConnectPLC.Click += button4_Click; + // + // readAdress + // + readAdress.Location = new Point(300, 16); + readAdress.Name = "readAdress"; + readAdress.Size = new Size(75, 23); + readAdress.TabIndex = 2; + readAdress.Text = "读地址INT"; + readAdress.UseVisualStyleBackColor = true; + readAdress.Click += readAdress_Click; + // + // showPLC + // + showPLC.Location = new Point(175, 49); + showPLC.Name = "showPLC"; + showPLC.Size = new Size(100, 23); + showPLC.TabIndex = 3; + // + // readPLc + // + readPLc.Location = new Point(175, 16); + readPLc.Name = "readPLc"; + readPLc.Size = new Size(100, 23); + readPLc.TabIndex = 1; + // + // tabPage1 + // + tabPage1.Controls.Add(groupBox3); + tabPage1.Controls.Add(pictureBox2); + tabPage1.Controls.Add(groupBox1); + tabPage1.Controls.Add(pictureBox1); + tabPage1.Location = new Point(4, 26); + tabPage1.Name = "tabPage1"; + tabPage1.Padding = new Padding(3); + tabPage1.Size = new Size(1276, 499); + tabPage1.TabIndex = 0; + tabPage1.Text = "相机"; + tabPage1.UseVisualStyleBackColor = true; + // + // groupBox3 + // + groupBox3.Controls.Add(SnapshotCam2); + groupBox3.Controls.Add(button3); + groupBox3.Controls.Add(bnSetParam2); + groupBox3.Controls.Add(label5); + groupBox3.Controls.Add(Cam2OpenBtn); + groupBox3.Controls.Add(bnGetParam2); + groupBox3.Controls.Add(tbGain2); + groupBox3.Controls.Add(tbExposure2); + groupBox3.Controls.Add(label7); + groupBox3.Controls.Add(label8); + groupBox3.Location = new Point(566, 322); + groupBox3.Name = "groupBox3"; + groupBox3.Size = new Size(300, 174); + groupBox3.TabIndex = 19; + groupBox3.TabStop = false; + groupBox3.Text = "参数"; + // + // SnapshotCam2 + // + SnapshotCam2.Location = new Point(200, 143); + SnapshotCam2.Name = "SnapshotCam2"; + SnapshotCam2.Size = new Size(75, 23); + SnapshotCam2.TabIndex = 9; + SnapshotCam2.Text = "拍照"; + SnapshotCam2.UseVisualStyleBackColor = true; + SnapshotCam2.Click += SnapshotCam2_Click_1; + // + // button3 + // + button3.Location = new Point(200, 91); + button3.Name = "button3"; + button3.Size = new Size(75, 23); + button3.TabIndex = 8; + button3.Text = "关闭"; + button3.UseVisualStyleBackColor = true; + // + // bnSetParam2 + // + bnSetParam2.Enabled = false; + bnSetParam2.Location = new Point(97, 135); + bnSetParam2.Name = "bnSetParam2"; + bnSetParam2.Size = new Size(75, 23); + bnSetParam2.TabIndex = 7; + bnSetParam2.Text = "设置参数"; + bnSetParam2.UseVisualStyleBackColor = true; + // + // label5 + // + label5.AutoSize = true; + label5.Location = new Point(200, 19); + label5.Name = "label5"; + label5.Size = new Size(56, 17); + label5.TabIndex = 2; + label5.Text = "链接相机"; + // + // Cam2OpenBtn + // + Cam2OpenBtn.Location = new Point(200, 44); + Cam2OpenBtn.Name = "Cam2OpenBtn"; + Cam2OpenBtn.Size = new Size(75, 23); + Cam2OpenBtn.TabIndex = 1; + Cam2OpenBtn.Text = "开启"; + Cam2OpenBtn.UseVisualStyleBackColor = true; + Cam2OpenBtn.Click += Cam2OpenBtn_Click_1; + // + // bnGetParam2 + // + bnGetParam2.Location = new Point(12, 135); + bnGetParam2.Name = "bnGetParam2"; + bnGetParam2.Size = new Size(75, 23); + bnGetParam2.TabIndex = 6; + bnGetParam2.Text = "获取参数"; + bnGetParam2.UseVisualStyleBackColor = true; + bnGetParam2.Click += bnGetParam2_Click_1; + // + // tbGain2 + // + tbGain2.Location = new Point(72, 57); + tbGain2.Name = "tbGain2"; + tbGain2.Size = new Size(100, 23); + tbGain2.TabIndex = 4; + // + // tbExposure2 + // + tbExposure2.Location = new Point(72, 23); + tbExposure2.Name = "tbExposure2"; + tbExposure2.Size = new Size(100, 23); + tbExposure2.TabIndex = 3; + // + // label7 + // + label7.AutoSize = true; + label7.Location = new Point(12, 60); + label7.Name = "label7"; + label7.Size = new Size(32, 17); + label7.TabIndex = 1; + label7.Text = "增益"; + // + // label8 + // + label8.AutoSize = true; + label8.Location = new Point(12, 25); + label8.Name = "label8"; + label8.Size = new Size(32, 17); + label8.TabIndex = 0; + label8.Text = "曝光"; + // + // pictureBox2 + // + pictureBox2.Location = new Point(566, 6); + pictureBox2.Name = "pictureBox2"; + pictureBox2.Size = new Size(464, 293); + pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage; + pictureBox2.TabIndex = 18; + pictureBox2.TabStop = false; + // + // groupBox1 + // + groupBox1.Controls.Add(SnapshotCam1); + groupBox1.Controls.Add(button2); + groupBox1.Controls.Add(bnSetParam); + groupBox1.Controls.Add(label1); + groupBox1.Controls.Add(Cam1OpenBtn); + groupBox1.Controls.Add(bnGetParam); + groupBox1.Controls.Add(tbGain); + groupBox1.Controls.Add(tbExposure); + groupBox1.Controls.Add(label2); + groupBox1.Controls.Add(label4); + groupBox1.Location = new Point(8, 311); + groupBox1.Name = "groupBox1"; + groupBox1.Size = new Size(300, 174); + groupBox1.TabIndex = 17; + groupBox1.TabStop = false; + groupBox1.Text = "参数"; + // + // SnapshotCam1 + // + SnapshotCam1.Location = new Point(200, 143); + SnapshotCam1.Name = "SnapshotCam1"; + SnapshotCam1.Size = new Size(75, 23); + SnapshotCam1.TabIndex = 9; + SnapshotCam1.Text = "拍照"; + SnapshotCam1.UseVisualStyleBackColor = true; + SnapshotCam1.Click += SnapshotCam1_Click; + // + // button2 + // + button2.Location = new Point(200, 91); + button2.Name = "button2"; + button2.Size = new Size(75, 23); + button2.TabIndex = 8; + button2.Text = "关闭"; + button2.UseVisualStyleBackColor = true; + button2.Click += button2_Click; + // + // bnSetParam + // + bnSetParam.Enabled = false; + bnSetParam.Location = new Point(97, 135); + bnSetParam.Name = "bnSetParam"; + bnSetParam.Size = new Size(75, 23); + bnSetParam.TabIndex = 7; + bnSetParam.Text = "设置参数"; + bnSetParam.UseVisualStyleBackColor = true; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(200, 19); + label1.Name = "label1"; + label1.Size = new Size(56, 17); + label1.TabIndex = 2; + label1.Text = "链接相机"; + // + // Cam1OpenBtn + // + Cam1OpenBtn.Location = new Point(200, 44); + Cam1OpenBtn.Name = "Cam1OpenBtn"; + Cam1OpenBtn.Size = new Size(75, 23); + Cam1OpenBtn.TabIndex = 1; + Cam1OpenBtn.Text = "开启"; + Cam1OpenBtn.UseVisualStyleBackColor = true; + Cam1OpenBtn.Click += CamOpenBtn_Click; + // + // bnGetParam + // + bnGetParam.Location = new Point(12, 135); + bnGetParam.Name = "bnGetParam"; + bnGetParam.Size = new Size(75, 23); + bnGetParam.TabIndex = 6; + bnGetParam.Text = "获取参数"; + bnGetParam.UseVisualStyleBackColor = true; + bnGetParam.Click += bnGetParam_Click; + // + // tbGain + // + tbGain.Location = new Point(72, 57); + tbGain.Name = "tbGain"; + tbGain.Size = new Size(100, 23); + tbGain.TabIndex = 4; + // + // tbExposure + // + tbExposure.Location = new Point(72, 23); + tbExposure.Name = "tbExposure"; + tbExposure.Size = new Size(100, 23); + tbExposure.TabIndex = 3; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(12, 60); + label2.Name = "label2"; + label2.Size = new Size(32, 17); + label2.TabIndex = 1; + label2.Text = "增益"; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(12, 25); + label4.Name = "label4"; + label4.Size = new Size(32, 17); + label4.TabIndex = 0; + label4.Text = "曝光"; + // + // pictureBox1 + // + pictureBox1.Location = new Point(8, 6); + pictureBox1.Name = "pictureBox1"; + pictureBox1.Size = new Size(535, 293); + pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; + pictureBox1.TabIndex = 0; + pictureBox1.TabStop = false; + // + // tabControl1 + // + tabControl1.Controls.Add(tabPage1); + tabControl1.Controls.Add(tabPage2); + tabControl1.Controls.Add(tabPage5); + tabControl1.Controls.Add(tabPage3); + tabControl1.Dock = DockStyle.Top; + tabControl1.Location = new Point(0, 0); + tabControl1.Name = "tabControl1"; + tabControl1.SelectedIndex = 0; + tabControl1.Size = new Size(1284, 529); + tabControl1.TabIndex = 0; + // + // tabPage5 + // + tabPage5.Controls.Add(panel4); + tabPage5.Location = new Point(4, 26); + tabPage5.Name = "tabPage5"; + tabPage5.Size = new Size(1276, 499); + tabPage5.TabIndex = 3; + tabPage5.Text = "流程"; + tabPage5.UseVisualStyleBackColor = true; + // + // panel4 + // + panel4.Controls.Add(panel5); + panel4.Dock = DockStyle.Fill; + panel4.Location = new Point(0, 0); + panel4.Name = "panel4"; + panel4.Size = new Size(1276, 499); + panel4.TabIndex = 0; + // + // panel5 + // + panel5.Controls.Add(panel8); + panel5.Controls.Add(panel6); + panel5.Dock = DockStyle.Top; + panel5.Location = new Point(0, 0); + panel5.Name = "panel5"; + panel5.Size = new Size(1276, 577); + panel5.TabIndex = 0; + // + // panel8 + // + panel8.Controls.Add(RefeshData); + panel8.Controls.Add(实时显示); + panel8.Controls.Add(OKOrNGShow); + panel8.Controls.Add(OKDNum); + panel8.Controls.Add(label20); + panel8.Controls.Add(NGDNum); + panel8.Controls.Add(label19); + panel8.Controls.Add(AllDSum); + panel8.Controls.Add(label18); + panel8.Controls.Add(InsertSqlBtn); + panel8.Controls.Add(StartDecBtn); + panel8.Controls.Add(ScanDevList); + panel8.Controls.Add(DevNameCombo); + panel8.Controls.Add(InitMachine); + panel8.Location = new Point(853, 0); + panel8.Name = "panel8"; + panel8.Size = new Size(440, 496); + panel8.TabIndex = 2; + panel8.Paint += panel8_Paint; + // + // RefeshData + // + RefeshData.Location = new Point(38, 442); + RefeshData.Name = "RefeshData"; + RefeshData.Size = new Size(94, 43); + RefeshData.TabIndex = 13; + RefeshData.Text = "刷新"; + RefeshData.UseVisualStyleBackColor = true; + RefeshData.Click += RefeshData_Click; + // + // 实时显示 + // + 实时显示.AutoSize = true; + 实时显示.Location = new Point(326, 175); + 实时显示.Name = "实时显示"; + 实时显示.Size = new Size(56, 17); + 实时显示.TabIndex = 12; + 实时显示.Text = "实时显示"; + // + // OKOrNGShow + // + OKOrNGShow.Location = new Point(254, 204); + OKOrNGShow.Name = "OKOrNGShow"; + OKOrNGShow.Size = new Size(183, 179); + OKOrNGShow.SizeMode = PictureBoxSizeMode.CenterImage; + OKOrNGShow.TabIndex = 11; + OKOrNGShow.TabStop = false; + // + // OKDNum + // + OKDNum.Location = new Point(125, 296); + OKDNum.Name = "OKDNum"; + OKDNum.ReadOnly = true; + OKDNum.Size = new Size(100, 23); + OKDNum.TabIndex = 10; + // + // label20 + // + label20.AutoSize = true; + label20.Location = new Point(49, 300); + label20.Name = "label20"; + label20.Size = new Size(50, 17); + label20.TabIndex = 9; + label20.Text = "OK个数"; + // + // NGDNum + // + NGDNum.Location = new Point(125, 249); + NGDNum.Name = "NGDNum"; + NGDNum.ReadOnly = true; + NGDNum.Size = new Size(100, 23); + NGDNum.TabIndex = 8; + // + // label19 + // + label19.AutoSize = true; + label19.Location = new Point(49, 253); + label19.Name = "label19"; + label19.Size = new Size(51, 17); + label19.TabIndex = 7; + label19.Text = "NG个数"; + // + // AllDSum + // + AllDSum.Location = new Point(125, 204); + AllDSum.Name = "AllDSum"; + AllDSum.ReadOnly = true; + AllDSum.Size = new Size(100, 23); + AllDSum.TabIndex = 6; + // + // label18 + // + label18.AutoSize = true; + label18.Location = new Point(49, 208); + label18.Name = "label18"; + label18.Size = new Size(44, 17); + label18.TabIndex = 5; + label18.Text = "总个数"; + // + // InsertSqlBtn + // + InsertSqlBtn.Location = new Point(54, 56); + InsertSqlBtn.Name = "InsertSqlBtn"; + InsertSqlBtn.Size = new Size(92, 48); + InsertSqlBtn.TabIndex = 4; + InsertSqlBtn.Text = "型号录入"; + InsertSqlBtn.UseVisualStyleBackColor = true; + InsertSqlBtn.Visible = false; + InsertSqlBtn.Click += InsertSqlBtn_Click; + // + // StartDecBtn + // + StartDecBtn.Location = new Point(160, 127); + StartDecBtn.Name = "StartDecBtn"; + StartDecBtn.Size = new Size(94, 43); + StartDecBtn.TabIndex = 3; + StartDecBtn.Text = "开启检测"; + StartDecBtn.UseVisualStyleBackColor = true; + StartDecBtn.Click += StartDecBtn_Click; + // + // ScanDevList + // + ScanDevList.Location = new Point(272, 25); + ScanDevList.Name = "ScanDevList"; + ScanDevList.Size = new Size(75, 23); + ScanDevList.TabIndex = 2; + ScanDevList.Text = "Scan"; + ScanDevList.UseVisualStyleBackColor = true; + ScanDevList.Click += ScanDevList_Click; + // + // DevNameCombo + // + DevNameCombo.FormattingEnabled = true; + DevNameCombo.Location = new Point(54, 25); + DevNameCombo.Name = "DevNameCombo"; + DevNameCombo.Size = new Size(200, 25); + DevNameCombo.TabIndex = 1; + // + // InitMachine + // + InitMachine.Location = new Point(54, 127); + InitMachine.Name = "InitMachine"; + InitMachine.Size = new Size(94, 43); + InitMachine.TabIndex = 0; + InitMachine.Text = "初始化设备"; + InitMachine.UseVisualStyleBackColor = true; + InitMachine.Click += InitMachine_Click; + // + // panel6 + // + panel6.Controls.Add(groupBox2); + panel6.Location = new Point(0, 0); + panel6.Name = "panel6"; + panel6.Size = new Size(847, 531); + panel6.TabIndex = 1; + // + // groupBox2 + // + groupBox2.AutoSize = true; + groupBox2.Controls.Add(ResultMat2Show); + groupBox2.Controls.Add(originMat2Show); + groupBox2.Controls.Add(ResultMatShow2); + groupBox2.Controls.Add(originMatShow2); + groupBox2.Controls.Add(originMatShow); + groupBox2.Controls.Add(ResultMatShow); + groupBox2.Location = new Point(8, 4); + groupBox2.Name = "groupBox2"; + groupBox2.Size = new Size(839, 493); + groupBox2.TabIndex = 0; + groupBox2.TabStop = false; + groupBox2.Text = "图片"; + // + // ResultMat2Show + // + ResultMat2Show.Location = new Point(574, 245); + ResultMat2Show.Name = "ResultMat2Show"; + ResultMat2Show.Size = new Size(259, 213); + ResultMat2Show.SizeMode = PictureBoxSizeMode.StretchImage; + ResultMat2Show.TabIndex = 7; + ResultMat2Show.TabStop = false; + // + // originMat2Show + // + originMat2Show.Location = new Point(574, 22); + originMat2Show.Name = "originMat2Show"; + originMat2Show.Size = new Size(259, 213); + originMat2Show.SizeMode = PictureBoxSizeMode.StretchImage; + originMat2Show.TabIndex = 6; + originMat2Show.TabStop = false; + // + // ResultMatShow2 + // + ResultMatShow2.Location = new Point(297, 246); + ResultMatShow2.Name = "ResultMatShow2"; + ResultMatShow2.Size = new Size(271, 213); + ResultMatShow2.SizeMode = PictureBoxSizeMode.StretchImage; + ResultMatShow2.TabIndex = 5; + ResultMatShow2.TabStop = false; + // + // originMatShow2 + // + originMatShow2.Location = new Point(6, 250); + originMatShow2.Name = "originMatShow2"; + originMatShow2.Size = new Size(285, 213); + originMatShow2.SizeMode = PictureBoxSizeMode.StretchImage; + originMatShow2.TabIndex = 4; + originMatShow2.TabStop = false; + // + // originMatShow + // + originMatShow.Location = new Point(6, 22); + originMatShow.Name = "originMatShow"; + originMatShow.Size = new Size(285, 213); + originMatShow.SizeMode = PictureBoxSizeMode.StretchImage; + originMatShow.TabIndex = 3; + originMatShow.TabStop = false; + // + // ResultMatShow + // + ResultMatShow.Location = new Point(297, 22); + ResultMatShow.Name = "ResultMatShow"; + ResultMatShow.Size = new Size(271, 213); + ResultMatShow.SizeMode = PictureBoxSizeMode.StretchImage; + ResultMatShow.TabIndex = 2; + ResultMatShow.TabStop = false; + // + // tabPage3 + // + tabPage3.Controls.Add(panel2); + tabPage3.Location = new Point(4, 26); + tabPage3.Name = "tabPage3"; + tabPage3.Size = new Size(1276, 499); + tabPage3.TabIndex = 4; + tabPage3.Text = "录入新型号"; + tabPage3.UseVisualStyleBackColor = true; + // + // panel2 + // + panel2.Controls.Add(openModelBtn); + panel2.Controls.Add(modelChangeCbx); + panel2.Controls.Add(label34); + panel2.Controls.Add(button4); + panel2.Controls.Add(OpenTwoDirBtn); + panel2.Controls.Add(OpenDirBtn); + panel2.Controls.Add(Cam2MatCbx); + panel2.Controls.Add(label22); + panel2.Controls.Add(Cam1MatCbx); + panel2.Controls.Add(label23); + panel2.Controls.Add(QueryoneBtn); + panel2.Controls.Add(DetectBArMatbox); + panel2.Controls.Add(label24); + panel2.Controls.Add(InsertBtn); + panel2.Controls.Add(moveTwoZbox); + panel2.Controls.Add(label25); + panel2.Controls.Add(moveTwoYbox); + panel2.Controls.Add(label26); + panel2.Controls.Add(moveTwoXbox); + panel2.Controls.Add(label27); + panel2.Controls.Add(moveZbox); + panel2.Controls.Add(label28); + panel2.Controls.Add(moveYbox); + panel2.Controls.Add(label29); + panel2.Controls.Add(moveXbox); + panel2.Controls.Add(label30); + panel2.Controls.Add(OcrBarBox); + panel2.Controls.Add(label31); + panel2.Controls.Add(TypeBox); + panel2.Controls.Add(queryALLBtn); + panel2.Controls.Add(label32); + panel2.Controls.Add(InsertDataDgv); + panel2.Location = new Point(8, 3); + panel2.Name = "panel2"; + panel2.Size = new Size(1260, 533); + panel2.TabIndex = 1; + // + // openModelBtn + // + openModelBtn.Location = new Point(1042, 15); + openModelBtn.Name = "openModelBtn"; + openModelBtn.Size = new Size(75, 23); + openModelBtn.TabIndex = 37; + openModelBtn.Text = "打开模型"; + openModelBtn.UseVisualStyleBackColor = true; + openModelBtn.Click += openModelBtn_Click; + // + // modelChangeCbx + // + modelChangeCbx.Location = new Point(824, 15); + modelChangeCbx.Name = "modelChangeCbx"; + modelChangeCbx.Size = new Size(188, 23); + modelChangeCbx.TabIndex = 34; + modelChangeCbx.Text = "D:\\Hisence\\config\\chinese.json"; + // + // label34 + // + label34.AutoSize = true; + label34.Location = new Point(718, 21); + label34.Name = "label34"; + label34.Size = new Size(80, 17); + label34.TabIndex = 33; + label34.Text = "面板语言选择"; + // + // button4 + // + button4.Location = new Point(696, 152); + button4.Name = "button4"; + button4.Size = new Size(75, 23); + button4.TabIndex = 32; + button4.Text = "打开文件"; + button4.UseVisualStyleBackColor = true; + button4.Click += button4_Click_1; + // + // OpenTwoDirBtn + // + OpenTwoDirBtn.Location = new Point(696, 241); + OpenTwoDirBtn.Name = "OpenTwoDirBtn"; + OpenTwoDirBtn.Size = new Size(75, 23); + OpenTwoDirBtn.TabIndex = 31; + OpenTwoDirBtn.Text = "打开文件"; + OpenTwoDirBtn.UseVisualStyleBackColor = true; + OpenTwoDirBtn.Click += OpenTwoDirBtn_Click; + // + // OpenDirBtn + // + OpenDirBtn.Location = new Point(696, 193); + OpenDirBtn.Name = "OpenDirBtn"; + OpenDirBtn.Size = new Size(75, 23); + OpenDirBtn.TabIndex = 30; + OpenDirBtn.Text = "打开文件"; + OpenDirBtn.UseVisualStyleBackColor = true; + OpenDirBtn.Click += OpenDirBtn_Click; + // + // Cam2MatCbx + // + Cam2MatCbx.Location = new Point(478, 244); + Cam2MatCbx.Name = "Cam2MatCbx"; + Cam2MatCbx.Size = new Size(218, 23); + Cam2MatCbx.TabIndex = 29; + Cam2MatCbx.Text = "D:\\Hisence\\4\\202452915599711.jpg"; + // + // label22 + // + label22.AutoSize = true; + label22.Location = new Point(371, 244); + label22.Name = "label22"; + label22.Size = new Size(80, 17); + label22.TabIndex = 28; + label22.Text = "面板第二张图"; + // + // Cam1MatCbx + // + Cam1MatCbx.Location = new Point(478, 193); + Cam1MatCbx.Name = "Cam1MatCbx"; + Cam1MatCbx.Size = new Size(218, 23); + Cam1MatCbx.TabIndex = 27; + Cam1MatCbx.Text = "D:\\Hisence\\4\\202452915596701.jpg"; + // + // label23 + // + label23.AutoSize = true; + label23.Location = new Point(372, 199); + label23.Name = "label23"; + label23.Size = new Size(80, 17); + label23.TabIndex = 26; + label23.Text = "面板第一张图"; + // + // QueryoneBtn + // + QueryoneBtn.Location = new Point(896, 245); + QueryoneBtn.Name = "QueryoneBtn"; + QueryoneBtn.Size = new Size(93, 23); + QueryoneBtn.TabIndex = 25; + QueryoneBtn.Text = "条件查询"; + QueryoneBtn.UseVisualStyleBackColor = true; + QueryoneBtn.Click += QueryoneBtn_Click; + // + // DetectBArMatbox + // + DetectBArMatbox.Location = new Point(477, 152); + DetectBArMatbox.Name = "DetectBArMatbox"; + DetectBArMatbox.Size = new Size(219, 23); + DetectBArMatbox.TabIndex = 24; + DetectBArMatbox.Text = "D:\\Hisence\\202452414231.jpg"; + // + // label24 + // + label24.AutoSize = true; + label24.Location = new Point(402, 158); + label24.Name = "label24"; + label24.Size = new Size(56, 17); + label24.TabIndex = 23; + label24.Text = "条码录入"; + // + // InsertBtn + // + InsertBtn.Location = new Point(896, 155); + InsertBtn.Name = "InsertBtn"; + InsertBtn.Size = new Size(93, 23); + InsertBtn.TabIndex = 22; + InsertBtn.Text = "插入"; + InsertBtn.UseVisualStyleBackColor = true; + InsertBtn.Click += InsertBtn_Click; + // + // moveTwoZbox + // + moveTwoZbox.Location = new Point(477, 101); + moveTwoZbox.Name = "moveTwoZbox"; + moveTwoZbox.Size = new Size(219, 23); + moveTwoZbox.TabIndex = 21; + moveTwoZbox.Text = "0"; + // + // label25 + // + label25.AutoSize = true; + label25.Location = new Point(371, 107); + label25.Name = "label25"; + label25.Size = new Size(87, 17); + label25.TabIndex = 20; + label25.Text = "第二次拍照Z轴"; + // + // moveTwoYbox + // + moveTwoYbox.Location = new Point(477, 54); + moveTwoYbox.Name = "moveTwoYbox"; + moveTwoYbox.Size = new Size(213, 23); + moveTwoYbox.TabIndex = 19; + moveTwoYbox.Text = "0"; + // + // label26 + // + label26.AutoSize = true; + label26.Location = new Point(371, 60); + label26.Name = "label26"; + label26.Size = new Size(87, 17); + label26.TabIndex = 18; + label26.Text = "第二次拍照Y轴"; + // + // moveTwoXbox + // + moveTwoXbox.Location = new Point(477, 12); + moveTwoXbox.Name = "moveTwoXbox"; + moveTwoXbox.Size = new Size(213, 23); + moveTwoXbox.TabIndex = 17; + moveTwoXbox.Text = "54964"; + // + // label27 + // + label27.AutoSize = true; + label27.Location = new Point(371, 18); + label27.Name = "label27"; + label27.Size = new Size(88, 17); + label27.TabIndex = 16; + label27.Text = "第二次拍照X轴"; + // + // moveZbox + // + moveZbox.Location = new Point(111, 193); + moveZbox.Name = "moveZbox"; + moveZbox.Size = new Size(188, 23); + moveZbox.TabIndex = 15; + moveZbox.Text = "0"; + // + // label28 + // + label28.AutoSize = true; + label28.Location = new Point(12, 199); + label28.Name = "label28"; + label28.Size = new Size(87, 17); + label28.TabIndex = 14; + label28.Text = "第一次拍照Z轴"; + // + // moveYbox + // + moveYbox.Location = new Point(111, 146); + moveYbox.Name = "moveYbox"; + moveYbox.Size = new Size(188, 23); + moveYbox.TabIndex = 13; + moveYbox.Text = "0"; + // + // label29 + // + label29.AutoSize = true; + label29.Location = new Point(17, 152); + label29.Name = "label29"; + label29.Size = new Size(87, 17); + label29.TabIndex = 12; + label29.Text = "第一次拍照Y轴"; + // + // moveXbox + // + moveXbox.Location = new Point(111, 104); + moveXbox.Name = "moveXbox"; + moveXbox.Size = new Size(188, 23); + moveXbox.TabIndex = 11; + moveXbox.Text = "8974"; + // + // label30 + // + label30.AutoSize = true; + label30.Location = new Point(17, 110); + label30.Name = "label30"; + label30.Size = new Size(88, 17); + label30.TabIndex = 10; + label30.Text = "第一次拍照X轴"; + // + // OcrBarBox + // + OcrBarBox.Location = new Point(111, 54); + OcrBarBox.Name = "OcrBarBox"; + OcrBarBox.Size = new Size(188, 23); + OcrBarBox.TabIndex = 5; + OcrBarBox.Text = "1234567890"; + // + // label31 + // + label31.AutoSize = true; + label31.Location = new Point(14, 60); + label31.Name = "label31"; + label31.Size = new Size(32, 17); + label31.TabIndex = 4; + label31.Text = "条码"; + // + // TypeBox + // + TypeBox.Location = new Point(111, 12); + TypeBox.Name = "TypeBox"; + TypeBox.Size = new Size(188, 23); + TypeBox.TabIndex = 3; + TypeBox.Text = "1"; + // + // queryALLBtn + // + queryALLBtn.Location = new Point(896, 196); + queryALLBtn.Name = "queryALLBtn"; + queryALLBtn.Size = new Size(93, 23); + queryALLBtn.TabIndex = 2; + queryALLBtn.Text = "查询全部"; + queryALLBtn.UseVisualStyleBackColor = true; + queryALLBtn.Click += queryALLBtn_Click; + // + // label32 + // + label32.AutoSize = true; + label32.Location = new Point(14, 18); + label32.Name = "label32"; + label32.Size = new Size(32, 17); + label32.TabIndex = 1; + label32.Text = "类型"; + // + // InsertDataDgv + // + InsertDataDgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + InsertDataDgv.Location = new Point(12, 281); + InsertDataDgv.Name = "InsertDataDgv"; + InsertDataDgv.RowTemplate.Height = 25; + InsertDataDgv.Size = new Size(1245, 219); + InsertDataDgv.TabIndex = 0; + // + // richTextBox1 + // + richTextBox1.Dock = DockStyle.Bottom; + richTextBox1.Location = new Point(0, 801); + richTextBox1.Name = "richTextBox1"; + richTextBox1.Size = new Size(1284, 176); + richTextBox1.TabIndex = 1; + richTextBox1.Text = ""; + // + // contextMenuStrip1 + // + contextMenuStrip1.Name = "contextMenuStrip1"; + contextMenuStrip1.Size = new Size(61, 4); + // + // dataGridView1 + // + dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView1.Dock = DockStyle.Fill; + dataGridView1.Location = new Point(0, 529); + dataGridView1.Name = "dataGridView1"; + dataGridView1.RowTemplate.Height = 25; + dataGridView1.Size = new Size(1284, 272); + dataGridView1.TabIndex = 3; + // + // MainForm + // + AutoScaleDimensions = new SizeF(7F, 17F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1284, 977); + Controls.Add(dataGridView1); + Controls.Add(richTextBox1); + Controls.Add(tabControl1); + Name = "MainForm"; + Text = "海信视觉防差错"; + Load += MainForm_Load; + tabPage2.ResumeLayout(false); + panel1.ResumeLayout(false); + panel1.PerformLayout(); + groupBox5.ResumeLayout(false); + groupBox5.PerformLayout(); + groupBox4.ResumeLayout(false); + groupBox4.PerformLayout(); + ModeleShow.ResumeLayout(false); + tabPage1.ResumeLayout(false); + groupBox3.ResumeLayout(false); + groupBox3.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox2).EndInit(); + groupBox1.ResumeLayout(false); + groupBox1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit(); + tabControl1.ResumeLayout(false); + tabPage5.ResumeLayout(false); + panel4.ResumeLayout(false); + panel5.ResumeLayout(false); + panel8.ResumeLayout(false); + panel8.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)OKOrNGShow).EndInit(); + panel6.ResumeLayout(false); + panel6.PerformLayout(); + groupBox2.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)ResultMat2Show).EndInit(); + ((System.ComponentModel.ISupportInitialize)originMat2Show).EndInit(); + ((System.ComponentModel.ISupportInitialize)ResultMatShow2).EndInit(); + ((System.ComponentModel.ISupportInitialize)originMatShow2).EndInit(); + ((System.ComponentModel.ISupportInitialize)originMatShow).EndInit(); + ((System.ComponentModel.ISupportInitialize)ResultMatShow).EndInit(); + tabPage3.ResumeLayout(false); + panel2.ResumeLayout(false); + panel2.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)InsertDataDgv).EndInit(); + ((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit(); + ResumeLayout(false); + } + + #endregion + private TabPage tabPage2; + private TabPage tabPage1; + private Label label1; + private Button Cam1OpenBtn; + private PictureBox pictureBox1; + private TabControl tabControl1; + private TabPage tabPage5; + private Panel panel4; + private Panel panel7; + private Panel panel6; + private Panel panel5; + private Panel panel8; + private GroupBox groupBox2; + private PictureBox originMatShow; + private PictureBox ResultMatShow; + private GroupBox groupBox1; + private Button bnSetParam; + private Button bnGetParam; + private TextBox tbGain; + private TextBox tbExposure; + private Label label2; + private Label label4; + private PictureBox pictureBox2; + private Button button2; + private Button SnapshotCam1; + private Button InitMachine; + private TextBox readPLc; + private Button ConnectPLC; + private Button readAdress; + private TextBox showPLC; + private Panel panel1; + private Label label9; + private Label label10; + private Button wirteAdressBtn; + private TextBox PLCValue; + private TextBox WriteAdress; + private Label label6; + private Label label3; + private TextBox writePLCValue; + private GroupBox ModeleShow; + private Button PLCPowerON; + private Button PLCPostion; + private Button PLCDiskZero; + private System.Windows.Forms.Timer timer1; + private System.Windows.Forms.Timer timer2; + private System.Windows.Forms.Timer timer3; + private System.Windows.Forms.Timer timer4; + private System.Windows.Forms.Timer timer5; + private System.Windows.Forms.Timer timer6; + private GroupBox groupBox4; + private Label XCurrentPostion; + private Label label14; + private Label label13; + private Label label12; + private Label label11; + private Label ZPostion; + private Label YPostion; + private Label XPostion; + private Button ScanDevList; + private ComboBox DevNameCombo; + private RichTextBox richTextBox1; + private TextBox txtSetValue; + private TextBox lnEditmiZOP; + private TextBox lnEditmiYOP; + private TextBox lnEditmiXOP; + private Label label17; + private TextBox lnEditmiZS; + private TextBox lnEditmiYS; + private TextBox lnEditmiXS; + private Label label16; + private TextBox lnEditmiZHS; + private TextBox lnEditmiYHS; + private TextBox lnEditmiXHS; + private Label label15; + private Button StartDecBtn; + private ContextMenuStrip contextMenuStrip1; + private DataGridView dataGridView1; + private Button InsertSqlBtn; + private PictureBox ResultMatShow2; + private PictureBox originMatShow2; + private TextBox OKDNum; + private Label label20; + private TextBox NGDNum; + private Label label19; + private TextBox AllDSum; + private Label label18; + private Label 实时显示; + private PictureBox OKOrNGShow; + private Button RefeshData; + private GroupBox groupBox3; + private Button SnapshotCam2; + private Button button3; + private Button bnSetParam2; + private Label label5; + private Button Cam2OpenBtn; + private Button bnGetParam2; + private TextBox tbGain2; + private TextBox tbExposure2; + private Label label7; + private Label label8; + private TextBox SetlnEditmiZOP; + private TextBox SetlnEditmiYOP; + private TextBox SetlnEditmiXOP; + private TextBox SetlnEditmiZH; + private TextBox SetlnEditmiYH; + private TextBox SetlnEditmiXH; + private Button SetAutoSpeed; + private Button SetHandleSpeed; + private RadioButton XZerorbx; + private System.ComponentModel.BackgroundWorker backgroundWorker1; + private RadioButton YZerorbx; + private RadioButton ZZerorbx; + private RadioButton XForwardrbx; + private RadioButton YForwardrbx; + private RadioButton ZForwardrbx; + private RadioButton XBackwardrbx; + private RadioButton YBackwardrbx; + private RadioButton ZBackwardrbx; + private GroupBox groupBox5; + private TextBox DistanceShow; + private Label label21; + private PictureBox originMat2Show; + private PictureBox ResultMat2Show; + private TabPage tabPage3; + private Panel panel2; + private Button button4; + private Button OpenTwoDirBtn; + private Button OpenDirBtn; + private TextBox Cam2MatCbx; + private Label label22; + private TextBox Cam1MatCbx; + private Label label23; + private Button QueryoneBtn; + private TextBox DetectBArMatbox; + private Label label24; + private Button InsertBtn; + private TextBox moveTwoZbox; + private Label label25; + private TextBox moveTwoYbox; + private Label label26; + private TextBox moveTwoXbox; + private Label label27; + private TextBox moveZbox; + private Label label28; + private TextBox moveYbox; + private Label label29; + private TextBox moveXbox; + private Label label30; + private TextBox OcrBarBox; + private Label label31; + private TextBox TypeBox; + private Button queryALLBtn; + private Label label32; + private DataGridView InsertDataDgv; + private Button openModelBtn; + private TextBox modelChangeCbx; + private Label label34; + } +} diff --git a/HisenceYoloDetection/MainForm.cs b/HisenceYoloDetection/MainForm.cs new file mode 100644 index 0000000..bf92fb8 --- /dev/null +++ b/HisenceYoloDetection/MainForm.cs @@ -0,0 +1,2042 @@ +using DVPCameraType; +using Microsoft.VisualBasic.Logging; +using OpenCvSharp; +using OpenCvSharp.Dnn; +using OpenCvSharp.Extensions; +using OpenCvSharp.XFeatures2D; +using System.Data; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Net; +using System.Numerics; +using System.Text.RegularExpressions; +using System.Windows.Forms; +using XKRS.Device.SimboVision.SimboHelper; +using static HisenceYoloDetection.MainForm; +using static System.Runtime.InteropServices.JavaScript.JSType; +using static System.Windows.Forms.VisualStyles.VisualStyleElement; + + +namespace HisenceYoloDetection +{ + public partial class MainForm : Form + { + public MainForm() + { + InitializeComponent(); + } + MGSCameraDriver Cam1 = new MGSCameraDriver(); + MGSCameraDriver Cam2 = new MGSCameraDriver(); + SQLiteHelper sqlhelper = new SQLiteHelper(); + TCPClienDriver Scanner = new TCPClienDriver(); + MelsecPLCTCPDriver melsecPLCTCPDriver = new MelsecPLCTCPDriver(); + SimboObjectDetection simboObjectDetection = new SimboObjectDetection(); + PaddleOcrModel paddleOcrModel = new PaddleOcrModel(); + PaddleOcrModelCountry paddleOcrModelCountry = new PaddleOcrModelCountry(); + List xKHisences = new List(); + + static AutoResetEvent myResetEvent = new AutoResetEvent(false); + bool PLC545 = false; + + bool PLC548 = false; + string m_sKEYENCEBar; + string IfChangeLanguage = "";//Ƿϴ»ͺ + bool bTriger = true;//ǷԴ + bool bBarTriger = false;//һַɺܴڶλ + bool bBar = false;//ǷԷ + bool IfCam1OneTriger = false;//1һ + bool IfCam1TwoTriger = false;//12 + bool IfCam2Triger = false;//2һ + Mat Cam1ImgOne = new Mat();//ʵʱ1Ƭ + Mat Cam1ImgTwo = new Mat();//ʵʱ1Ƭ + Mat Cam2ImgShowBar = new Mat();//ʵʱ2Ƭ ʶ + + XKHisence xKNow;//ݿеϴ» + bool bOn = false; + //////////////////////////// + public static int m_CamCount = 0; + public int m_n_dev_count = 0; + public static dvpCameraInfo[] m_info = new dvpCameraInfo[16]; + bool ifXZeroValue = false; + bool ifYZeroValue = false; + bool ifZZeroValue = false; + + bool ifXForward = false; + bool ifYForward = false; + bool ifZForward = false; + + bool ifXBackward = false; + bool ifYBackward = false; + bool ifZBackward = false; + //¼ݿ + string BarPath = ""; + string Cam1OnePath = ""; + string Cam1TwoPath = ""; + string ModelChangePath = ""; + /// + /// 鿴б + /// + public void InitDevList() + { + dvpStatus status; + uint i, n = 0; + dvpCameraInfo dev_info = new dvpCameraInfo(); + + // "n" represents the number of cameras that is enumerated successfully, the drop-down list contains each camera's FriendlyName. + DevNameCombo.Items.Clear(); + + // Get the number of cameras that has been connected to a computer. + status = DVPCamera.dvpRefresh(ref n); + Debug.Assert(status == dvpStatus.DVP_STATUS_OK); + m_n_dev_count = (int)n; + if (status == dvpStatus.DVP_STATUS_OK) + { + m_CamCount = 0; + + for (i = 0; i < n; i++) + { + // Acquire each camera's information one by one. + status = DVPCamera.dvpEnum(i, ref dev_info); + Debug.Assert(status == dvpStatus.DVP_STATUS_OK); + if (status == dvpStatus.DVP_STATUS_OK) + { + m_info[m_CamCount] = dev_info; + + int item = -1; + + // add User Define Name + item = DevNameCombo.Items.Add(dev_info.UserID); + + if (item == 0) + { + DevNameCombo.SelectedIndex = item; + } + m_CamCount++; + + if (item == 0) + { + DevNameCombo.SelectedIndex = item; + } + } + } + } + + + + + + } + System.Timers.Timer SpeedTimer = new System.Timers.Timer(); + System.Timers.Timer PostionTimer = new System.Timers.Timer(); + + public delegate void MyDelegateUI(); //ί + MyDelegateUI myDelegateUI; //ίж + + public delegate void MyPosDelegateUI(); //ί + MyPosDelegateUI myPosDelegateUI; //ίж + + public delegate void MyLogDelegateUI(); //ί + MyLogDelegateUI myLogDelegateUI; //־ίж + private void Application_ThreadException(Exception e) + { + string msg = e.Message; + + using (StreamWriter sw = new StreamWriter("D://ThreadException.log", true)) + { + sw.WriteLine("================================"); + sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); + sw.WriteLine(msg); + sw.Flush(); + } + + + + } + /// + /// + /// + /// + /// + private void MainForm_Load(object sender, EventArgs e) + { + string vBarPath = "D:\\Hisence\\202452915589671.jpg"; + string vCam1OnePath = "D:\\Hisence\\4\\202452915596701.jpg"; + string vCam1TwoPath = "D:\\Hisence\\4\\202452915599711.jpg"; + string vModelChangePath = "D:\\Hisence\\config\\chinese.json"; + if (File.Exists(vBarPath) && File.Exists(vCam1OnePath) && File.Exists(vCam1TwoPath) && File.Exists(vModelChangePath)) + { + BarPath = vBarPath; + Cam1OnePath = vCam1OnePath; + Cam1TwoPath = vCam1TwoPath; + ModelChangePath = vModelChangePath; + } + ifXZeroValue = XZerorbx.Checked; + ifYZeroValue = YZerorbx.Checked; + InitDevList(); + this.WindowState = FormWindowState.Maximized; + + string Dectionstr = "D:\\Hisence\\best.onnx"; + string CountryStr = "D:\\Hisence\\config\\chinese.json"; + if (File.Exists(Dectionstr) && File.Exists(CountryStr)) + { + } + else + { + MessageBox.Show("" + Dectionstr + " " + CountryStr + "ģ"); + return; + } + //ʼ + simboObjectDetection.Load(Dectionstr, "CPU", "images", 640, 640); + paddleOcrModelCountry.Load(CountryStr, "CPU"); + paddleOcrModel.Load(CountryStr, "CPU"); + IfChangeLanguage = CountryStr; + // + + StartDecBtn.Enabled = false; + + //myThread = new Thread(doWork); + myDelegateUI = new MyDelegateUI(initAll);//ί + + + myPosDelegateUI = new MyPosDelegateUI(initAll2);//ί + + myLogDelegateUI = new MyLogDelegateUI(initAll3);//ί + + //ʼPLC + melsecPLCTCPDriver.Start(); + + + + + //bool ismatch = IsMatchOcrText("WF3S7021BB", strMatListListOne); + //ص + + melsecPLCTCPDriver.Heartbeat -= PLcHeratAdress; + melsecPLCTCPDriver.Heartbeat += PLcHeratAdress; + + OnSpeedShow();//߳̿ٶʾڽ + OnPostionShow();//߳̿λʾڽ + } + private void initAll() //Ϣ + { + //richTextBox1.AppendText("TEST line \r"); + if (HspeedList.Count == 33) + { + + lnEditmiXHS.Text = HspeedList[1].ToString(); + lnEditmiYHS.Text = HspeedList[6].ToString(); + lnEditmiZHS.Text = HspeedList[11].ToString(); + //λٶ + lnEditmiXS.Text = HspeedList[0].ToString(); + lnEditmiYS.Text = HspeedList[5].ToString(); + lnEditmiZS.Text = HspeedList[10].ToString(); + } + if (disShow != 0) + { + //TODOʵʱʽ ֪ƶ + double disreal = disShow * (-0.54054) + 1324.3232; + DistanceShow.Text = Math.Ceiling(disreal).ToString(); + //һԪһ + //y = -0.54054x + 1324.3232 + + } + } + private void initAll2() //Ϣ + { + if (relPosStrList.Count == 31) + { + + + // XPostion.Text = ""; + XPostion.Text = relPosStrList[0].ToString(); + //YPostion.Text = ""; + YPostion.Text = relPosStrList[5].ToString(); + // ZPostion.Text = ""; + ZPostion.Text = relPosStrList[10].ToString(); + + } + } + string Logtxt = ""; + private void initAll3() //Ϣ + { + richTextBox1.AppendText(Logtxt); + AllDSum.Text = AllDsums.ToString(); + OKDNum.Text = OKDsums.ToString(); + NGDNum.Text = NGDsums.ToString(); + using (StreamWriter stream = new StreamWriter("D://information.log", true)) + { + stream.WriteLine(Logtxt); + stream.Flush(); + } + } + + private void OnSpeedShow() + { + Task.Run(() => + { + while (true) + { + try + { + UpDatePlcValue(600, 2); + //404 ַ 33ַ + UpDatePlcValue(404, 33); + if (HspeedList.Count == 33) + { + + //ֶٶ + + this.Invoke(myDelegateUI); //richTextBox1.AppendText("TEST line \r"); + Application.DoEvents(); + } + if (disShow != 0) + { + this.Invoke(myDelegateUI); //richTextBox1.AppendText("TEST line \r"); + Application.DoEvents(); + } + + } + catch (Exception ex) + { + + } + + Thread.Sleep(200); + } + }); + } + + private void OnPostionShow() + { + Task.Run(() => + { + while (true) + { + try + { + UpDatePlcValue(102, 31); + if (relPosStrList.Count == 31) + { + this.Invoke(myPosDelegateUI); //richTextBox1.AppendText("TEST line \r"); + Application.DoEvents(); + + + + } + } + catch (Exception ex) + { + } + + + Thread.Sleep(200); + } + }); + + } + /// + /// + /// + /// + /// + private void CamOpenBtn_Click(object sender, EventArgs e) + { + + + Cam1.Start("Cam1"); + + bnGetParam.Enabled = true; + SetCtrlWhenOpen(); + Cam1OpenBtn.BackColor = Color.Green; + + } + private void SetCtrlWhenOpen() + { + + + tbExposure.Enabled = true; + tbGain.Enabled = true; + // tbFrameRate.Enabled = true; + bnGetParam.Enabled = true; + bnSetParam.Enabled = true; + } + private void bnGetParam_Click(object sender, EventArgs e) + { + tbExposure.Text = Cam1.dvpGetExposure().ToString(); + tbGain.Text = Cam1.dvpGetAnalogGain().ToString(); + + } + + private void bnGetParam2_Click(object sender, EventArgs e) + { + //tbExposure2.Text = Cam1.dvpGetExposure().ToString(); + //tbGain2.Text = Cam1.dvpGetAnalogGain().ToString(); + } + /// + /// 2 + /// + /// + /// + private void Cam2OpenBtn_Click(object sender, EventArgs e) + { + + // Cam2.Start("Cam2"); + // bnGetParam2.Enabled = true; + // Cam2OpenBtn.BackColor = Color.Green; + } + + private void button2_Click(object sender, EventArgs e) + { + Cam1.Stop(); + SetCtrlWhenClose(); + } + private void SetCtrlWhenClose() + { + + tbExposure.Enabled = false; + tbGain.Enabled = false; + // tbFrameRate.Enabled = false; + bnGetParam.Enabled = false; + bnSetParam.Enabled = false; + } + private void button3_Click(object sender, EventArgs e) + { + Cam2.Stop(); + } + /// + /// 1 + /// + /// + /// + private void SnapshotCam1_Click(object sender, EventArgs e) + { + Cam1.Snapshot(); + + } + /// + /// 2 + /// + /// + /// + private void SnapshotCam2_Click(object sender, EventArgs e) + { + //Cam2.Snapshot(); + } + int TimesCalled = 0; + Bitmap OKbitmap = new Bitmap("OK.jpg"); + Bitmap NGbitmap = new Bitmap("NG.jpg"); + + /// + /// ̵߳ + /// + /// + /// + private void InitMachine_Click(object sender, EventArgs e) + { + try + { + //ʼ + + DataSet dataSet = SQLiteHelper.Query("select * from XK_HisenceDet"); + dataGridView1.DataSource = dataSet.Tables[0]; + + // xKNow = GetModeFromBar("VWJ070633V0WW80F0120356");//ݿвѯֵ + //string sql = "insert into XK_HisenceDet VALUES('" + xKNow.Type + "','" + xKNow.OcrBar + "'," + xKNow.MoveX + "," + xKNow.MoveY + "," + + // xKNow.MoveZ + ",'" + "123" + "',null," + xKNow.MoveTwoZ + "," + xKNow.MoveTwoY + "," + xKNow.MoveTwoZ + ", '" + DateTime.Now + "'," + 1 + ")"; + //SQLiteHelper.ExecuteSql(sql); + Cam1.Start("Cam1"); + if (Cam1.IfSuccess) + { + myLog("Cam1", DateTime.Now); + } + Cam2.Start("Cam2"); + if (Cam2.IfSuccess) + { + myLog("Cam2", DateTime.Now); + } + Cam1.OnHImageOutput -= OnCameraMatOutPut; + Cam1.OnHImageOutput += OnCameraMatOutPut; + Cam2.OnHImageOutput -= OnCameraMatOutPut2; + Cam2.OnHImageOutput += OnCameraMatOutPut2; + + OKOrNGShow.Image = OKbitmap; + //ʼɨǹ + //Scanner.Strart(); + //Scanner.OnClientDataReceived -= OnDataReceived; + //Scanner.OnClientDataReceived += OnDataReceived; + //Scanner.btnSendMsg("LON\r");//Ϳָ + //myLog("Ͷʿɨǹָ", DateTime.Now); + + //PLCʹܿ + melsecPLCTCPDriver.WriteInt("581", 0);//λɿ + melsecPLCTCPDriver.WriteInt("504", 0);//λɿ + melsecPLCTCPDriver.WriteInt("514", 0);//λɿ + melsecPLCTCPDriver.WriteInt("524", 0);//λɿ + melsecPLCTCPDriver.WriteInt("406", 60000); //дֶٶ + melsecPLCTCPDriver.WriteInt("416", 8000); + melsecPLCTCPDriver.WriteInt("426", 8000); + melsecPLCTCPDriver.WriteInt("404", 100000); //д붨λٶ + melsecPLCTCPDriver.WriteInt("414", 8000); + melsecPLCTCPDriver.WriteInt("424", 8000); + + + melsecPLCTCPDriver.WriteInt("500", 0); + + melsecPLCTCPDriver.WriteInt("500", 1); + Thread.Sleep(200); + + bOn = true; + melsecPLCTCPDriver.WriteInt("580", 0);// + melsecPLCTCPDriver.WriteInt("580", 1);// + Thread.Sleep(200); + melsecPLCTCPDriver.WriteInt("580", 0); + Thread.Sleep(200); + while (true) + { + int IfXZeros = melsecPLCTCPDriver.ReadInt("102"); + int IfYZeros = melsecPLCTCPDriver.ReadInt("112"); + int IfZZeros = melsecPLCTCPDriver.ReadInt("122"); + if (IfXZeros <= 40 && IfYZeros <= 140 && IfZZeros <= 40) + { + StartDecBtn.Enabled = true; + break; + } + Thread.Sleep(10); + } + + + + myLog("豸ȫ", DateTime.Now); + + } + catch (Exception ex) + { + Application_ThreadException(ex); + } + + } + /// + /// ȫͼϴ» ü֮ OCRʶĽ + /// + /// + /// + /// + private void InsertSqlRunData(ref Mat currentMatC, MLResult cam1TwoML, ref List strMatListList, ref PaddleOcrModel IOcrModel) + { + + + +#if false + try + { + List mats = new List(); + + Mat mResultCut = currentMatC.Clone(); + string OcrTextinsert = ""; + for (int i = 0; i < cam1TwoML.ResultDetails.Count; i++) + { + Mat mResultCuti = mResultCut.Clone(); + int rectsx = cam1TwoML.ResultDetails[i].Rect.X; + int rectsy = cam1TwoML.ResultDetails[i].Rect.Y; + int rectsWidth = cam1TwoML.ResultDetails[i].Rect.Width; + int rectsHeight = cam1TwoML.ResultDetails[i].Rect.Height; + Rect area = new Rect(rectsx, rectsy, rectsWidth, rectsHeight); + Mat matroi = new Mat(mResultCuti, area); + mats.Add(matroi); + //OCRʶüͼƬ + MLRequest reqcut = new MLRequest(); + reqcut.currentMat = matroi.Clone(); + MLResultModel mLcut = IOcrModel.RunInferenceFixed(reqcut); + + + for (int j = 0; j < mLcut.ResultDetails.Count; j++) + { + string jdetial = mLcut.ResultDetails[j].LabelDisplay; + strMatListList.Add(jdetial); + OcrTextinsert += jdetial + "##"; + } + + + } + + + } + catch (Exception ex) + { + + } +#endif + + + } + + /// + /// ݿӦOCRıǷʶı + /// + /// + /// + /// + private bool IsMatchOcrText(string WashBar, List DetMatstrList) + { + try + { + xKNow = GetModeFromBar(WashBar);//ݿвѯֵ + List strMatListListB = new List(); + if (xKNow.OcrText.Contains("##")) + { + + string[] sArray = Regex.Split(xKNow.OcrText, "##", RegexOptions.IgnoreCase); + + + for (int i = 0; i < sArray.Count(); i++) + { + if (sArray[i] != "") + { + strMatListListB.Add(sArray[i]); + } + + + } + + + } + var firstNotSecond = DetMatstrList.Except(strMatListListB, StringComparer.OrdinalIgnoreCase).ToList(); + var secondNotFirst = strMatListListB.Except(DetMatstrList, StringComparer.OrdinalIgnoreCase).ToList(); + if (firstNotSecond.Count() == 0 && secondNotFirst.Count() == 0) + { + return true; + } + return false; + + } + catch (Exception ex) + { + return false; + } + } + /// + /// ʵʱƶģ + /// + public void MoveToP(int currentXP, int currentYP, int currentZP) + { + + melsecPLCTCPDriver.WriteInt("581", 0); + melsecPLCTCPDriver.WriteInt("402", currentXP); + melsecPLCTCPDriver.WriteInt("412", currentYP); + melsecPLCTCPDriver.WriteInt("422", currentZP); + melsecPLCTCPDriver.WriteInt("581", 1); + Thread.Sleep(200); + melsecPLCTCPDriver.WriteInt("581", 0); + while (true) + { + int IfXZeros = melsecPLCTCPDriver.ReadInt("102"); + int IfYZeros = melsecPLCTCPDriver.ReadInt("112"); + int IfZZeros = melsecPLCTCPDriver.ReadInt("122"); + if ((IfXZeros < currentXP + 20) && (IfXZeros > currentXP - 20) && (IfYZeros <= currentYP + 20) && (IfYZeros >= currentYP - 20) && (IfZZeros <= currentZP + 20) && (IfZZeros >= currentZP - 20))//TODO:õһλ + { + + break; + } + Thread.Sleep(10); + } + } + public int disShow = new int(); + public List MonitorValues { get; set; } = new List(); + public List relPosStrList { get; set; } = new List(); + public List HspeedList { get; set; } = new List(); + /// + /// ʵʱˢPLCֵַ + /// + /// + public void UpDatePlcValue(int Address, int length) + { + //Task.Run(() => + //{ + // while (true) + // { + try + { + //ʵʱˢ»еֵλ + List newValues = melsecPLCTCPDriver.GetMonitorValues(Address, length); + if (newValues == null || newValues.Count == 0) + return; + + Stopwatch sw = new Stopwatch(); + sw.Start(); + if (Address == 600) + { + disShow = melsecPLCTCPDriver.ReadInt(Convert.ToString(Address)); + } + if (Address == 102) //ʼַΪ102 + { + if (relPosStrList.Count == newValues.Count) + { + var tempNew = new List(newValues); + var tempOld = new List(relPosStrList); + //MonitorCheckAndInvoke(tempNew, tempOld); + } + relPosStrList = new List(newValues); + // relPosStrList = MonitorValues; + //ʵʱʾڽ + } + if (Address == 404) + { + if (HspeedList.Count == newValues.Count) + { + var tempNew = new List(newValues); + var tempOld = new List(HspeedList); + //MonitorCheckAndInvoke(tempNew, tempOld); + } + HspeedList = new List(newValues); + //HspeedList = MonitorValues; + //ʵʱʾڽ + } + sw.Stop(); + + if (sw.ElapsedMilliseconds > 20) + { + //LogAsync(DateTime.Now, LogLevel.Detail, $"{this.Name}ѯʱ䣺{sw.ElapsedMilliseconds}"); + } + Thread.Sleep(20); + } + catch (Exception ex) + { + + } + + // } + //}); + } + /// + /// ϴ»545Ƿ񴥷䴫 + /// + public void TrigerCamera1() + { + //һ̼߳PLCֵ + Task.Run(() => + { + int iNum1 = 0; + int iNum0 = 0; + while (true) + { + // myResetEvent.Set(); + PLC545 = true; + int m_iCureent545 = melsecPLCTCPDriver.ReadInt("545"); + ////int m_iCureent545 = CMPLC.SLMPReadD(545); + if (m_iCureent545 != 1) + { + iNum0++; + } + else + { + iNum0 = 0; + } + if (iNum0 >= 5) + { + while (true) + { + m_iCureent545 = melsecPLCTCPDriver.ReadInt("545"); + if (m_iCureent545 == 1) + { + iNum1++; + } + else + { + iNum1 = 0; + } + if (iNum1 >= 5) + { + //Console.WriteLine("ڶβɼͼ"); + //Cam1.Snapshot(); + //Cam2.Snapshot(); + //IfCam1Triger = false; + //IfCam2Triger = false; + + iNum0 = 0; + iNum1 = 0; + break; + + } + } + + } + + + Thread.Sleep(100); + + + } + }); + } + /// + /// ȡʿͺ + /// + public void OnGetBar() + { + Task.Run(() => + { + int iNum0 = 0; + int iNum1 = 0; + + // const char pCR[4] = { 0x4C, 0x4F, 0x4E, 0x0D }; + //const char pOFF[5] = { 0x4C, 0x4F, 0x46, 0x46, 0x0D };ر + Thread.CurrentThread.Priority = ThreadPriority.Highest; + while (true) + { + //545ʱΪ0 + // myResetEvent.Set(); + PLC545 = true; + int m_iCureent545 = melsecPLCTCPDriver.ReadInt("545"); + + if (m_iCureent545 != 1) + { + iNum0++; + } + else + { + iNum0 = 0; + } + if (iNum0 >= 1) + { + //ָ + while (true) + { + bTriger = false; + //544һֱ1s + m_iCureent545 = melsecPLCTCPDriver.ReadInt("545"); + if (m_iCureent545 == 1) + { + iNum1++; + } + else + { + iNum1 = 0; + } + if (iNum1 >= 2) + { + if (bBar) + { + bBarTriger = true;//޸ijջȡͺ + Cam2.SnapshotCount = 0; + Cam2.Snapshot(); + + xKNow = GetModeFromBar("VWJ070633V0WW80F0120356");//ݿвѯֵ + //xKNow = GetModeFromBar(m_sKEYENCEBar);//ݿвѯֵ + if (Regex.IsMatch(xKNow.MoveX.ToString(), @"^[0-9]+$") && Regex.IsMatch(xKNow.MoveY.ToString(), @"^[0-9]+$") && Regex.IsMatch(xKNow.MoveZ.ToString(), @"^[0-9]+$")) + { + myLog("ͺƥɹ" + m_sKEYENCEBar, DateTime.Now); + bBarTriger = true; + //MoveToP(xKNow.MoveX, xKNow.MoveY, xKNow.MoveZ);// PLCƵƶ + } + + break; + } + Thread.Sleep(2); + bBar = false; + + } + } + } + + + + + + } + Thread.Sleep(10); + + + }); + } + /// + /// ϴ»544Ƿ񴥷䴫 + /// + public void TriggerCameral2() + { + //һ̼߳PLCֵ + Task.Run(() => + { + try + { + int iNum1 = 0; + int iNum0 = 0; + Thread.CurrentThread.Priority = ThreadPriority.Highest; + while (true) + { + // myResetEvent.Set(); + PLC548 = true; + int m_iCureent548 = melsecPLCTCPDriver.ReadInt("548"); + + if (m_iCureent548 != 0) + { + iNum0++; + } + else + { + iNum0 = 0; + } + if (iNum0 >= 1) + { + while (true) + { + + bTriger = false; + //544һֱ1s + m_iCureent548 = melsecPLCTCPDriver.ReadInt("548"); + if (m_iCureent548 == 0) + { + iNum1++; + } + else + { + iNum1 = 0; + } + if (iNum1 >= 2) + { + //if (bBarTriger) + { + + + myLog("һβɼͼ", DateTime.Now); + //ƶģ βĵַ Ƿǰƶ + List DisList = new List(); + for (int i = 0; i < 5; i++) + { + int m600 = melsecPLCTCPDriver.ReadInt("600"); + DisList.Add(m600); + } + DisList.Remove(DisList.Max()); + DisList.Remove(DisList.Min()); + // ʣֵƽ + double average = DisList.Average(); + double disreal = average * (-0.54054) + 1324.3232; + + + MoveToP(8974, 0, (int)(disreal)); + Thread.Sleep(500); + Cam1.SnapshotCount = 0; + Cam1.Snapshot(); + Cam2.SnapshotCount = 0; + Cam2.Snapshot(); + // myLog("ڶβɼͼ", DateTime.Now); + //if (xKNow != null) + //{ + // MoveToP(xKNow.MoveTwoX, xKNow.MoveTwoY, xKNow.MoveTwoZ); + //} + // currentXP = 54964; + MoveToP(54964, 0, (int)(disreal)); + //Thread.Sleep(3000); + Cam1.Snapshot(); + MoveToP(8974, 0, 0); + //if (xKNow != null) + //{ + // MoveToP(xKNow.MoveX, xKNow.MoveY, xKNow.MoveZ); + //} + myLog("ɼͼɹ", DateTime.Now); + //ģ鸴λ + + bTriger = true;//Խмʶ + bBarTriger = false;//Բ + iNum0 = 0; + iNum1 = 0; + break; + } + + + } + } + + } + + + Thread.Sleep(10); + + + } + + } + catch (Exception e) + { + + } + + }); + } + /// + /// PLC + /// + /// + public void PLcHeratAdress(int ifPlcHeart) + { + if (ifPlcHeart == 1) + { + myLog("PLCʧ", DateTime.Now); + + } + else + { + + } + } + + /// + /// 1Ļص + /// + /// + /// + /// + public void OnCameraMatOutPut(DateTime dt, Mat cameraMat, int SnapshotCount) + { + string fitImageFolder = "D://cam1//"; + if (!Directory.Exists(fitImageFolder)) + { + Directory.CreateDirectory(fitImageFolder); + } + + //һ + if (SnapshotCount == 1) + { + // Mat mat = Cv2.ImRead("F:\\ϴ»\\cam1\\2024517161641.jpg"); + Cam1ImgOne = cameraMat; + IfCam2Triger = true; + originMatShow.Image = cameraMat.ToBitmap(); + //pictureBox1.Image = cameraMat.ToBitmap(); + + + } + //ڶ + if (SnapshotCount == 2) + { + // Mat mat = Cv2.ImRead("F:\\ϴ»\\cam1\\2024517164541.jpg"); + Cam1ImgTwo = cameraMat; + + IfCam1TwoTriger = true; + originMatShow2.Image = cameraMat.ToBitmap(); + //pictureBox1.Image = cameraMat.ToBitmap(); + } + + + pictureBox1.Image = cameraMat.ToBitmap(); + cameraMat.ImWrite(fitImageFolder + dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Millisecond.ToString() + "1.jpg"); + + } + + /// + /// 2ص + /// + /// + /// + /// + public void OnCameraMatOutPut2(DateTime dt, Mat cameraMat, int SnapshotCount) + { + string fitImageFolder = "D://cam2//"; + if (!Directory.Exists(fitImageFolder)) + { + Directory.CreateDirectory(fitImageFolder); + } + //һ + if (SnapshotCount == 1) + { + // Mat mat = Cv2.ImRead("F:\\ϴ»\\cam1\\2024517161641.jpg"); + Cam2ImgShowBar = cameraMat; + IfCam2Triger = true; + originMat2Show.Image = cameraMat.ToBitmap(); + //pictureBox1.Image = cameraMat.ToBitmap(); + + + } + + + pictureBox2.Image = cameraMat.ToBitmap(); + cameraMat.ImWrite(fitImageFolder + dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Millisecond.ToString() + "1.jpg"); + + } + public volatile int AllDsums = 0; + public volatile int NGDsums = 0; + public volatile int OKDsums = 0; + /// + /// ʼʶ + /// + public void ReadyDetect() + { + Task.Run(() => + { + Thread.CurrentThread.Priority = ThreadPriority.Highest; + while (true) + { + try + { + //2һ + if (IfCam2Triger) + { + + //OCRʶ + MLRequest req = new MLRequest(); + req.currentMat = Cam2ImgShowBar; + //req.currentMat = Cv2.ImRead("D:\\Hisence\\202452414231.jpg"); + MLResultModel mL = paddleOcrModelCountry.RunInferenceFixed(req); + //ݿȶ + xKNow = GetModeFromBar(mL.WashMachineBar);//ݿвѯֵ + if (xKNow.OcrBar == null) + { + myLog("δƥɹ" + IfChangeLanguage, DateTime.Now); + break; + } + if (xKNow.OcrText != "" && xKNow.Detect != "") + { + //ʱеϴ»Ǻ֮ǰһģ + if (IfChangeLanguage == mL.WashMachineBar) + { + + } + else + { + //شOCR.josn + if (File.Exists(xKNow.OcrParm)) + { + paddleOcrModel.Load(xKNow.OcrParm, "CPU"); + + IfChangeLanguage = mL.WashMachineBar; + } + + } + myLog("ͺƥɹ" + IfChangeLanguage, DateTime.Now); + bBarTriger = true; + } + + + //ݿƥſԽģƶ + //ͺźϴεͺһ Ͳûʶģll + + IfCam2Triger = false; + + } + //1ڶ + if (IfCam1TwoTriger && bBarTriger) + { + AllDsums++; + // + MLRequest req = new MLRequest(); + req.currentMat = Cam1ImgOne; + req.ResizeWidth = 640; + req.ResizeHeight = 640; + req.Score = 0.3f; + req.in_lable_path = "D:\\Hisence\\ClassName.txt";//ǩ· + req.confThreshold = 0.3f;//ģŶ + req.iouThreshold = 0.4f;//IOU + req.out_node_name = "output"; + MLResult mL = simboObjectDetection.RunInferenceFixed(req); + DateTime dt = DateTime.Now; + //еĿü ʶַԱַ + List strMatListListOne = new List(); + Mat mResultCut = req.currentMat.Clone(); + + InsertSqlRunData(ref mResultCut, mL, ref strMatListListOne, ref paddleOcrModel); + + + mL.ResultMap.Save("D://cam1//" + dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Millisecond.ToString() + "1result.jpg"); + ResultMatShow.Image = mL.ResultMap; + // + MLRequest req2 = new MLRequest(); + req2.currentMat = Cam1ImgTwo; + req2.ResizeWidth = 640; + req2.ResizeHeight = 640; + req2.Score = 0.3f; + req2.in_lable_path = "D:\\Hisence\\ClassName.txt";//ǩ· + req2.confThreshold = 0.3f;//ģŶ + req2.iouThreshold = 0.4f;//IOU + req2.out_node_name = "output"; + MLResult mL2 = simboObjectDetection.RunInferenceFixed(req2); + List strMatListListTwo = new List(); + Mat mResultCut2 = req2.currentMat.Clone(); + + InsertSqlRunData(ref mResultCut2, mL2, ref strMatListListTwo, ref paddleOcrModel); + mL2.ResultMap.Save("D://cam1//" + dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Millisecond.ToString() + "2result.jpg"); + ResultMatShow2.Image = mL2.ResultMap; + + //ִбȶ ģ23һ + string[] listLabels = xKNow.Detect.Split(","); + + MLResult MLsum = mL; + for (int i = 0; i < mL2.ResultDetails.Count; i++) + { + MLsum.ResultDetails.Add(mL2.ResultDetails[i]); + } + string[] RealLabels = new string[MLsum.ResultDetails.Count]; + string detstr = ""; + for (int i = 0; i < MLsum.ResultDetails.Count; i++) + { + RealLabels[i] = MLsum.ResultDetails[i].LabelName; + if (i < MLsum.ResultDetails.Count - 1) + { + detstr += RealLabels[i] + ","; + } + else + { + detstr += RealLabels[i]; + } + + } + IfCam1TwoTriger = false; + bBarTriger = false; + bool isMatch = false; + string OcrTextinsert = ""; + List bingji = strMatListListOne.Union(strMatListListTwo).ToList();//ȫ + for (int j = 0; j < bingji.Count; j++) + { + string jdetial = bingji[j]; + OcrTextinsert += jdetial + "##"; + } + + bool ismatch = IsMatchOcrText(xKNow.OcrBar, bingji); + + //  + //var except = listLabels.Except(RealLabels); + //Console.WriteLine("IJ:"); + //if (except.Count() == 0) + //{ + // // isMatch = true; + //} + //foreach (var num in except) + //{ + // if ((num == "2" || num == "3") && except.Count() == 1) + // { + // // isMatch = true; + // break; + // } + // else + // { + // // isMatch = false; + // break; + // } + //} + if (isMatch) + { + OKDsums++; + myLog("ƥɹ", DateTime.Now); + //ʾ + string sql = "insert into XK_HisenceDet VALUES('" + xKNow.Type + "','" + xKNow.OcrBar + "'," + xKNow.MoveX + "," + xKNow.MoveY + "," + + xKNow.MoveZ + ",'" + detstr + "','" + OcrTextinsert + "'," + xKNow.MoveTwoX + "," + xKNow.MoveTwoY + "," + xKNow.MoveTwoZ + ", '" + DateTime.Now + "'," + 1 + ")"; + SQLiteHelper.ExecuteSql(sql); + OKOrNGShow.Image = OKbitmap; + } + else + { + NGDsums++; + myLog("ƥʧ", DateTime.Now); + //ʾ + string sql = "insert into XK_HisenceDet VALUES('" + xKNow.Type + "','" + xKNow.OcrBar + "'," + xKNow.MoveX + "," + xKNow.MoveY + "," + + xKNow.MoveZ + ",'" + detstr + "','" + OcrTextinsert + "'," + xKNow.MoveTwoX + "," + xKNow.MoveTwoY + "," + xKNow.MoveTwoZ + ", '" + DateTime.Now + "'," + 0 + ")"; + SQLiteHelper.ExecuteSql(sql); + OKOrNGShow.Image = NGbitmap; + } + + } + + } + catch (Exception e) + { + + } + finally + { + + } + + + + + Thread.Sleep(10); + } + + }); + + } + /// + /// ݿлȡͺ + /// + /// + /// + public XKHisence GetModeFromBar(string SkBar) + { + //ģ + + DataSet ds = SQLiteHelper.Query($"select * from XK_Hisence where OCRBar='{SkBar}' "); + XKHisence XK_hisence = new XKHisence(); + + //cbx.DataSource = ds; + DataTableReader rdr = ds.CreateDataReader(); + //cbx.Rows.Clear(); + while (rdr.Read())//ȡ + + { + + // xKOCROfficeWord.ID = (int)rdr["ID"]; + XK_hisence.Type = (string)rdr["Type"]; + XK_hisence.OcrBar = (string)rdr["OcrBar"]; + XK_hisence.MoveX = (int)rdr["MoveX"]; + XK_hisence.MoveY = (int)rdr["MoveY"]; + XK_hisence.MoveZ = (int)rdr["MoveZ"]; + XK_hisence.Detect = (string)rdr["Detect"]; + XK_hisence.OcrText = (string)rdr["OcrText"]; + XK_hisence.MoveTwoX = (int)rdr["MoveTwoX"]; + XK_hisence.MoveTwoY = (int)rdr["MoveTwoY"]; + XK_hisence.MoveTwoZ = (int)rdr["MoveTwoZ"]; + XK_hisence.OcrParm = (string)rdr["OcrParm"]; + XK_hisence.Language = (string)rdr["Language"]; + //xKHisences.Add(XK_hisence); + return XK_hisence; + //additem(XK_hisence); + + + } + return XK_hisence; + + + } + /// + /// Ļص + /// + /// + public void OnDataReceived(byte[] data) + { + // + if (data.Length > 10) + { + m_sKEYENCEBar = System.Text.Encoding.UTF8.GetString(data); + // myLog("ͺOcr" + m_sKEYENCEBar, DateTime.Now); + + bBar = true; + } + + } + /// + /// PLCijʼ + /// + /// + /// + private void button4_Click(object sender, EventArgs e) + { + melsecPLCTCPDriver.Start(); + myLog("PLCɹ", DateTime.Now); + } + /// + /// ־ + /// + /// + /// + private void myLog(string txt, DateTime date) + { + Logtxt = txt + " ʱ䣺" + date.ToString() + "\n"; + this.Invoke(myLogDelegateUI); //richTextBox1.AppendText("TEST line \r"); + Application.DoEvents(); + } + private void readAdress_Click(object sender, EventArgs e) + { + if (Regex.IsMatch(readPLc.Text.ToString(), @"^[0-9]+$")) + { + int m_iCureent545 = melsecPLCTCPDriver.ReadInt(readPLc.Text.ToString()); + showPLC.Text = m_iCureent545.ToString(); + myLog("ȡ" + readPLc.Text.ToString() + "", DateTime.Now); + } + + } + + private void wirteAdress_Click(object sender, EventArgs e) + { + try + { + if (Regex.IsMatch(WriteAdress.Text.ToString(), @"^[0-9]+$") && Regex.IsMatch(PLCValue.Text.ToString(), @"^[0-9]+$")) + { + melsecPLCTCPDriver.WriteInt(WriteAdress.Text.ToString(), Convert.ToInt16(PLCValue.Text)); + myLog("д" + WriteAdress.Text.ToString() + "", DateTime.Now); + } + + + } + catch (Exception ex) { } + + } + + private void ScanDevList_Click(object sender, EventArgs e) + { + InitDevList(); + } + + + private void PLCPowerON_Click(object sender, EventArgs e) + { + if (bOn == true) + { + melsecPLCTCPDriver.WriteInt("500", 0); + // PLCcontrol->WritePlc(500, 0); + bOn = false; + PLCPowerON.Text = "ʹOn"; + myLog("ʹOn", DateTime.Now); + } + else + { + melsecPLCTCPDriver.WriteInt("500", 1); + bOn = true; + PLCPowerON.Text = "ʹOff"; + myLog("ʹOff", DateTime.Now); + } + } + + + bool IfPLCDiskZero = false; + bool IfPLCPostion = false; + private void PLCDiskZero_Click(object sender, EventArgs e) + { + //if (!IfPLCDiskZero) + //{ + melsecPLCTCPDriver.WriteInt("580", 0); + // + melsecPLCTCPDriver.WriteInt("580", 1); + + Thread.Sleep(200); + melsecPLCTCPDriver.WriteInt("580", 0); + IfPLCDiskZero = true; + this.txtSetValue.Text = "1"; + myLog("580ʼ", DateTime.Now); + //} + //else + //{ + // melsecPLCTCPDriver.WriteInt("580", 0); + // IfPLCDiskZero = false; + // this.txtSetValue.Text = "0"; + // myLog("580ֹͣ", DateTime.Now); + //} + } + + private void PLCPostion_Click(object sender, EventArgs e) + { + //if (!IfPLCPostion) + //{ + + + + try + { + if (Regex.IsMatch(lnEditmiXOP.Text.ToString(), @"^[0-9]+$") && Regex.IsMatch(lnEditmiYOP.Text.ToString(), @"^[0-9]+$") && Regex.IsMatch(lnEditmiZOP.Text.ToString(), @"^[0-9]+$")) + { + if (lnEditmiXOP.Text != "" && lnEditmiYOP.Text != "" && lnEditmiZOP.Text != "") + { + //ͨȡ༭ֵ ΪĿλ + int iXTPosition = Convert.ToInt16(lnEditmiXOP.Text); //λXλ + int iYTPosition = Convert.ToInt16(lnEditmiYOP.Text); + int iZTPosition = Convert.ToInt16(lnEditmiZOP.Text); + + //Ҫλλд + melsecPLCTCPDriver.WriteInt("402", iXTPosition); + melsecPLCTCPDriver.WriteInt("412", iYTPosition); + melsecPLCTCPDriver.WriteInt("422", iZTPosition); + + string logs = "д붨λλ X" + iXTPosition + "Y:" + iYTPosition + "Z:" + iZTPosition + " "; + myLog(logs, DateTime.Now); + } + } + + + + melsecPLCTCPDriver.WriteInt("581", 1); + Thread.Sleep(1000); + melsecPLCTCPDriver.WriteInt("581", 0); + IfPLCPostion = true; + this.txtSetValue.Text = "1"; + myLog("XYZʼλ581", DateTime.Now); + } + catch (Exception ex) + { + + } + + + + + //} + //else + //{ + // melsecPLCTCPDriver.WriteInt("581", 0); + // IfPLCPostion = false; + // this.txtSetValue.Text = "0"; + // myLog("XYZֹͣ581", DateTime.Now); + //} + } + + + + private void StartDecBtn_Click(object sender, EventArgs e) + { + //OnGetBar(); + TriggerCameral2(); + ReadyDetect(); + myLog("̳ɹ", DateTime.Now); + } + + private void InsertSqlBtn_Click(object sender, EventArgs e) + { + InsertSqlFrm insertSqlFrm = new InsertSqlFrm(); + // insertSqlFrm. + //insertSqlFrm.Parent = this; + insertSqlFrm.ShowDialog(); + } + + private void RefeshData_Click(object sender, EventArgs e) + { + DataSet dataSet = SQLiteHelper.Query("select * from XK_HisenceDet"); + dataGridView1.DataSource = dataSet.Tables[0]; + } + + private void panel8_Paint(object sender, PaintEventArgs e) + { + + } + + private void SetHandleSpeed_Click(object sender, EventArgs e) + { + if (Regex.IsMatch(lnEditmiXHS.Text.ToString(), @"^[0-9]+$") && Regex.IsMatch(lnEditmiYHS.Text.ToString(), @"^[0-9]+$") && Regex.IsMatch(lnEditmiZHS.Text.ToString(), @"^[0-9]+$")) + { + if (SetlnEditmiXH.Text != "" && SetlnEditmiYH.Text != "" && SetlnEditmiZH.Text != "") + { + int XHspeed = Convert.ToInt32(SetlnEditmiXH.Text); //Xֶٶ + int YHspeed = Convert.ToInt32(SetlnEditmiYH.Text); //Yֶٶ + int ZHspeed = Convert.ToInt32(SetlnEditmiZH.Text); //Zֶٶ + + melsecPLCTCPDriver.WriteInt("406", XHspeed); //дֶٶ + melsecPLCTCPDriver.WriteInt("416", YHspeed); + melsecPLCTCPDriver.WriteInt("426", ZHspeed); + string logs = "дֶٶ X" + XHspeed + "Y:" + YHspeed + "Z:" + ZHspeed + " "; + myLog(logs, DateTime.Now); + } + + + } + } + + private void SetAutoSpeed_Click(object sender, EventArgs e) + { + if (Regex.IsMatch(lnEditmiXS.Text.ToString(), @"^[0-9]+$") && Regex.IsMatch(lnEditmiYS.Text.ToString(), @"^[0-9]+$") && Regex.IsMatch(lnEditmiZS.Text.ToString(), @"^[0-9]+$")) + { + if (SetlnEditmiXOP.Text != "" && SetlnEditmiYOP.Text != "" && SetlnEditmiZOP.Text != "") + { + int Xspeed = Convert.ToInt32(SetlnEditmiXOP.Text); //Xᶨλٶ + int Yspeed = Convert.ToInt32(SetlnEditmiYOP.Text); //Yᶨλٶ + int Zspeed = Convert.ToInt32(SetlnEditmiZOP.Text); //Zᶨλٶ + + melsecPLCTCPDriver.WriteInt("404", Xspeed); //д붨λٶ + melsecPLCTCPDriver.WriteInt("414", Yspeed); + melsecPLCTCPDriver.WriteInt("424", Zspeed); + + string logs = "д붨λٶ X" + Xspeed + "Y:" + Yspeed + "Z:" + Zspeed + " "; + myLog(logs, DateTime.Now); + } + } + } + //״̬ʶ + private bool m_btnState; + private void radioButton1_Click(object sender, EventArgs e) + { + + if (!ifXZeroValue) + { + this.XZerorbx.Checked = true; + // + melsecPLCTCPDriver.WriteInt("503", 1); + ifXZeroValue = true; + this.txtSetValue.Text = "1"; + myLog("XῪʼ", DateTime.Now); + } + else + { + this.XZerorbx.Checked = false; + melsecPLCTCPDriver.WriteInt("503", 0); + ifXZeroValue = false; + this.txtSetValue.Text = "0"; + myLog("Xֹͣ", DateTime.Now); + } + } + + private void YZerorbx_Click(object sender, EventArgs e) + { + if (!ifYZeroValue) + { + this.YZerorbx.Checked = true; + // + melsecPLCTCPDriver.WriteInt("513", 1); + ifYZeroValue = true; + this.txtSetValue.Text = "1"; + myLog("YῪʼ", DateTime.Now); + } + else + { + this.YZerorbx.Checked = false; + melsecPLCTCPDriver.WriteInt("513", 0); + ifYZeroValue = false; + this.txtSetValue.Text = "0"; + myLog("Yֹͣ", DateTime.Now); + } + } + + private void ZZerorbx_Click(object sender, EventArgs e) + { + if (!ifZZeroValue) + { + this.ZZerorbx.Checked = true; + // + melsecPLCTCPDriver.WriteInt("523", 1); + ifZZeroValue = true; + this.txtSetValue.Text = "1"; + myLog("ZῪʼ", DateTime.Now); + } + else + { + this.ZZerorbx.Checked = false; + melsecPLCTCPDriver.WriteInt("523", 0); + ifZZeroValue = false; + this.txtSetValue.Text = "0"; + myLog("Zֹͣ", DateTime.Now); + } + } + + private void XForwardrbx_Click(object sender, EventArgs e) + { + if (!ifXForward) + { + this.XForwardrbx.Checked = true; + // + melsecPLCTCPDriver.WriteInt("502", 1); + ifXForward = true; + this.txtSetValue.Text = "1"; + myLog("XῪʼ", DateTime.Now); + } + else + { + this.XForwardrbx.Checked = false; + melsecPLCTCPDriver.WriteInt("502", 0); + ifXForward = false; + this.txtSetValue.Text = "0"; + myLog("Xֹͣ", DateTime.Now); + } + } + + private void YForwardrbx_Click(object sender, EventArgs e) + { + if (!ifYForward) + { + this.YForwardrbx.Checked = true; + // + melsecPLCTCPDriver.WriteInt("512", 1); + ifYForward = true; + this.txtSetValue.Text = "1"; + myLog("YῪʼ", DateTime.Now); + } + else + { + this.YForwardrbx.Checked = false; + melsecPLCTCPDriver.WriteInt("512", 0); + ifYForward = false; + this.txtSetValue.Text = "0"; + myLog("Yֹͣ", DateTime.Now); + } + } + + private void ZForwardrbx_Click(object sender, EventArgs e) + { + if (!ifZForward) + { + this.ZForwardrbx.Checked = true; + // + melsecPLCTCPDriver.WriteInt("522", 1); + ifZForward = true; + this.txtSetValue.Text = "1"; + myLog("ZῪʼ", DateTime.Now); + } + else + { + this.ZForwardrbx.Checked = false; + melsecPLCTCPDriver.WriteInt("522", 0); + ifZForward = false; + this.txtSetValue.Text = "0"; + myLog("Zֹͣ", DateTime.Now); + } + } + + private void XBackwardrbx_Click(object sender, EventArgs e) + { + if (!ifXBackward) + { + this.XBackwardrbx.Checked = true; + // + melsecPLCTCPDriver.WriteInt("501", 1); + ifXBackward = true; + this.txtSetValue.Text = "1"; + myLog("XῪʼ", DateTime.Now); + } + else + { + this.XBackwardrbx.Checked = false; + melsecPLCTCPDriver.WriteInt("501", 0); + ifXBackward = false; + this.txtSetValue.Text = "0"; + myLog("Xֹͣ", DateTime.Now); + } + } + + private void YBackwardrbx_Click(object sender, EventArgs e) + { + if (!ifYBackward) + { + this.YBackwardrbx.Checked = true; + // + melsecPLCTCPDriver.WriteInt("511", 1); + ifYBackward = true; + this.txtSetValue.Text = "1"; + myLog("YῪʼ", DateTime.Now); + } + else + { + this.YBackwardrbx.Checked = false; + melsecPLCTCPDriver.WriteInt("511", 0); + ifYBackward = false; + this.txtSetValue.Text = "0"; + myLog("Yֹͣ", DateTime.Now); + } + } + + private void ZBackwardrbx_Click(object sender, EventArgs e) + { + if (!ifZBackward) + { + this.ZBackwardrbx.Checked = true; + // + melsecPLCTCPDriver.WriteInt("521", 1); + ifZBackward = true; + this.txtSetValue.Text = "1"; + myLog("ZῪʼ", DateTime.Now); + } + else + { + this.ZBackwardrbx.Checked = false; + melsecPLCTCPDriver.WriteInt("521", 0); + ifZBackward = false; + this.txtSetValue.Text = "0"; + myLog("Zֹͣ", DateTime.Now); + } + } + + private void button1_Click(object sender, EventArgs e) + { + string ss = "BB0VA5E0000BCQ5L0114"; + + } + + private void Cam2OpenBtn_Click_1(object sender, EventArgs e) + { + + Cam2.Start("Cam2"); + + bnGetParam2.Enabled = true; + //SetCtrlWhenOpen(); + Cam2OpenBtn.BackColor = Color.Green; + } + + private void button4_Click_1(object sender, EventArgs e) + { + OpenFileDialog openFileDialog = new OpenFileDialog(); + openFileDialog.Title = "ͼƬ"; + + + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + string fName = openFileDialog.FileName; + //File fileOpen = new File(fName); + //isFileHaveName = true; + //richTextBox1.Text = fileOpen.ReadFile(); + //richTextBox1.AppendText(""); + DetectBArMatbox.Text = fName; + BarPath = fName; + } + } + + private void InsertBtn_Click(object sender, EventArgs e) + { + try + { + string type = TypeBox.Text; + string OcrBar = OcrBarBox.Text; + string moveX = moveXbox.Text; + string moveY = moveYbox.Text; + string moveZ = moveZbox.Text; + string Detect = DetectBArMatbox.Text; + string movetwoX = moveTwoXbox.Text; + string movetwoY = moveTwoYbox.Text; + string movetwoZ = moveTwoZbox.Text; + + if (!Regex.IsMatch(moveX, @"^[0-9]+$")) + { + MessageBox.Show("һƶXֻ"); + return; + } + if (!Regex.IsMatch(moveY, @"^[0-9]+$")) + { + MessageBox.Show("һƶYֻ"); + return; + } + if (!Regex.IsMatch(moveZ, @"^[0-9]+$")) + { + MessageBox.Show("һƶZֻ"); + return; + } + if (!Regex.IsMatch(movetwoX, @"^[0-9]+$")) + { + MessageBox.Show("ڶƶXֻ"); + return; + } + if (!Regex.IsMatch(movetwoY, @"^[0-9]+$")) + { + MessageBox.Show("ڶƶYֻ"); + return; + } + if (!Regex.IsMatch(movetwoZ, @"^[0-9]+$")) + { + MessageBox.Show("ڶƶZֻ"); + return; + } + + if (OcrBar != "" && Detect != "" && BarPath != "" && Cam1OnePath != "" && Cam1TwoPath != "" && ModelChangePath != "") + { + int HmoveX = (int)Convert.ToInt64(moveX); + int HmoveY = (int)Convert.ToInt64(moveY); + int HmoveZ = (int)Convert.ToInt64(moveZ); + int HmovetwoX = (int)Convert.ToInt64(movetwoX); + int HmovetwoY = (int)Convert.ToInt64(movetwoY); + int HmovetwoZ = (int)Convert.ToInt64(movetwoZ); + InsertXK_Hisence(HmoveX, HmoveY, HmoveZ, HmovetwoX, HmovetwoY, HmovetwoZ); + + + } + else + { + MessageBox.Show("ݲΪNULL"); + } + + } + catch (Exception es) + { + } + } + public void InsertXK_Hisence(int MoveX, int MoveY, int MoveZ, int MoveTwoX, int MoveTwoY, int MoveTwoZ) + { + PaddleOcrModel IpaddleOcrModel = new PaddleOcrModel(); + IpaddleOcrModel.Load(ModelChangePath, "CPU"); + MLRequest OcrBari = new MLRequest(); + OcrBari.currentMat = Cv2.ImRead(BarPath); + MLResultModel mL2 = IpaddleOcrModel.RunInferenceFixed(OcrBari); + string IOcrBAr = ""; + for (int v = 0; v < mL2.ResultDetails.Count(); v++) + { + string iv = mL2.ResultDetails[v].LabelDisplay; + IOcrBAr += iv; + } + using (StreamWriter sw = new StreamWriter("D://123.log", true)) + { + sw.WriteLine("\n"); + sw.WriteLine(IOcrBAr); + sw.Flush(); + } + MLRequest CamOneI = new MLRequest(); + CamOneI.currentMat = Cv2.ImRead(Cam1OnePath); + CamOneI.ResizeWidth = 640; + CamOneI.ResizeHeight = 640; + CamOneI.Score = 0.3f; + CamOneI.in_lable_path = "D:\\Hisence\\ClassName.txt";//ǩ· + CamOneI.confThreshold = 0.3f;//ģŶ + CamOneI.iouThreshold = 0.4f;//IOU + CamOneI.out_node_name = "output"; + MLResult mL3 = simboObjectDetection.RunInferenceFixed(CamOneI); + if (mL3.IsSuccess) + { + DateTime dt = DateTime.Now; + mL3.ResultMap.Save("D:\\Hisence\\detImages\\" + dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Millisecond.ToString() + "1result.jpg"); + + } + List strMatListListOne = new List(); + Mat mResultCut = CamOneI.currentMat.Clone(); + + InsertSqlRunData(ref mResultCut, mL3, ref strMatListListOne, ref IpaddleOcrModel); + + MLRequest CamTwoI = new MLRequest(); + CamTwoI.currentMat = Cv2.ImRead(Cam1TwoPath); + CamTwoI.ResizeWidth = 640; + CamTwoI.ResizeHeight = 640; + CamTwoI.Score = 0.3f; + CamTwoI.in_lable_path = "D:\\Hisence\\ClassName.txt";//ǩ· + CamTwoI.confThreshold = 0.3f;//ģŶ + CamTwoI.iouThreshold = 0.4f;//IOU + CamTwoI.out_node_name = "output"; + MLResult mL4 = simboObjectDetection.RunInferenceFixed(CamTwoI); + if (mL4.IsSuccess) + { + DateTime dt = DateTime.Now; + mL4.ResultMap.Save("D:\\Hisence\\detImages\\" + dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Millisecond.ToString() + "2result.jpg"); + + } + + + List strMatListListTwo = new List(); + Mat mResultCut2 = CamTwoI.currentMat.Clone(); + + InsertSqlRunData(ref mResultCut2, mL4, ref strMatListListTwo, ref IpaddleOcrModel); + //ı + string OcrTextinsert = ""; + List bingji = strMatListListOne.Union(strMatListListTwo).ToList();//ȫ + for (int j = 0; j < bingji.Count; j++) + { + string jdetial = bingji[j]; + OcrTextinsert += jdetial + "##"; + } + string detstr = ""; + + //ҵʶ + MLResult MLsum = mL3; + for (int v = 0; v < mL4.ResultDetails.Count; v++) + { + MLsum.ResultDetails.Add(mL4.ResultDetails[v]); + } + for (int v = 0; v < MLsum.ResultDetails.Count; v++) + { + + if (v < MLsum.ResultDetails.Count - 1) + { + detstr += MLsum.ResultDetails[v].LabelName + ","; + } + else + { + detstr += MLsum.ResultDetails[v].LabelName ; + + } + + } + + + XKHisence xK = new XKHisence("1", IOcrBAr, MoveX, MoveY, MoveZ, detstr, OcrTextinsert, MoveTwoX, MoveTwoY, MoveTwoZ, ModelChangePath, ""); + + + //IpaddleOcrModel.FreeModel(); + + string sql = "insert into XK_Hisence VALUES('" + xK.Type + "','" + xK.OcrBar + "'," + xK.MoveX + "," + xK.MoveY + "," + xK.MoveZ + ",'" + xK.Detect + "','" + xK.OcrText + "'," + xK.MoveTwoX + "," + xK.MoveTwoY + "," + xK.MoveTwoZ + ",'" + xK.OcrParm + "','" + xK.Language + "')"; + int i = SQLiteHelper.ExecuteSql(sql); + if (i == 1) + { + MessageBox.Show("һ"); + } + //bool ismatch = IsMatchOcrText("WF3S7021BB", strMatListListOne); + //ص + } + private void queryALLBtn_Click(object sender, EventArgs e) + { + try + { + DataSet dataSet = SQLiteHelper.Query("select * from XK_Hisence"); + InsertDataDgv.DataSource = dataSet.Tables[0]; + + + } + catch (Exception es) + { + } + } + + private void QueryoneBtn_Click(object sender, EventArgs e) + { + try + { + string type = TypeBox.Text; + string OcrBar = OcrBarBox.Text; + string moveX = moveXbox.Text; + string moveY = moveYbox.Text; + string moveZ = moveZbox.Text; + string Detect = DetectBArMatbox.Text; + string movetwoX = moveTwoXbox.Text; + string movetwoY = moveTwoYbox.Text; + string movetwoZ = moveTwoZbox.Text; + + + string sql = "select * from XK_Hisence where type='" + type + "' or OcrBar='" + OcrBar + "'"; + DataSet dataSet = SQLiteHelper.Query(sql); + InsertDataDgv.DataSource = dataSet.Tables[0]; + + } + catch (Exception es) + { + } + } + + private void OpenDirBtn_Click(object sender, EventArgs e) + { + OpenFileDialog openFileDialog = new OpenFileDialog(); + openFileDialog.Title = "ͼƬ"; + + + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + string fName = openFileDialog.FileName; + //File fileOpen = new File(fName); + //isFileHaveName = true; + //richTextBox1.Text = fileOpen.ReadFile(); + //richTextBox1.AppendText(""); + Cam1MatCbx.Text = fName; + Cam1OnePath = fName; + } + } + + private void OpenTwoDirBtn_Click(object sender, EventArgs e) + { + OpenFileDialog openFileDialog = new OpenFileDialog(); + openFileDialog.Title = "ͼƬ"; + + + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + string fName = openFileDialog.FileName; + //File fileOpen = new File(fName); + //isFileHaveName = true; + //richTextBox1.Text = fileOpen.ReadFile(); + //richTextBox1.AppendText(""); + Cam2MatCbx.Text = fName; + Cam1TwoPath = fName; + } + } + + private void openModelBtn_Click(object sender, EventArgs e) + { + OpenFileDialog openFileDialog = new OpenFileDialog(); + openFileDialog.Title = "json"; + + + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + string fName = openFileDialog.FileName; + //File fileOpen = new File(fName); + //isFileHaveName = true; + //richTextBox1.Text = fileOpen.ReadFile(); + //richTextBox1.AppendText(""); + modelChangeCbx.Text = fName; + ModelChangePath = fName; + } + } + + private void SnapshotCam2_Click_1(object sender, EventArgs e) + { + Cam2.Snapshot(); + } + + private void bnGetParam2_Click_1(object sender, EventArgs e) + { + tbExposure2.Text = Cam2.dvpGetExposure().ToString(); + tbGain2.Text = Cam2.dvpGetAnalogGain().ToString(); + } + } +} diff --git a/HisenceYoloDetection/MainForm.resx b/HisenceYoloDetection/MainForm.resx new file mode 100644 index 0000000..40dc29b --- /dev/null +++ b/HisenceYoloDetection/MainForm.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + 109, 17 + + + 201, 17 + + + 293, 17 + + + 385, 17 + + + 477, 17 + + + 569, 17 + + + 733, 17 + + + 28 + + \ No newline at end of file diff --git a/HisenceYoloDetection/MelsecPLCTCPDriver.cs b/HisenceYoloDetection/MelsecPLCTCPDriver.cs new file mode 100644 index 0000000..ad6e1bf --- /dev/null +++ b/HisenceYoloDetection/MelsecPLCTCPDriver.cs @@ -0,0 +1,358 @@ + +using HslCommunication; +using HslCommunication.Profinet.Melsec; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; +using System.Xml.Linq; +using static OpenCvSharp.FileStorage; + + + +public class MelsecPLCTCPDriver +{ + private MelsecMcNet melsecMc = new MelsecMcNet(); + // private HslCommunication.ModBus.ModbusTcpNet melsecMc = new HslCommunication.ModBus.ModbusTcpNet(); + //HslCommunication.Profinet.Melsec.MelsecMcServer melsecMc = new HslCommunication.Profinet.Melsec.MelsecMcServer(); + + #region PLCBase + public List Read(string startAddress, int length) + { + PLCItem item = new PLCItem(); + item.Address = startAddress; + item.ItemLength = length; + + ReadItem(item); + //List valueList = new List(); + //if (!string.IsNullOrWhiteSpace(item.ItemValue)) + //{ + // valueList = item.ItemValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList().ConvertAll(s => int.Parse(s)).ToList(); + //} + return item.ItemValues; + } + + public void ReadItem(PLCItem item) + { + // item.PLCOpType = PLCOpType.Read; + item.ItemValues.Clear(); + try + { + // 读取Int变量 + var result = melsecMc.ReadInt32("D"+item.Address, (ushort)item.ItemLength); + if (result.IsSuccess) + { + for (int i = 0; i < result.Content.Length; i++) + { + item.ItemValues.Add(result.Content[i]); + } + } + else + { + // LogAsync(DateTime.Now, LogLevel.Error, $"{Name}未读取到数据:" + "地址:" + item.Address + ";长度:" + item.ItemLength + ";提示:" + result.Message); + } + } + catch (Exception ex) + { + // LogAsync(DateTime.Now, LogLevel.Exception, $"{Name}读取异常:" + ex.GetExceptionMessage()); + } + } + + + public int ReadInt(string address) + { + try + { + // 读取Int变量 + var result = melsecMc.ReadInt32("D"+address); + if (result.IsSuccess) + { + return result.Content; + } + else + { + // LogAsync(DateTime.Now, LogLevel.Error, $"{Name}未读取到数据:" + "地址:" + address + ";提示:" + result.Message); + return -1; + } + } + catch (Exception ex) + { + // LogAsync(DateTime.Now, LogLevel.Exception, $"{Name}读取异常:" + ex.GetExceptionMessage()); + return -1; + } + } + + public void WriteItem(PLCItem item, bool waitForReply = true) + { + item.PLCOpType = PLCOpType.Write; + + if (item.ItemValues == null || item.ItemValues.Count < 1) + { + // LogAsync(DateTime.Now, LogLevel.Error, $"{Name} 数据写入值不能为空"); + return; + } + + int repeatTime = 3; + Stopwatch sw = new Stopwatch(); + + do + { + try + { + var result = melsecMc.Write(item.Address, item.ItemValues.First()); + if (result.IsSuccess) + { + repeatTime = 0; + } + } + catch (Exception ex) + { + if (repeatTime < 0) + { + //LogAsync(DateTime.Now, LogLevel.Exception, $"{Name}数据写入异常:{ex.GetExceptionMessage()}"); + } + } + } while (repeatTime > 0); + sw.Stop(); + // LogAsync(DateTime.Now, LogLevel.Assist, $"{Name} WriteItem:{item.GetDisplayText()},写入 {item.ItemValues.First()}完成,耗时:{sw.ElapsedMilliseconds} ms"); + } + + /// + /// 写单独地址 + /// + /// 地址 + /// + /// + public void WriteInt(string address, int writeValue, bool waitForReply = true) + { + if (string.IsNullOrEmpty(address)) + { + // LogAsync(DateTime.Now, LogLevel.Error, $"{Name} 数据写入参数不能为空!"); + return; + } + + int repeatTime = 3; + Stopwatch sw = new Stopwatch(); + + do + { + try + { + + var result = melsecMc.Write("D"+address, writeValue); + if (result.IsSuccess) + { + repeatTime = 0; + } + } + catch (Exception ex) + { + if (repeatTime < 0) + { + // LogAsync(DateTime.Now, LogLevel.Exception, $"{Name}数据写入异常:{ex.GetExceptionMessage()}"); + } + } + } while (repeatTime > 0); + sw.Stop(); + // LogAsync(DateTime.Now, LogLevel.Assist, $"{Name} {address},写入 {writeValue} 完成,耗时:{sw.ElapsedMilliseconds} ms"); + } + /// + /// 写单独地址 string值 + /// + /// 地址 + /// + /// + public void WriteString(string address, string writeValue, bool waitForReply = true) + { + if (string.IsNullOrEmpty(address) || string.IsNullOrEmpty(writeValue)) + { + // LogAsync(DateTime.Now, LogLevel.Error, $"{Name} 数据写入参数不能为空!"); + return; + } + + int repeatTime = 3; + Stopwatch sw = new Stopwatch(); + + do + { + try + { + var result = melsecMc.Write(address, writeValue); + if (result.IsSuccess) + { + repeatTime = 0; + } + } + catch (Exception ex) + { + if (repeatTime < 0) + { + // LogAsync(DateTime.Now, LogLevel.Exception, $"{Name}数据写入异常:{ex.GetExceptionMessage()}"); + } + } + } while (repeatTime > 0); + sw.Stop(); + // LogAsync(DateTime.Now, LogLevel.Assist, $"{Name} {address},写入{writeValue}完成,耗时:{sw.ElapsedMilliseconds} ms"); + } + + /// + /// 写单独地址 float值 + /// + /// 地址 + /// + /// + public void WriteFloat(string address, float writeValue, bool waitForReply = true) + { + if (string.IsNullOrEmpty(address)) + { + //LogAsync(DateTime.Now, LogLevel.Error, $"{Name} 数据写入参数不能为空!"); + return; + } + + int repeatTime = 3; + Stopwatch sw = new Stopwatch(); + + do + { + try + { + var result = melsecMc.Write(address, writeValue); + if (result.IsSuccess) + { + repeatTime = 0; + } + } + catch (Exception ex) + { + if (repeatTime < 0) + { + // LogAsync(DateTime.Now, LogLevel.Exception, $"{Name}数据写入异常:{ex.GetExceptionMessage()}"); + } + } + } while (repeatTime > 0); + sw.Stop(); + // LogAsync(DateTime.Now, LogLevel.Assist, $"{Name} {address},写入{writeValue}完成,耗时:{sw.ElapsedMilliseconds} ms"); + } + #endregion + + #region DeviceBase + + public void Start() + { + // IConfig.ip + + melsecMc = new MelsecMcNet( "192.168.3.39", 502); + + // 如果网络不太理想,配置了两个端口,一个有问题,立即切换另一个的话,可以配置如下的代码 + // melsecMc.GetPipeSocket().SetMultiPorts(new int[] { 6000, 6001 }); + //melsecMc = new HslCommunication.ModBus.ModbusTcpNet(); + //melsecMc.IpAddress = "192.168.3.39"; + //melsecMc.Port = 502; + //melsecMc.ConnectTimeOut = 10000; // 连接超时,单位毫秒 + //melsecMc.ReceiveTimeOut = 5000; // 接收超时,单位毫秒 + //melsecMc.Station = 1; + //melsecMc.AddressStartWithZero = true; + //melsecMc.IsStringReverse = false; + //melsecMc.DataFormat = HslCommunication.Core.DataFormat.CDAB; + + + // melsecMc.ServerStart(6000); + // 连接对象 + OperateResult connect = melsecMc.ConnectServer(); + if (connect.IsSuccess) + { + + Task.Run(() => + { + HeartbeatMonitor(); + }); + } + else + { + // LogAsync(DateTime.Now, LogLevel.Exception, $"{Name}已开启异常:{connect.Message}"); + } + } + + protected void Stop() + { + try + { + + // 断开连接 + // melsecMc.RemoteStop(); + // OmronUDPNet.Stop(); + } + catch (Exception ex) + { + // LogAsync(DateTime.Now, LogLevel.Exception, $"{Name}关闭异常:{ex.GetExceptionMessage()}"); + } + } + #endregion + + + + + #region IMonitor + readonly byte[] scanBuffer = new byte[2048]; + + public List GetMonitorValues(int startAddress, int length) + { + List res = new List(); + // var result = melsecMc.ReadUInt16(startAddress.ToString(), (ushort)length); + // var result = melsecMc.ReadInt32("D" + startAddress, (ushort)length); + var result = melsecMc.ReadInt32("D" + startAddress, (ushort)length); + if (result.IsSuccess) + { + res = new List(result.Content); + } + else + { + //LogAsync(DateTime.Now, LogLevel.Error, $"{Name}未读取到数据:" + "地址:W" + startAddress + ";长度:" + length + ";提示:" + result.Message); + } + return res; + } + #endregion + + int HeartbeatCycle = 2; + string HeartbeatAddress = "D800"; + bool CurrentState = false; + public event Action Heartbeat; + public async void HeartbeatMonitor() + { + if (HeartbeatCycle <= 0) + { + return; + } + await Task.Run(async () => + { + if (!string.IsNullOrEmpty(HeartbeatAddress) + && HeartbeatCycle > 0) + { + while (CurrentState != false) + { + if (HeartbeatCycle <= 0) + { + return; + } + + try + { + await Task.Delay(HeartbeatCycle * 1000); + var result = melsecMc.Write(HeartbeatAddress, 1); + if (!result.IsSuccess) + { + Heartbeat?.Invoke(1); + //LogAsync(DateTime.Now, LogLevel.Error, $"{this.Name} 心跳监听失败"); + } + } + catch (Exception ex) + { + + } + } + } + }); + } +} + diff --git a/HisenceYoloDetection/PLCItem.cs b/HisenceYoloDetection/PLCItem.cs new file mode 100644 index 0000000..a7a2aca --- /dev/null +++ b/HisenceYoloDetection/PLCItem.cs @@ -0,0 +1,53 @@ + +using System; +using System.Collections.Generic; +using System.ComponentModel; + +public enum PLCOpType +{ + [Description("读取")] + Read = 1, + [Description("写入")] + Write = 2, + [Description("监控")] + Monitor = 4, + + /// + /// 报警监控 1+8 + /// + [Description("报警监控")] + WarningMonitor = 9, + + /// + /// CT监控 1+16 + /// + [Description("CT监控")] + CTMonitor = 17, +} +public class PLCItem + { + /// + /// 读写地址 + /// + public string Address { get; set; } = ""; + + /// + /// 读写地址长度 + /// + public int ItemLength { get; set; } = 1; + + /// + /// PLC项目值 + /// + public List ItemValues { get; set; } = new List(); + + /// + /// 是否写数据 1:读数据 2:写数据 4:监控 参见枚举PLCOpType + /// + public PLCOpType PLCOpType { get; set; } = PLCOpType.Read; + + public DateTime OpTimeStamp { get; set; } = DateTime.Now; + + + } + diff --git a/HisenceYoloDetection/PaddleOcrModel.cs b/HisenceYoloDetection/PaddleOcrModel.cs new file mode 100644 index 0000000..73a3551 --- /dev/null +++ b/HisenceYoloDetection/PaddleOcrModel.cs @@ -0,0 +1,286 @@ + +using Newtonsoft.Json; + +using OpenCvSharp; +using OpenCvSharp.Extensions; +using PaddleOCRSharp; +using STTech.BytesIO.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +using static System.Net.Mime.MediaTypeNames; + +using Point = OpenCvSharp.Point; + +namespace XKRS.Device.SimboVision.SimboHelper +{ + public class SegResult + { + public List SegmentResult; + public class Result + { + + public double fScore; + public int classId; + public string classname; + + public double area; + public List> rect; + + + } + + + } + + + + public class PaddleOcrModel + { + IntPtr Model; + public bool Load(string ModelFile,string Device) + { + bool res = false; + try + { + + + Model = OcrEngine.InitModel(ModelFile, Device); + res = true; + +#if USE_MULTI_THREAD + + IsCreated = true; + if (IsCreated) + { + if (_runHandleBefore == null) + { + _runHandleBefore = new AutoResetEvent(false); + } + + if (_runHandleAfter == null) + { + _runHandleAfter = new ManualResetEvent(false); + } + + if (_runTask == null) + { + _runTask = Task.Factory.StartNew(() => + { + while (IsCreated) + { + _runHandleBefore.WaitOne(); + + if (IsCreated) + { + _result = RunInferenceFixed(_req); + _runHandleAfter.Set(); + } + } + }, TaskCreationOptions.LongRunning); + } + } +#endif + } + catch (Exception ex) + { + throw ex; + } + return res; + } + + + +#if USE_MULTI_THREAD + MLRequest _req = null; + MLResult _result = null; + + + public bool IsCreated { get; set; } = false; + Task _runTask = null; + AutoResetEvent _runHandleBefore = new AutoResetEvent(false); + ManualResetEvent _runHandleAfter = new ManualResetEvent(false); + object _runLock = new object(); +#endif + + [HandleProcessCorruptedStateExceptions] + public MLResultModel RunInference(MLRequest req) + { +#if USE_MULTI_THREAD + MLResult mlResult = null; + lock (_runLock) + { + _result = new MLResult(); + + _req = req; + + _runHandleAfter.Reset(); + _runHandleBefore.Set(); + _runHandleAfter.WaitOne(); + + mlResult = _result; + } + + return mlResult; +#else + return RunInferenceFixed(req); +#endif + + + + + } + + + private void ConvertJsonResult(string json, ref MLResultModel result) + { + // json = "{\"FastDetResult\":[{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.654843,\"rect\":[175,99,110,594]},{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.654589,\"rect\":[2608,19,104,661]},{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.654285,\"rect\":[1275,19,104,662]},{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.620762,\"rect\":[1510,95,107,600]},{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.617812,\"rect\":[2844,93,106,602]}]}"; + // + Console.WriteLine("检测结果JSON:" + json); + SegResult detResult = JsonConvert.DeserializeObject(json); + if (detResult == null) + { + return; + } + + int iNum = detResult.SegmentResult.Count; + int IokNum = 0; + for (int ix = 0; ix < iNum; ix++) + { + var det = detResult.SegmentResult[ix]; + + var rect = det.rect; + List points = new List(); + List maxYs = new List(); + //把字体打印在矩形框的下面,考虑矩形框最靠下的角点Y值不能超过边框值 否则就往上写 + for (int n = 0; n < det.rect.Count(); n++) + { + points.Add(new Point(det.rect[n][0], det.rect[n][1])); + maxYs.Add(det.rect[n][1]); + } + // 定义矩形左上角和右下角的坐标 + Point topLeft = points[0]; + Point bottomRight = points[2]; + + // 计算矩形的长和宽 + int width = bottomRight.X - topLeft.X;//矩形宽度 + int height = bottomRight.Y - topLeft.Y;//矩形高度 + //下面定义一个矩形区域,以后在这个矩形里画上白底黑字 + float rectX = points[0].X; + float rectY = points[0].Y; + float rectWidth = width; + float rectHeight = height; + if(det.classname!="") + { + DetectionResultDetail detectionResultDetail = new DetectionResultDetail(); + detectionResultDetail.LabelNo = det.classId; + //todo: 标签名相对应 + detectionResultDetail.LabelDisplay = det.classname; + detectionResultDetail.Rect = new Rectangle(rectX.ToInt(), rectY.ToInt(), rectWidth.ToInt(), rectHeight.ToInt()); + detectionResultDetail.Score = det.fScore; + detectionResultDetail.LabelName = det.classname; + detectionResultDetail.Area = det.area; + result.ResultDetails.Add(detectionResultDetail); + } + + + } + + } + + + + + [HandleProcessCorruptedStateExceptions] + public MLResultModel RunInferenceFixed(MLRequest req) + { + MLResultModel mlResult = new MLResultModel(); + Mat originMat = new Mat(); + + try + { + originMat = req.currentMat;//1ms + + int iWidth = originMat.Cols; + int iHeight = originMat.Rows; + + //输入数据转化为字节 + var inputByte = new byte[originMat.Total() * 3];//这里必须乘以通道数,不然数组越界,也可以用w*h*c,差不多 + Marshal.Copy(originMat.Data, inputByte, 0, inputByte.Length); + + byte[] labellist = new byte[20480]; //新建字节数组:label1_str label2_str + + byte[] outputByte = new byte[originMat.Total() * 3]; + + Stopwatch sw = new Stopwatch(); + sw.Start(); + unsafe + { + mlResult.IsSuccess = OcrEngine.Inference(Model, inputByte, iWidth, iHeight, 3, ref outputByte[0], ref labellist[0]); + + } + sw.Stop(); + + if (mlResult.IsSuccess) + { + mlResult.ResultMessage = $"深度学习推理成功,耗时:{sw.ElapsedMilliseconds} ms"; + + Mat maskWeighted = new Mat(iHeight, iWidth, MatType.CV_8UC3, outputByte); + + mlResult.ResultMap = BitmapConverter.ToBitmap(maskWeighted);//4ms + + //将字节数组转换为字符串 + mlResult.ResultMap = originMat.ToBitmap();//4ms + string strGet = System.Text.Encoding.Default.GetString(labellist, 0, labellist.Length); + + + Console.WriteLine("strGet:", strGet); + + + ConvertJsonResult(strGet, ref mlResult); + + maskWeighted?.Dispose(); + maskWeighted = null; + + //解析json字符串 + + return mlResult; + } + else + { + mlResult.ResultMessage = $"异常:深度学习执行推理失败!"; + return mlResult; + } + } + catch (Exception ex) + { + mlResult.ResultMessage = $"深度学习执行推理异常:{ex.Message}"; + return mlResult; + } + finally + { + + originMat?.Dispose(); + originMat = null; + + + // GC.Collect(); + } + } + + [HandleProcessCorruptedStateExceptions] + public void FreeModel() + { + OcrEngine.FreePredictor(Model); + } + + + } +} diff --git a/HisenceYoloDetection/PaddleOcrModelCountry.cs b/HisenceYoloDetection/PaddleOcrModelCountry.cs new file mode 100644 index 0000000..607e670 --- /dev/null +++ b/HisenceYoloDetection/PaddleOcrModelCountry.cs @@ -0,0 +1,304 @@ + +using Newtonsoft.Json; + +using OpenCvSharp; +using OpenCvSharp.Extensions; +using PaddleOCRSharp; +using STTech.BytesIO.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +using static System.Net.Mime.MediaTypeNames; + +using Point = OpenCvSharp.Point; + +namespace XKRS.Device.SimboVision.SimboHelper +{ + public class SegResultCountry + { + public List SegmentResult; + public class ResultCountry + { + + public double fScore; + public int classId; + public string classname; + + public double area; + public List> rect; + + + } + + + } + + + + public class PaddleOcrModelCountry + { + IntPtr Model; + public bool Load(string ModelFile,string Device) + { + bool res = false; + try + { + + + Model = OcrEngine.InitModel(ModelFile, Device); + res = true; + +#if USE_MULTI_THREAD + + IsCreated = true; + if (IsCreated) + { + if (_runHandleBefore == null) + { + _runHandleBefore = new AutoResetEvent(false); + } + + if (_runHandleAfter == null) + { + _runHandleAfter = new ManualResetEvent(false); + } + + if (_runTask == null) + { + _runTask = Task.Factory.StartNew(() => + { + while (IsCreated) + { + _runHandleBefore.WaitOne(); + + if (IsCreated) + { + _result = RunInferenceFixed(_req); + _runHandleAfter.Set(); + } + } + }, TaskCreationOptions.LongRunning); + } + } +#endif + } + catch (Exception ex) + { + throw ex; + } + return res; + } + + + +#if USE_MULTI_THREAD + MLRequest _req = null; + MLResult _result = null; + + + public bool IsCreated { get; set; } = false; + Task _runTask = null; + AutoResetEvent _runHandleBefore = new AutoResetEvent(false); + ManualResetEvent _runHandleAfter = new ManualResetEvent(false); + object _runLock = new object(); +#endif + + [HandleProcessCorruptedStateExceptions] + public MLResultModel RunInference(MLRequest req) + { +#if USE_MULTI_THREAD + MLResult mlResult = null; + lock (_runLock) + { + _result = new MLResult(); + + _req = req; + + _runHandleAfter.Reset(); + _runHandleBefore.Set(); + _runHandleAfter.WaitOne(); + + mlResult = _result; + } + + return mlResult; +#else + return RunInferenceFixed(req); +#endif + + + + + } + + + private void ConvertJsonResult(string json, ref MLResultModel result) + { + // json = "{\"FastDetResult\":[{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.654843,\"rect\":[175,99,110,594]},{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.654589,\"rect\":[2608,19,104,661]},{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.654285,\"rect\":[1275,19,104,662]},{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.620762,\"rect\":[1510,95,107,600]},{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.617812,\"rect\":[2844,93,106,602]}]}"; + // + Console.WriteLine("检测结果JSON:" + json); + SegResultCountry detResult = JsonConvert.DeserializeObject(json); + if (detResult == null) + { + return; + } + + int iNum = detResult.SegmentResult.Count; + int IokNum = 0; + for (int ix = 0; ix < iNum; ix++) + { + var det = detResult.SegmentResult[ix]; + + var rect = det.rect; + List points = new List(); + List maxYs = new List(); + //把字体打印在矩形框的下面,考虑矩形框最靠下的角点Y值不能超过边框值 否则就往上写 + for (int n = 0; n < det.rect.Count(); n++) + { + points.Add(new Point(det.rect[n][0], det.rect[n][1])); + maxYs.Add(det.rect[n][1]); + } + // 定义矩形左上角和右下角的坐标 + Point topLeft = points[0]; + Point bottomRight = points[2]; + + // 计算矩形的长和宽 + int width = bottomRight.X - topLeft.X;//矩形宽度 + int height = bottomRight.Y - topLeft.Y;//矩形高度 + //下面定义一个矩形区域,以后在这个矩形里画上白底黑字 + float rectX = points[0].X; + float rectY = points[0].Y; + float rectWidth = width; + float rectHeight = height; + + + DetectionResultDetail detectionResultDetail = new DetectionResultDetail(); + detectionResultDetail.LabelNo = det.classId; + //todo: 标签名相对应 + detectionResultDetail.LabelDisplay = det.classname; + detectionResultDetail.Rect = new Rectangle(rectX.ToInt(), rectY.ToInt(), rectWidth.ToInt(), rectHeight.ToInt()); + detectionResultDetail.Score = det.fScore; + detectionResultDetail.LabelName = det.classname; + detectionResultDetail.Area = det.area; + result.ResultDetails.Add(detectionResultDetail); + //if (det.classname.Contains("Model:") || det.classname.Contains("Batch:")) + //{ + // string[] sArray = Regex.Split(det.classname, "Model:", RegexOptions.IgnoreCase); + // string splitBar = ""; + // if (sArray.Count() > 1) + // { + // result.WashMachineBar = sArray[1]; + // string[] aBatch = Regex.Split(sArray[0], "Batch:", RegexOptions.IgnoreCase); + // if (aBatch.Count() > 1) + // { + // result.WashMachineBatch = aBatch[1]; + // } + // } + //} + //if (det.classname.Contains("SN:") ) + //{ + // string[] sArray = Regex.Split(det.classname, "SN:", RegexOptions.IgnoreCase); + // string splitBar = ""; + // if (sArray.Count() > 1) + // { + // result.WashMachineSN = sArray[1]; + + // } + //} + } + + } + + + + + [HandleProcessCorruptedStateExceptions] + public MLResultModel RunInferenceFixed(MLRequest req) + { + MLResultModel mlResult = new MLResultModel(); + Mat originMat = new Mat(); + + try + { + originMat = req.currentMat;//1ms + + int iWidth = originMat.Cols; + int iHeight = originMat.Rows; + + //输入数据转化为字节 + var inputByte = new byte[originMat.Total() * 3];//这里必须乘以通道数,不然数组越界,也可以用w*h*c,差不多 + Marshal.Copy(originMat.Data, inputByte, 0, inputByte.Length); + + byte[] labellist = new byte[20480]; //新建字节数组:label1_str label2_str + + byte[] outputByte = new byte[originMat.Total() * 3]; + + Stopwatch sw = new Stopwatch(); + sw.Start(); + unsafe + { + mlResult.IsSuccess = OcrEngine.Inference(Model, inputByte, iWidth, iHeight, 3, ref outputByte[0], ref labellist[0]); + + } + sw.Stop(); + + if (mlResult.IsSuccess) + { + mlResult.ResultMessage = $"深度学习推理成功,耗时:{sw.ElapsedMilliseconds} ms"; + + Mat maskWeighted = new Mat(iHeight, iWidth, MatType.CV_8UC3, outputByte); + + mlResult.ResultMap = BitmapConverter.ToBitmap(maskWeighted);//4ms + //将字节数组转换为字符串 + mlResult.ResultMap = originMat.ToBitmap();//4ms + string strGet = System.Text.Encoding.Default.GetString(labellist, 0, labellist.Length); + + + Console.WriteLine("strGet:", strGet); + + + ConvertJsonResult(strGet, ref mlResult); + + maskWeighted?.Dispose(); + maskWeighted = null; + + //解析json字符串 + + return mlResult; + } + else + { + mlResult.ResultMessage = $"异常:深度学习执行推理失败!"; + return mlResult; + } + } + catch (Exception ex) + { + mlResult.ResultMessage = $"深度学习执行推理异常:{ex.Message}"; + return mlResult; + } + finally + { + + //originMat?.Dispose(); + //originMat = null; + + + // GC.Collect(); + } + } + + + public void FreeModel() + { + OcrEngine.FreePredictor(Model); + } + } +} diff --git a/HisenceYoloDetection/Program.cs b/HisenceYoloDetection/Program.cs new file mode 100644 index 0000000..79884d0 --- /dev/null +++ b/HisenceYoloDetection/Program.cs @@ -0,0 +1,68 @@ +namespace HisenceYoloDetection +{ + internal static class Program + { + static MainForm? mainFrm = null; + /// + /// The main entry point for the application. + /// + [STAThread] + + static void Main() + { + try + { + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + mainFrm = new MainForm(); + Application.Run(mainFrm); + AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; + Application.ThreadException += Application_ThreadException; + }catch (Exception ex) + { + } + + + } + private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) + { + string msg = e.Exception.Message; + + using (StreamWriter sw = new StreamWriter("D://ThreadException.log", true)) + { + sw.WriteLine("================================"); + sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); + sw.WriteLine(msg); + sw.Flush(); + } + + + if (mainFrm != null) + { + // mainFrm.DockFrm_OnLogMsgOutput(new LogMsg(DateTime.Now, EnumHelper.LogLevel.Exception, msg)); + } + //MessageBox.Show(msg, "߳쳣"); + } + + private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) + { + string msg = (e.ExceptionObject as Exception).Message; + + using (StreamWriter sw = new StreamWriter("D://UnhandledException.log", true)) + { + sw.WriteLine("================================"); + sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); + sw.WriteLine(msg); + sw.Flush(); + } + + if (mainFrm != null) + { + //mainFrm.DockFrm_OnLogMsgOutput(new LogMsg(DateTime.Now, EnumHelper.LogLevel.Exception, msg)); + //MessageBox.Show(msg, "δ쳣"); + } + + } + } +} \ No newline at end of file diff --git a/HisenceYoloDetection/Properties/Resources.Designer.cs b/HisenceYoloDetection/Properties/Resources.Designer.cs new file mode 100644 index 0000000..514665c --- /dev/null +++ b/HisenceYoloDetection/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace HisenceYoloDetection.Properties { + using System; + + + /// + /// 一个强类型的资源类,用于查找本地化的字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// 返回此类使用的缓存的 ResourceManager 实例。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("HisenceYoloDetection.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// 重写当前线程的 CurrentUICulture 属性,对 + /// 使用此强类型资源类的所有资源查找执行重写。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/HisenceYoloDetection/Properties/Resources.resx b/HisenceYoloDetection/Properties/Resources.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/HisenceYoloDetection/Properties/Resources.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/HisenceYoloDetection/SQLiteHelper.cs b/HisenceYoloDetection/SQLiteHelper.cs new file mode 100644 index 0000000..2352527 --- /dev/null +++ b/HisenceYoloDetection/SQLiteHelper.cs @@ -0,0 +1,612 @@ +using System; +using System.Collections; +using System.Collections.Specialized; +using System.Data; +using System.Data.SQLite; +using System.Configuration; + + + public class SQLiteHelper + { + //ݿַ + // public static string connectionString = ConfigurationManager.ConnectionStrings["ProcessDB"].ConnectionString; + public static string connectionString = "Data Source = D:\\Hisence\\DataBase\\ProcessDB.db;BinaryGUID=False;"; + // public SQLiteHelper() { } + + #region ÷ + + public static int GetMaxID(string FieldName, string TableName) + { + string strsql = "select max(" + FieldName + ")+1 from " + TableName; + object obj = GetSingle(strsql); + if (obj == null) + { + return 1; + } + else + { + return int.Parse(obj.ToString()); + } + } + + public static bool Exists(string strSql) + { + object obj = GetSingle(strSql); + int cmdresult; + if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) + { + cmdresult = 0; + } + else + { + cmdresult = int.Parse(obj.ToString()); + } + if (cmdresult == 0) + { + return false; + } + else + { + return true; + } + } + + public static bool Exists(string strSql, params SQLiteParameter[] cmdParms) + { + object obj = GetSingle(strSql, cmdParms); + int cmdresult; + if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) + { + cmdresult = 0; + } + else + { + cmdresult = int.Parse(obj.ToString()); + } + if (cmdresult == 0) + { + return false; + } + else + { + return true; + } + } + + #endregion + + #region ִмSQL + + /// + /// ִSQL䣬Ӱļ¼ + /// + /// SQL + /// Ӱļ¼ + public static int ExecuteSql(string SQLString) + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection)) + { + try + { + connection.Open(); + int rows = cmd.ExecuteNonQuery(); + return rows; + } + catch (System.Data.SQLite.SQLiteException E) + { + connection.Close(); + throw new Exception(E.Message); + } + } + } + } + + /// + /// ִSQL䣬ִеȴʱ + /// + /// + /// + /// + public static int ExecuteSqlByTime(string SQLString, int Times) + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection)) + { + try + { + connection.Open(); + cmd.CommandTimeout = Times; + int rows = cmd.ExecuteNonQuery(); + return rows; + } + catch (System.Data.SQLite.SQLiteException E) + { + connection.Close(); + throw new Exception(E.Message); + } + } + } + } + + /// + /// ִжSQL䣬ʵݿ + /// + /// SQL + public static bool ExecuteSqlTran(ArrayList SQLStringList) + { + bool isSuccess = false; + using (SQLiteConnection conn = new SQLiteConnection(connectionString)) + { + conn.Open(); + SQLiteCommand cmd = new SQLiteCommand(); + cmd.Connection = conn; + cmd.CommandText = "PRAGMA synchronous = OFF;"; + cmd.ExecuteNonQuery(); + SQLiteTransaction tx = conn.BeginTransaction(); + cmd.Transaction = tx; + try + { + for (int n = 0; n < SQLStringList.Count; n++) + { + string strsql = SQLStringList[n].ToString(); + if (strsql.Trim().Length > 1) + { + cmd.CommandText = strsql; + cmd.ExecuteNonQuery(); + } + } + tx.Commit(); + isSuccess = true; + } + catch (System.Data.SQLite.SQLiteException E) + { + tx.Rollback(); + isSuccess = false; + throw new Exception(E.Message); + } + } + return isSuccess; + } + + /// + /// ִдһ洢̲ĵSQL䡣 + /// + /// SQL + /// ,һֶǸʽӵ£ţͨʽ + /// Ӱļ¼ + public static int ExecuteSql(string SQLString, string content) + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + SQLiteCommand cmd = new SQLiteCommand(SQLString, connection); + SQLiteParameter myParameter = new SQLiteParameter("@content", DbType.String); + myParameter.Value = content; + cmd.Parameters.Add(myParameter); + try + { + connection.Open(); + int rows = cmd.ExecuteNonQuery(); + return rows; + } + catch (System.Data.SQLite.SQLiteException E) + { + throw new Exception(E.Message); + } + finally + { + cmd.Dispose(); + connection.Close(); + } + } + } + + /// + /// ִдһ洢̲ĵSQL䡣 + /// + /// SQL + /// ,һֶǸʽӵ£ţͨʽ + /// Ӱļ¼ + public static object ExecuteSqlGet(string SQLString, string content) + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + SQLiteCommand cmd = new SQLiteCommand(SQLString, connection); + SQLiteParameter myParameter = new SQLiteParameter("@content", DbType.String); + myParameter.Value = content; + cmd.Parameters.Add(myParameter); + try + { + connection.Open(); + object obj = cmd.ExecuteScalar(); + if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) + { + return null; + } + else + { + return obj; + } + } + catch (System.Data.SQLite.SQLiteException E) + { + throw new Exception(E.Message); + } + finally + { + cmd.Dispose(); + connection.Close(); + } + } + } + + /// + /// ݿͼʽֶ(Ƶһʵ) + /// + /// SQL + /// ͼֽ,ݿֶΪimage + /// Ӱļ¼ + public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + SQLiteCommand cmd = new SQLiteCommand(strSQL, connection); + SQLiteParameter myParameter = new SQLiteParameter("@fs", DbType.Binary); + myParameter.Value = fs; + cmd.Parameters.Add(myParameter); + try + { + connection.Open(); + int rows = cmd.ExecuteNonQuery(); + return rows; + } + catch (System.Data.SQLite.SQLiteException E) + { + throw new Exception(E.Message); + } + finally + { + cmd.Dispose(); + connection.Close(); + } + } + } + + /// + /// ִһѯ䣬زѯobject + /// + /// ѯ + /// ѯobject + public static object GetSingle(string SQLString) + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection)) + { + try + { + connection.Open(); + object obj = cmd.ExecuteScalar(); + if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) + { + return null; + } + else + { + return obj; + } + } + catch (System.Data.SQLite.SQLiteException e) + { + connection.Close(); + throw new Exception(e.Message); + } + } + } + } + + /// + /// ִвѯ䣬SQLiteDataReader(ʹø÷мҪֹرSQLiteDataReader) + /// + /// ѯ + /// SQLiteDataReader + public static SQLiteDataReader ExecuteReader(string strSQL) + { + SQLiteConnection connection = new SQLiteConnection(connectionString); + SQLiteCommand cmd = new SQLiteCommand(strSQL, connection); + try + { + connection.Open(); + SQLiteDataReader myReader = cmd.ExecuteReader(); + return myReader; + } + catch (System.Data.SQLite.SQLiteException e) + { + throw new Exception(e.Message); + } + //finally //ڴ˹رգ򣬷صĶ޷ʹ + //{ + // cmd.Dispose(); + // connection.Close(); + //} + } + + /// + /// ִвѯ䣬DataSet + /// + /// ѯ + /// DataSet + public static DataSet Query(string SQLString) + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + DataSet ds = new DataSet(); + try + { + connection.Open(); + SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection); + command.Fill(ds, "ds"); + connection.Close(); + command.Dispose(); + } + catch (System.Data.SQLite.SQLiteException ex) + { + throw new Exception(ex.Message); + } + return ds; + } + } + + public static DataSet Query(string SQLString, string TableName) + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + DataSet ds = new DataSet(); + try + { + connection.Open(); + SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection); + command.Fill(ds, TableName); + } + catch (System.Data.SQLite.SQLiteException ex) + { + throw new Exception(ex.Message); + } + return ds; + } + } + + /// + /// ִвѯ䣬DataSet,ִеȴʱ + /// + /// + /// + /// + public static DataSet Query(string SQLString, int Times) + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + DataSet ds = new DataSet(); + try + { + connection.Open(); + SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection); + command.SelectCommand.CommandTimeout = Times; + command.Fill(ds, "ds"); + } + catch (System.Data.SQLite.SQLiteException ex) + { + throw new Exception(ex.Message); + } + return ds; + } + } + + #endregion + + #region ִдSQL + + /// + /// ִSQL䣬Ӱļ¼ + /// + /// SQL + /// Ӱļ¼ + public static int ExecuteSql(string SQLString, params SQLiteParameter[] cmdParms) + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + using (SQLiteCommand cmd = new SQLiteCommand()) + { + try + { + PrepareCommand(cmd, connection, null, SQLString, cmdParms); + int rows = cmd.ExecuteNonQuery(); + cmd.Parameters.Clear(); + return rows; + } + catch (System.Data.SQLite.SQLiteException E) + { + throw new Exception(E.Message); + } + } + } + } + + /// + /// ִжSQL䣬ʵݿ + /// + /// SQLĹϣkeyΪsql䣬valueǸSQLiteParameter[] + public static void ExecuteSqlTran(Hashtable SQLStringList) + { + using (SQLiteConnection conn = new SQLiteConnection(connectionString)) + { + conn.Open(); + using (SQLiteTransaction trans = conn.BeginTransaction()) + { + SQLiteCommand cmd = new SQLiteCommand(); + try + { + //ѭ + foreach (DictionaryEntry myDE in SQLStringList) + { + string cmdText = myDE.Key.ToString(); + SQLiteParameter[] cmdParms = (SQLiteParameter[])myDE.Value; + PrepareCommand(cmd, conn, trans, cmdText, cmdParms); + int val = cmd.ExecuteNonQuery(); + cmd.Parameters.Clear(); + } + trans.Commit(); + } + catch (System.Data.SQLite.SQLiteException e) + { + trans.Rollback(); + throw new Exception(e.Message); + } + } + } + } + + /// + /// ִһѯ䣬زѯobject + /// + /// ѯ + /// ѯobject + public static object GetSingle(string SQLString, params SQLiteParameter[] cmdParms) + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + using (SQLiteCommand cmd = new SQLiteCommand()) + { + try + { + PrepareCommand(cmd, connection, null, SQLString, cmdParms); + object obj = cmd.ExecuteScalar(); + cmd.Parameters.Clear(); + if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) + { + return null; + } + else + { + return obj; + } + } + catch (System.Data.SQLite.SQLiteException e) + { + throw new Exception(e.Message); + } + } + } + } + + /// + /// ִвѯ䣬SQLiteDataReader (ʹø÷мҪֹرSQLiteDataReader) + /// + /// ѯ + /// SQLiteDataReader + public static SQLiteDataReader ExecuteReader(string SQLString, params SQLiteParameter[] cmdParms) + { + SQLiteConnection connection = new SQLiteConnection(connectionString); + SQLiteCommand cmd = new SQLiteCommand(); + try + { + PrepareCommand(cmd, connection, null, SQLString, cmdParms); + SQLiteDataReader myReader = cmd.ExecuteReader(); + cmd.Parameters.Clear(); + return myReader; + } + catch (System.Data.SQLite.SQLiteException e) + { + throw new Exception(e.Message); + } + //finally //ڴ˹رգ򣬷صĶ޷ʹ + //{ + // cmd.Dispose(); + // connection.Close(); + //} + + } + + /// + /// ִвѯ䣬DataSet + /// + /// ѯ + /// DataSet + public static DataSet Query(string SQLString, params SQLiteParameter[] cmdParms) + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + SQLiteCommand cmd = new SQLiteCommand(); + PrepareCommand(cmd, connection, null, SQLString, cmdParms); + using (SQLiteDataAdapter da = new SQLiteDataAdapter(cmd)) + { + DataSet ds = new DataSet(); + try + { + da.Fill(ds, "ds"); + cmd.Parameters.Clear(); + } + catch (System.Data.SQLite.SQLiteException ex) + { + throw new Exception(ex.Message); + } + return ds; + } + } + } + + public static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, + SQLiteTransaction trans, string cmdText, SQLiteParameter[] cmdParms) + { + if (conn.State != ConnectionState.Open) + conn.Open(); + cmd.Connection = conn; + cmd.CommandText = cmdText; + if (trans != null) + cmd.Transaction = trans; + cmd.CommandType = CommandType.Text;//cmdType; + if (cmdParms != null) + { + foreach (SQLiteParameter parameter in cmdParms) + { + if ((parameter.Direction == ParameterDirection.InputOutput + || parameter.Direction == ParameterDirection.Input) && + (parameter.Value == null)) + { + parameter.Value = DBNull.Value; + } + cmd.Parameters.Add(parameter); + } + } + } + + #endregion + + #region ת + /// + /// ŻһSQLiteParameter + /// + /// + /// + /// С + /// ֵ + /// SQLiteParameterֵ + public static SQLiteParameter MakeSQLiteParameter(string name, + DbType type, int size, object value) + { + SQLiteParameter parm = new SQLiteParameter(name, type, size); + parm.Value = value; + return parm; + } + + public static SQLiteParameter MakeSQLiteParameter(string name, DbType type, object value) + { + SQLiteParameter parm = new SQLiteParameter(name, type); + parm.Value = value; + return parm; + } + + #endregion + } diff --git a/HisenceYoloDetection/SimboObjectDetection.cs b/HisenceYoloDetection/SimboObjectDetection.cs new file mode 100644 index 0000000..f15bb1b --- /dev/null +++ b/HisenceYoloDetection/SimboObjectDetection.cs @@ -0,0 +1,268 @@ + +using OpenCvSharp; +using OpenCvSharp.Extensions; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.Linq; +using System.Runtime.ExceptionServices; +using System.Threading; +using System.Threading.Tasks; +using System.Runtime.InteropServices; +using Newtonsoft.Json; + + + + + +public class SegResult +{ + public List SegmentResult; + public class Result + { + + public double fScore; + public int classId; + public string classname; + + public double area; + public List rect; + + + } + +} + + + +/// +/// 实例分割 maskrcnn +/// +public class SimboObjectDetection +{ + + + IntPtr Model; + + public bool Load(string ModelFile, string InferenceDevice, string InputNodeName, int InferenceWidth, int InferenceHeight) + { + bool res = false; + try + { + + + Model = MLEngine.InitModel(ModelFile, + InferenceDevice, + InputNodeName, + 1, 3, + InferenceWidth, + InferenceHeight); + res = true; + +#if USE_MULTI_THREAD + + IsCreated = true; + if (IsCreated) + { + if (_runHandleBefore == null) + { + _runHandleBefore = new AutoResetEvent(false); + } + + if (_runHandleAfter == null) + { + _runHandleAfter = new ManualResetEvent(false); + } + + if (_runTask == null) + { + _runTask = Task.Factory.StartNew(() => + { + while (IsCreated) + { + _runHandleBefore.WaitOne(); + + if (IsCreated) + { + _result = RunInferenceFixed(_req); + _runHandleAfter.Set(); + } + } + }, TaskCreationOptions.LongRunning); + } + } +#endif + } + catch (Exception ex) + { + throw ex; + } + return res; + } + + + +#if USE_MULTI_THREAD + MLRequest _req = null; + MLResult _result = null; + + + public bool IsCreated { get; set; } = false; + Task _runTask = null; + AutoResetEvent _runHandleBefore = new AutoResetEvent(false); + ManualResetEvent _runHandleAfter = new ManualResetEvent(false); + object _runLock = new object(); +#endif + + [HandleProcessCorruptedStateExceptions] + public MLResult RunInference(MLRequest req) + { +#if USE_MULTI_THREAD + MLResult mlResult = null; + lock (_runLock) + { + _result = new MLResult(); + + _req = req; + + _runHandleAfter.Reset(); + _runHandleBefore.Set(); + _runHandleAfter.WaitOne(); + + mlResult = _result; + } + + return mlResult; +#else + return RunInferenceFixed(req); +#endif + + + + + } + + + private void ConvertJsonResult(string json, ref MLResult result) + { + // json = "{\"FastDetResult\":[{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.654843,\"rect\":[175,99,110,594]},{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.654589,\"rect\":[2608,19,104,661]},{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.654285,\"rect\":[1275,19,104,662]},{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.620762,\"rect\":[1510,95,107,600]},{\"cls_id\":0,\"cls\":\"liewen\",\"fScore\":0.617812,\"rect\":[2844,93,106,602]}]}"; + // + Console.WriteLine("检测结果JSON:" + json); + SegResult detResult = JsonConvert.DeserializeObject(json); + if (detResult == null) + { + return; + } + + int iNum = detResult.SegmentResult.Count; + int IokNum = 0; + for (int ix = 0; ix < iNum; ix++) + { + var det = detResult.SegmentResult[ix]; + + var rect = det.rect; + DetectionResultDetail detectionResultDetail = new DetectionResultDetail(); + detectionResultDetail.LabelNo = det.classId; + //todo: 标签名相对应 + detectionResultDetail.LabelDisplay = det.classname; + detectionResultDetail.Rect = new Rectangle(rect[0], rect[1], rect[2], rect[3]); + detectionResultDetail.Score = det.fScore; + detectionResultDetail.LabelName = det.classname; + detectionResultDetail.Area = det.area; + // detectionResultDetail.InferenceResult = ResultState.NG; + + result.ResultDetails.Add(detectionResultDetail); + } + + } + + + + + [HandleProcessCorruptedStateExceptions] + public MLResult RunInferenceFixed(MLRequest req) + { + MLResult mlResult = new MLResult(); + Mat originMat = new Mat(); + + try + { + + + // resize + originMat = req.currentMat;//1ms + + int iWidth = originMat.Cols; + int iHeight = originMat.Rows; + + //输入数据转化为字节 + var inputByte = new byte[originMat.Total() * 3];//这里必须乘以通道数,不然数组越界,也可以用w*h*c,差不多 + Marshal.Copy(originMat.Data, inputByte, 0, inputByte.Length); + + byte[] labellist = new byte[20480]; //新建字节数组:label1_str label2_str + + byte[] outputByte = new byte[originMat.Total() * 3]; + + Stopwatch sw = new Stopwatch(); + sw.Start(); + unsafe + { + mlResult.IsSuccess = MLEngine.det_ModelPredict(Model, + inputByte, + iWidth, iHeight, 3, + req.out_node_name, + req.in_lable_path, + req.confThreshold, req.iouThreshold, + ref outputByte[0], + ref labellist[0]); + //mlResult.IsSuccess = true; + } + sw.Stop(); + + if (mlResult.IsSuccess) + { + mlResult.ResultMessage = $"深度学习推理成功,耗时:{sw.ElapsedMilliseconds} ms"; + + Mat maskWeighted = new Mat(iHeight, iWidth, MatType.CV_8UC3, outputByte); + + mlResult.ResultMap = BitmapConverter.ToBitmap(maskWeighted);//4ms + //将字节数组转换为字符串 + // mlResult.ResultMap = originMat.ToBitmap();//4ms + string strGet = System.Text.Encoding.Default.GetString(labellist, 0, labellist.Length); + + Console.WriteLine("strGet:", strGet); + + ConvertJsonResult(strGet, ref mlResult); + + maskWeighted?.Dispose(); + maskWeighted = null; + + // 解析json字符串 + return mlResult; + } + else + { + mlResult.ResultMessage = $"异常:深度学习执行推理失败!"; + return mlResult; + } + } + catch (Exception ex) + { + //mlResult.ResultMessage = $"深度学习执行推理异常:{ex.GetExceptionMessage()}"; + return mlResult; + } + finally + { + + // originMat?.Dispose(); + // originMat = null; + + + // GC.Collect(); + } + } + + +} + diff --git a/HisenceYoloDetection/SimboVisionMLBase.cs b/HisenceYoloDetection/SimboVisionMLBase.cs new file mode 100644 index 0000000..d38cf56 --- /dev/null +++ b/HisenceYoloDetection/SimboVisionMLBase.cs @@ -0,0 +1,236 @@ + +using OpenCvSharp; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Runtime.InteropServices; + + + +public class XKHisence +{ + public int Number; + public string ?Type; + public string ?OcrBar; + + public int MoveX; + public int MoveY; + public int MoveZ; + public string ?Detect; + public string ?OcrText; + public int MoveTwoX; + public int MoveTwoY; + public int MoveTwoZ; + public string ?OcrParm; + public string ?Language; + public XKHisence() + { + + } + + public XKHisence(String type,string ocrBar,int MoveX,int MoveY,int MoveZ,string Detect,string ocrText,int MoveTwoX,int MoveTwoY,int MoveTwoZ,string OcrParm,string Language) + { + this.Type = type; + this.OcrBar = ocrBar; + this.MoveX = MoveX; + this.MoveY = MoveY; + this.MoveZ= MoveZ; + this.Detect = Detect; + this.OcrText= ocrText; + this.MoveTwoX = MoveTwoX; + this.MoveTwoY = MoveTwoY; + this.MoveTwoZ = MoveTwoZ; + this.OcrParm = OcrParm; + this.Language = Language; + + } + + +} +public class MLRequest +{ + public int ImageChannels = 3; + public Mat currentMat; + public int ResizeWidth; + public int ResizeHeight; + + public float confThreshold; + + public float iouThreshold; + + //public int ImageResizeCount; + + public string in_node_name; + + public string out_node_name; + + public string in_lable_path; + + public int ResizeImageSize; + public int segmentWidth; + public int ImageWidth; + + + + + public float Score; + +} +public class DetectionResultDetail +{ + public string LabelBGR { get; set; }//识别到对象的标签BGR + + + public int LabelNo { get; set; } // 识别到对象的标签索引 + + public string LabelName { get; set; }//识别到对象的标签名称 + + public double Score { get; set; }//识别目标结果的可能性、得分 + + public string LabelDisplay { get; set; }//识别到对象的 显示信息 + + public double Area { get; set; }//识别目标的区域面积 + + public Rectangle Rect { get; set; }//识别目标的外接矩形 + + public RotatedRect MinRect { get; set; }//识别目标的最小外接矩形(带角度) + + //public ResultState InferenceResult { get; set; }//只是模型推理 label的结果 + + public double DistanceToImageCenter { get; set; } //计算矩形框到图像中心的距离 + + + + // public ResultState FinalResult { get; set; }//模型推理+其他视觉、逻辑判断后 label结果 +} +public class MLResult +{ + public bool IsSuccess = false; + public string ResultMessage; + public Bitmap ResultMap; + public List ResultDetails = new List(); + +} +public class MLResultModel +{ + public bool IsSuccess = false; + public string ResultMessage; + public Bitmap ResultMap; + public List ResultDetails = new List(); + public string WashMachineBar; + public string WashMachineBatch; + public string WashMachineSN; + public string WashMachineLanguage; +} +public static class MLEngine +{ + + //private const string sPath = @"D:\\C#\磁环项目\\OpenVinoYolo\\openvino_Yolov5_v7_v2.0\\openvino_Yolov5_v7\\Program\ConsoleProject\\x64\\Release\\QuickSegmentDynamic.dll"; + + + [DllImport("QuickSegmentDynamic.dll", EntryPoint = "InitModel")] + public static extern IntPtr InitModel(string model_filename, string inferenceDevice, string input_node_name, int bacth, int inferenceChannels, int InferenceWidth, int InferenceHeight); + + + /// + /// 分割 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + [DllImport("QuickSegmentDynamic.dll", EntryPoint = "seg_ModelPredict")] + + public static extern bool seg_ModelPredict(IntPtr model, byte[] img, int W, int H, int C, + string labelText, float conf_threshold, float IOU_THRESHOLD, float fScoreThre, int segmentWidth, + ref byte Mask_output, ref byte label); + + + + /// + /// 目标检测 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + [DllImport("QuickSegmentDynamic.dll", EntryPoint = "det_ModelPredict")] + public static extern bool det_ModelPredict(IntPtr model, byte[] img, int W, int H, int C, + string nodes,// ++++++++++++++++++++++++++++++++++++ + string labelText, float conf_threshold, float IOU_THRESHOLD, + ref byte Mask_output, ref byte label); + + + [DllImport("QuickSegmentDynamic.dll", EntryPoint = "FreePredictor")] + public static extern void FreePredictor(IntPtr model); + + +} +public static class OcrEngine +{ + + // private const string sPath = @"F:\OOOCR\PaddleOCRsourcecodeGPU\PROJECTS\OcrDetForm\bin\Release\net7.0-windows\ocrInference.dll"; + + + + [DllImport("ocrInference.dll", EntryPoint = "InitModel")] + public static extern IntPtr InitModel(string model_ParaPath, string device_id); + + + + + + [DllImport("ocrInference.dll", EntryPoint = "Inference")] + public static extern bool Inference(IntPtr model, byte[] img, int W, int H, int C, + + ref byte Mask_output, ref byte label); + + + [DllImport("ocrInference.dll", EntryPoint = "FreePredictor")] + public static extern void FreePredictor(IntPtr model); +} +public static class MLEngine1 +{ + /**********************************************************************/ + /***************** 1.推理DLL导入实现 ****************/ + /**********************************************************************/ + //private const string sPath = @"D:\M018_NET7.0\src\Debug\model_infer.dll"; + // 加载推理相关方法 + [DllImport("model_infer.dll", EntryPoint = "InitModel")] // 模型统一初始化方法: 需要yml、pdmodel、pdiparams + //[DllImport(sPath, EntryPoint = "InitModel")] // 模型统一初始化方法: 需要yml、pdmodel、pdiparams + public static extern IntPtr InitModel(string model_type, string model_filename, string params_filename, string cfg_file, bool use_gpu, int gpu_id, ref byte paddlex_model_type); + + [DllImport("model_infer.dll", EntryPoint = "Det_ModelPredict")] // PaddleDetection模型推理方法 + public static extern bool Det_ModelPredict(IntPtr model, byte[] img, int W, int H, int C, IntPtr output, int[] BoxesNum, ref byte label); + + [DllImport("model_infer.dll", EntryPoint = "Seg_ModelPredict")] // PaddleSeg模型推理方法 + public static extern bool Seg_ModelPredict(IntPtr model, byte[] img, int W, int H, int C, ref byte output); + + [DllImport("model_infer.dll", EntryPoint = "Cls_ModelPredict")] // PaddleClas模型推理方法 + public static extern bool Cls_ModelPredict(IntPtr model, byte[] img, int W, int H, int C, ref float score, ref byte category, ref int category_id); + + [DllImport("model_infer.dll", EntryPoint = "Mask_ModelPredict")] // Paddlex的MaskRCNN模型推理方法 + public static extern bool Mask_ModelPredict(IntPtr model, byte[] img, int W, int H, int C, IntPtr output, ref byte Mask_output, int[] BoxesNum, ref byte label); + //public static extern bool Mask_ModelPredict(IntPtr model, IntPtr img, int W, int H, int C, IntPtr output, ref byte Mask_output, int[] BoxesNum, ref byte label); + [DllImport("model_infer.dll", EntryPoint = "DestructModel")] // 分割、检测、识别模型销毁方法 + public static extern void DestructModel(IntPtr model); + +} + + diff --git a/HisenceYoloDetection/StaticHelper.cs b/HisenceYoloDetection/StaticHelper.cs new file mode 100644 index 0000000..b8a3168 --- /dev/null +++ b/HisenceYoloDetection/StaticHelper.cs @@ -0,0 +1,668 @@ +using Microsoft.CSharp.RuntimeBinder; +//using Newtonsoft.Json; +using System.Collections.ObjectModel; +using System.Drawing.Imaging; +using System.Dynamic; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; +using System.Runtime.Serialization.Formatters.Binary; + + public static class StaticHelper + { + /// + /// 数值转换为byte数组 高位在前,低位在后 + /// + /// + /// + /// + public static byte[] IntToBytes(this int number, int size = 2) + { + byte[] result = new byte[size]; + + int temp = size; + while (temp > 0) + { + result[size - temp] = (byte)(number >> ((temp - 1) * 8) & 0xff); + + temp--; + } + + return result; + } + + /// + /// 字节数组转换为整数 + /// + /// 字节数组 + /// true:数组序号低的在高位 false:数组序号低的在低位 + /// + public static int BytesToInt(this byte[] data, bool HtL = true) + { + int res = 0; + + for (int i = 0; i < data.Length; i++) + { + int index = i; + + if (HtL) + { + index = data.Length - 1 - i; + } + + res += data[index] << (8 * i); + } + + return res; + } + + /// + /// 获取一个类指定的属性值 + /// + /// object对象 + /// 属性名称 + /// + public static object GetPropertyValue(object info, string field) + { + if (info == null) return null; + Type t = info.GetType(); + IEnumerable property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi; + return property.First().GetValue(info, null); + } + + /// + /// 将32位整形拆分为无符号16位整形 + /// + /// 需要拆分的32位整形 + /// 拆分为16位整形的位数 1或者2 + /// true:高位在前,低位在后;false:高位在后,低位在前 + /// + public static List ParseIntToUnsignShortList(this int num, int bitNum = 2, bool HtL = false) + { + if (bitNum == 2) + { + ushort high = (ushort)(num >> 16); + ushort low = (ushort)num; + + if (HtL) + { + return new List() { high, low }; + } + else + { + return new List() { low, high }; + } + } + else + { + if (num < 0) + { + num = ushort.MaxValue + 1 + num; + } + + return new List() { (ushort)num }; + } + } + + /// + /// 将32位整形数组拆分为无符号16位整形数组 + /// + /// 需要拆分的32位整形 + /// 拆分为16位整形的位数 1或者2 + /// true:高位在前,低位在后;false:高位在后,低位在前 + /// + public static List ParseIntToUnsignShortList(this List list, int bitNum = 2, bool HtL = false) + { + return list.SelectMany(u => u.ParseIntToUnsignShortList(bitNum, HtL)).ToList(); + } + + /// + /// 将ushort的集合转换为16位带符号整形 + /// + /// + /// 合并的位数 1或者2 + /// true:高位在前,低位在后;false:高位在后,低位在前 + /// + public static List ParseUnsignShortListToInt(this List numList, int bitNum = 2, bool HtL = false) + { + if (bitNum == 1) + { + return numList.ConvertAll(n => + { + int num = n; + if (num > short.MaxValue) + { + num = num - ushort.MaxValue - 1; + } + + return num; + }); + } + else + { + List list = new List(); + for (int i = 0; i < numList.Count; i += 2) + { + int high = HtL ? numList[i] : numList[i + 1]; + int low = HtL ? numList[i + 1] : numList[i]; + list.Add((high << 16) | low); + } + + return list; + } + } + + //public static T DeepSerializeClone(this T t) + //{ + // return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(t)); + //} + + public static void DataFrom(this T1 destT, T2 sourceT, List exceptionProps = null) where T1 : class where T2 : class + { + if (sourceT == null) + { + destT = null; + return; + } + + PropertyInfo[] propDest = destT.GetType().GetProperties();//.Where(p => !(p.GetMethod.IsVirtual && !p.GetMethod.IsFinal)).ToArray(); + PropertyInfo[] propSource = sourceT.GetType().GetProperties(); + + Array.ForEach(propDest, prop => + { + if (exceptionProps == null || !exceptionProps.Contains(prop.Name)) + { + if (prop.CanWrite) + { + PropertyInfo propS = propSource.FirstOrDefault(p => p.Name == prop.Name); + if (propS != null && propS.CanRead) + { + prop.SetValue(destT, propS.GetValue(sourceT)); + } + } + } + }); + } + + public static Bitmap BitmapSerializeCopy(this Bitmap map) + { + Bitmap image = null; + using (MemoryStream ms = new MemoryStream()) + { + BinaryFormatter bf = new BinaryFormatter(); +#if NET7_0_OR_GREATER +#pragma warning disable SYSLIB0011 +#endif + bf.Serialize(ms, map); + ms.Seek(0, SeekOrigin.Begin); + image = (Bitmap)bf.Deserialize(ms); +#if NET7_0_OR_GREATER +#pragma warning restore SYSLIB0011 +#endif + //ms.Close(); + } + + return image; + } + + public static Bitmap DeepClone(this Bitmap bitmap) + { + Bitmap dstBitmap = null; + using (MemoryStream mStream = new MemoryStream()) + { + BinaryFormatter bf = new BinaryFormatter(); +#if NET7_0_OR_GREATER +#pragma warning disable SYSLIB0011 +#endif + bf.Serialize(mStream, bitmap); + //#pragma warning restore SYSLIB0011 + mStream.Seek(0, SeekOrigin.Begin); + dstBitmap = (Bitmap)bf.Deserialize(mStream); + mStream.Close(); +#if NET7_0_OR_GREATER +#pragma warning restore SYSLIB0011 +#endif + } + return dstBitmap; + } + //RtlMoveMemory + [DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory", SetLastError = false)] + public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count); + [HandleProcessCorruptedStateExceptions] + public static Bitmap CopyBitmap(this Bitmap source) + { + Bitmap clone = new Bitmap(source.Width, source.Height, source.PixelFormat); + try + { + int PixelSize = Bitmap.GetPixelFormatSize(source.PixelFormat) / 8; + if (PixelSize == 1) + { + ColorPalette cp = clone.Palette; + for (int i = 0; i < 256; i++) + { + cp.Entries[i] = Color.FromArgb(255, i, i, i); + } + clone.Palette = cp; + } + + Rectangle rect = new Rectangle(0, 0, source.Width, source.Height); + BitmapData sourceData = source.LockBits(rect, ImageLockMode.ReadWrite, source.PixelFormat); + BitmapData cloneData = clone.LockBits(rect, ImageLockMode.ReadWrite, source.PixelFormat); + if (source.Width % 4 == 0) + { + unsafe + { + CopyMemory(cloneData.Scan0, sourceData.Scan0, (uint)(sourceData.Stride * sourceData.Height)); + } + } + else + { + Parallel.For(0, source.Height, h => + { + unsafe + { + CopyMemory(cloneData.Scan0 + h * sourceData.Stride, sourceData.Scan0 + h * sourceData.Stride, (uint)sourceData.Width); + } + }); + } + + clone.UnlockBits(cloneData); + source.UnlockBits(sourceData); + + } + catch (Exception ex) + { + return clone; + } + + return clone; + } + + public static Bitmap BitmapDeepClone(Bitmap source) + { + Bitmap clone = new Bitmap(source.Width, source.Height, source.PixelFormat); + + try + { + int PixelSize = Bitmap.GetPixelFormatSize(source.PixelFormat) / 8; + if (PixelSize == 1) + { + ColorPalette cp = clone.Palette; + for (int i = 0; i < 256; i++) + { + cp.Entries[i] = Color.FromArgb(255, i, i, i); + } + clone.Palette = cp; + } + Rectangle rect = new Rectangle(0, 0, source.Width, source.Height); + BitmapData source_bitmap = source.LockBits(rect, ImageLockMode.ReadWrite, source.PixelFormat); + BitmapData destination_bitmap = clone.LockBits(rect, ImageLockMode.ReadWrite, clone.PixelFormat); + + int depth_width = source_bitmap.Width * PixelSize; + + unsafe + { + byte* source_ptr = (byte*)source_bitmap.Scan0; + byte* destination_ptr = (byte*)destination_bitmap.Scan0; + + int offset = source_bitmap.Stride - depth_width; + + for (int i = 0; i < source_bitmap.Height; i++) + { + for (int j = 0; j < depth_width; j++, source_ptr++, destination_ptr++) + { + *destination_ptr = *source_ptr; + } + + source_ptr += offset; + destination_ptr += offset; + } + } + + source.UnlockBits(source_bitmap); + clone.UnlockBits(destination_bitmap); + } + catch (Exception ex) + { + + } + return clone; + } + + + + public static Bitmap HConnectBitmap(this Bitmap map1, Bitmap map2) + { + Bitmap connectImage = null; + if (map1 == null || map2 == null) + return null; + //横向拼接 + int width = map1.Width + map2.Width; + //高度不变 + int height = Math.Max(map1.Height, map2.Height); + connectImage = new Bitmap(width, height); + using (Graphics graph = Graphics.FromImage(connectImage)) + { + graph.DrawImage(connectImage, width, height); + graph.Clear(System.Drawing.Color.White); + graph.DrawImage(map1, 0, 0); + graph.DrawImage(map2, map1.Width, 0); + } + return connectImage; + } + + public static IntPtr FloatToIntptr(float[] bytes) + { + GCHandle hObject = GCHandle.Alloc(bytes, GCHandleType.Pinned); + return hObject.AddrOfPinnedObject(); + } + + // 将Btimap类转换为byte[]类函数 + public static byte[] GetBGRValues(Bitmap bmp, out int stride) + { + var rect = new Rectangle(0, 0, bmp.Width, bmp.Height); + var bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat); + stride = bmpData.Stride; + var rowBytes = bmpData.Width * Image.GetPixelFormatSize(bmp.PixelFormat) / 8; + var imgBytes = bmp.Height * rowBytes; + byte[] rgbValues = new byte[imgBytes]; + IntPtr ptr = bmpData.Scan0; + for (var i = 0; i < bmp.Height; i++) + { + Marshal.Copy(ptr, rgbValues, i * rowBytes, rowBytes); + ptr += bmpData.Stride; + } + bmp.UnlockBits(bmpData); + return rgbValues; + } + /// + /// 缺陷灰度图转彩色图像函数 + /// + /// 灰度图 + /// 返回构造的伪彩色图像 + public static Bitmap GrayMapToColorMap(this Bitmap src, Dictionary indexColorDict = null) + { + try + { + //Stopwatch sw = new Stopwatch(); + //sw.Start(); + + Bitmap dest = new Bitmap(src.Width, src.Height, PixelFormat.Format32bppArgb); + + int destHeight = dest.Height; + int destWidth = dest.Width; + + Rectangle rect = new Rectangle(0, 0, destWidth, destHeight); + BitmapData bmpDataDest = dest.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); + BitmapData bmpDataSrc = src.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed); + int strideDest = bmpDataDest.Stride; + + int strideSrc = bmpDataSrc.Stride; + unsafe + { + byte* pDest = (byte*)bmpDataDest.Scan0.ToPointer(); + byte* pSrc = (byte*)bmpDataSrc.Scan0.ToPointer(); + + Parallel.For(0, destHeight, y => + { + Parallel.For(0, destWidth, x => + { + int pixel = pSrc[y * strideSrc + x]; + int startIndex = y * strideDest + x * 4; + if (pixel >= 0 && pixel <= 63) + { + Color color = Color.Red; + if (indexColorDict != null && indexColorDict.ContainsKey(pixel)) + { + color = indexColorDict[pixel]; + } + + byte R = color.R; + byte G = color.G; + byte B = color.B; + + pDest[startIndex] = B; + pDest[startIndex + 1] = G; + pDest[startIndex + 2] = R; + pDest[startIndex + 3] = 100; + } + else + { + pDest[startIndex] = 255; + pDest[startIndex + 1] = 255; + pDest[startIndex + 2] = 255; + pDest[startIndex + 3] = 0; + } + }); + }); + } + dest.UnlockBits(bmpDataDest); + src.UnlockBits(bmpDataSrc); + + //sw.Stop(); + //Console.WriteLine($"转换耗时:{sw.ElapsedMilliseconds}"); + + return dest; + } + catch (Exception ex) + { + return null; + } + } + + public static void Sort(this ObservableCollection collection) where T : IComparable + { + List sortedList = collection.OrderByDescending(x => x).ToList();//这里用降序 + for (int i = 0; i < sortedList.Count(); i++) + { + collection.Move(collection.IndexOf(sortedList[i]), i); + } + } + + /// + /// 获得字符串中开始和结束字符串中间的值 + /// + /// + /// + /// + /// + public static string GetMidString(string sourse, string startstr, string endstr) + { + string result = string.Empty; + int startindex, endindex; + try + { + startindex = sourse.IndexOf(startstr); + if (startindex == -1) + return result; + string tmpstr = sourse.Substring(startindex + startstr.Length); + endindex = tmpstr.IndexOf(endstr); + if (endindex == -1) + return result; + result = tmpstr.Remove(endindex); + } + catch (Exception ex) + { + return ""; + } + return result; + } + + /// + /// 获得字符串中开始和结束字符串中间的值 + /// + /// 字符串 + /// 开始 + /// 结束 + /// + private static string GetMidString2(string sourse, string startstr, string endstr) //截取指定文本,和易语言的取文本中间差不多 + { + try //异常捕捉 + { + var kn = sourse.IndexOf(startstr, StringComparison.Ordinal) + startstr.Length; + var jn = sourse.IndexOf(endstr, kn, StringComparison.Ordinal); + return sourse.Substring(kn, jn - kn); + } + catch //如果发现未知的错误,比如上面的代码出错了,就执行下面这句代码 + { + return ""; //返回空 + } + + } + + // 布尔类型转换为整型 + public static int ToInt(this object obj) + { + if (Convert.ToBoolean(obj) == true) + return 1; + else + return 0; + } + + // 整型转换为布尔类型 + public static bool ToBool(this object obj) + { + if (Convert.ToInt32(obj) == 1) + return true; + else + return false; + } + + public static object GetProperty(this object o, string member) + { + if (o == null) throw new ArgumentNullException("o"); + if (member == null) throw new ArgumentNullException("member"); + Type scope = o.GetType(); + IDynamicMetaObjectProvider provider = o as IDynamicMetaObjectProvider; + if (provider != null) + { + ParameterExpression param = Expression.Parameter(typeof(object)); + DynamicMetaObject mobj = provider.GetMetaObject(param); + GetMemberBinder binder = (GetMemberBinder)Microsoft.CSharp.RuntimeBinder.Binder.GetMember(0, member, scope, new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(0, null) }); + DynamicMetaObject ret = mobj.BindGetMember(binder); + BlockExpression final = Expression.Block( + Expression.Label(CallSiteBinder.UpdateLabel), + ret.Expression + ); + LambdaExpression lambda = Expression.Lambda(final, param); + Delegate del = lambda.Compile(); + return del.DynamicInvoke(o); + } + else + { + return o.GetType().GetProperty(member, BindingFlags.Public | BindingFlags.Instance).GetValue(o, null); + } + } + + #region 检测文件状态及操作方式选择 + [DllImport("kernel32.dll")] + private static extern IntPtr _lopen(string lpPathName, int iReadWrite); + [DllImport("kernel32.dll")] + private static extern bool CloseHandle(IntPtr hObject); + private const int OF_READWRITE = 2; + private const int OF_SHARE_DENY_NONE = 0x40; + private static readonly IntPtr HFILE_ERROR = new IntPtr(-1); + /// + /// 检测文件是否只读或被使用 + /// + /// 要检测的文件 + /// true可用,false在用或只读 + public static bool CheckFilesCanUse(string fileName) + { + if (!File.Exists(fileName)) + return true;//文件不存在 + if ((File.GetAttributes(fileName) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) + return false; //文件只读 + IntPtr vHandle = _lopen(fileName, OF_READWRITE | OF_SHARE_DENY_NONE); + if (vHandle == HFILE_ERROR) + { + CloseHandle(vHandle); + return false; //文件被占用 + } + + CloseHandle(vHandle); //文件没被占用 + return true; + } + #endregion + + /// + /// 获取指定文件夹下所有的文件名称 + /// + /// 指定文件夹名称,绝对路径 + /// 文件类型过滤,根据文件后缀名,如:*,*.txt,*.xls + /// 是否包含子文件夹 + /// ArrayList数组,为所有需要的文件路径名称 + public static List GetAllFilesByFolder(string folderName, string fileFilter, bool isContainSubFolder = false) + { + List resList = new List(); + try + { + DirectoryInfo currDir = new DirectoryInfo(folderName);//当前目录 + FileInfo[] currFiles = currDir.GetFiles(fileFilter);//当前目录文件 + foreach (FileInfo file in currFiles) + { + if (fileFilter.ToLower().IndexOf(file.Extension.ToLower()) >= 0) + { + resList.Add(file); + } + } + if (isContainSubFolder) + { + string[] subFolders = Directory.GetDirectories(folderName); + foreach (string subFolder in subFolders) + { + resList.AddRange(GetAllFilesByFolder(subFolder, fileFilter));//递归 + } + } + } + catch (Exception ex) + { + throw ex; + } + return resList; + } + + /// + /// 获取指定文件夹下所有的文件名称,不过滤文件类型 + /// + /// 指定文件夹名称,绝对路径 + /// 是否包含子文件夹 + /// ArrayList数组,为所有需要的文件路径名称 + public static List GetAllFilesByFolder(string folderName, bool isContainSubFolder) + { + return GetAllFilesByFolder(folderName, "*", isContainSubFolder); + } + } + + public class Compare : IEqualityComparer + { + private Func _getField; + public Compare(Func getfield) + { + _getField = getfield; + } + public bool Equals(T x, T y) + { + return EqualityComparer.Default.Equals(_getField(x), _getField(y)); + } + public int GetHashCode(T obj) + { + return EqualityComparer.Default.GetHashCode(_getField(obj)); + } + } + + public static class ObjectExtensions + { + public static IEnumerable DistinctBy(this IEnumerable source, Func getfield) + { + return source.Distinct(new Compare(getfield)); + } + + public static IQueryable DistinctBy(this IQueryable source, Func getfield) + { + return source.Distinct(new Compare(getfield)); + } + } + diff --git a/HisenceYoloDetection/TCPClienDriver.cs b/HisenceYoloDetection/TCPClienDriver.cs new file mode 100644 index 0000000..f94e26c --- /dev/null +++ b/HisenceYoloDetection/TCPClienDriver.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading.Tasks; +using OpenCvSharp; +using STTech.BytesIO.Core; +using STTech.BytesIO.Tcp; +using TcpClient = STTech.BytesIO.Tcp.TcpClient; +namespace HisenceYoloDetection +{ + public class TCPClienDriver + { + private TcpClient client; + public event Action OnClientDataReceived; + public void Strart() + { + client = new TcpClient(); + client.Host = "192.168.3.100"; + client.Port= 9004; + //client.Host = "127.0.0.1"; + //client.Port = 9000; + client.Connect(); + + client.OnDataReceived += Client_OnDataReceived; + client.OnConnectedSuccessfully += Client_OnConnectedSuccessfully; + client.OnDisconnected += Client_OnDisconnected; + + + } + + private void Client_OnDisconnected(object? sender, DisconnectedEventArgs e) + { + Console.WriteLine("已经断开"); + } + + private void Client_OnConnectedSuccessfully(object? sender, ConnectedSuccessfullyEventArgs e) + { + Console.WriteLine("已经连上"); + } + + private void Client_OnDataReceived(object? sender, DataReceivedEventArgs e) + { + OnClientDataReceived?.Invoke(e.Data); + } + private void Stop() + { + client.Disconnect(); + } + + public void btnSendMsg(string msg) + { + //client.Send(msg.GetBytes("GBK")); + client.Send(System.Text.Encoding.UTF8.GetBytes(msg)); + } + + + + } +} diff --git a/HisenceYoloDetection/VirtualPLCTCPDriver.cs b/HisenceYoloDetection/VirtualPLCTCPDriver.cs new file mode 100644 index 0000000..cb6e723 --- /dev/null +++ b/HisenceYoloDetection/VirtualPLCTCPDriver.cs @@ -0,0 +1,212 @@ + +using HslCommunication; +using HslCommunication.Profinet.Melsec; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; +using System.Xml.Linq; +using static HisenceYoloDetection.MainForm; +using static OpenCvSharp.FileStorage; + + + +public class MelsecPLCTCPDriver1 +{ + // private MelsecMcNet melsecMc = new MelsecMcNet(); + // private HslCommunication.ModBus.ModbusTcpNet melsecMc = new HslCommunication.ModBus.ModbusTcpNet(); + HslCommunication.Profinet.Melsec.MelsecMcServer melsecMc = new HslCommunication.Profinet.Melsec.MelsecMcServer(); + + #region PLCBase + + + public int ReadInt(string address) + { + try + { + // 读取Int变量 + var result = melsecMc.ReadInt16("D"+address); + if (result.IsSuccess) + { + return result.Content; + } + else + { + // LogAsync(DateTime.Now, LogLevel.Error, $"{Name}未读取到数据:" + "地址:" + address + ";提示:" + result.Message); + return -1; + } + } + catch (Exception ex) + { + // LogAsync(DateTime.Now, LogLevel.Exception, $"{Name}读取异常:" + ex.GetExceptionMessage()); + return -1; + } + } + + + + /// + /// 写单独地址 + /// + /// 地址 + /// + /// + public void WriteInt(string address, int writeValue, bool waitForReply = true) + { + if (string.IsNullOrEmpty(address)) + { + // LogAsync(DateTime.Now, LogLevel.Error, $"{Name} 数据写入参数不能为空!"); + return; + } + + int repeatTime = 3; + Stopwatch sw = new Stopwatch(); + + do + { + try + { + + var result = melsecMc.Write("D"+address, writeValue); + if (result.IsSuccess) + { + repeatTime = 0; + } + } + catch (Exception ex) + { + if (repeatTime < 0) + { + // LogAsync(DateTime.Now, LogLevel.Exception, $"{Name}数据写入异常:{ex.GetExceptionMessage()}"); + } + } + } while (repeatTime > 0); + sw.Stop(); + // LogAsync(DateTime.Now, LogLevel.Assist, $"{Name} {address},写入 {writeValue} 完成,耗时:{sw.ElapsedMilliseconds} ms"); + } + + #endregion + + #region DeviceBase + + public void Start() + { + // IConfig.ip + + + + // 如果网络不太理想,配置了两个端口,一个有问题,立即切换另一个的话,可以配置如下的代码 + // melsecMc.GetPipeSocket().SetMultiPorts(new int[] { 6000, 6001 }); + //melsecMc = new HslCommunication.ModBus.ModbusTcpNet(); + //melsecMc.IpAddress = "192.168.3.39"; + //melsecMc.Port = 502; + //melsecMc.ConnectTimeOut = 10000; // 连接超时,单位毫秒 + //melsecMc.ReceiveTimeOut = 5000; // 接收超时,单位毫秒 + //melsecMc.Station = 1; + //melsecMc.AddressStartWithZero = true; + //melsecMc.IsStringReverse = false; + //melsecMc.DataFormat = HslCommunication.Core.DataFormat.CDAB; + + //se("01:00:00"); + // melsecMc.EnableIPv6 = false; + melsecMc.ServerStart(6000); + // melsecMc.ServerStart(6000); + // 连接对象 + //OperateResult connect = melsecMc.ConnectServer(); + CurrentState = true; + + Task.Run(() => + { + HeartbeatMonitor(); + }); + + //else + //{ + // // LogAsync(DateTime.Now, LogLevel.Exception, $"{Name}已开启异常:{connect.Message}"); + //} + + } + + protected void Stop() + { + try + { + + // 断开连接 + // melsecMc.RemoteStop(); + // OmronUDPNet.Stop(); + } + catch (Exception ex) + { + // LogAsync(DateTime.Now, LogLevel.Exception, $"{Name}关闭异常:{ex.GetExceptionMessage()}"); + } + } + #endregion + + + + + #region IMonitor + readonly byte[] scanBuffer = new byte[2048]; + + public List GetMonitorValues(int startAddress, int length) + { + List res = new List(); + // var result = melsecMc.ReadUInt16(startAddress.ToString(), (ushort)length); + // var result = melsecMc.ReadInt32("D" + startAddress, (ushort)length); + var result = melsecMc.ReadInt32("D" + startAddress, (ushort)length); + if (result.IsSuccess) + { + res = new List(result.Content); + } + else + { + //LogAsync(DateTime.Now, LogLevel.Error, $"{Name}未读取到数据:" + "地址:W" + startAddress + ";长度:" + length + ";提示:" + result.Message); + } + return res; + } + #endregion + + int HeartbeatCycle = 2; + string HeartbeatAddress = "D800"; + bool CurrentState = false; + public event Action Heartbeat; + public async void HeartbeatMonitor() + { + if (HeartbeatCycle <= 0) + { + return; + } + await Task.Run(async () => + { + if (!string.IsNullOrEmpty(HeartbeatAddress) + && HeartbeatCycle > 0) + { + while (CurrentState != false) + { + if (HeartbeatCycle <= 0) + { + return; + } + + try + { + await Task.Delay(HeartbeatCycle * 1000); + var result = melsecMc.Write(HeartbeatAddress, 1); + if (!result.IsSuccess) + { + Heartbeat?.Invoke(1); + //LogAsync(DateTime.Now, LogLevel.Error, $"{this.Name} 心跳监听失败"); + } + } + catch (Exception ex) + { + + } + } + } + }); + } +} + diff --git a/libs/HikCamera/MvCameraControl.Net.dll b/libs/HikCamera/MvCameraControl.Net.dll new file mode 100644 index 0000000..c65d9bd Binary files /dev/null and b/libs/HikCamera/MvCameraControl.Net.dll differ diff --git a/libs/HikCamera/MvCameraControl.dll b/libs/HikCamera/MvCameraControl.dll new file mode 100644 index 0000000..579f02c Binary files /dev/null and b/libs/HikCamera/MvCameraControl.dll differ diff --git a/libs/HslCommunication.dll b/libs/HslCommunication.dll new file mode 100644 index 0000000..b2d4702 Binary files /dev/null and b/libs/HslCommunication.dll differ diff --git a/libs/WPFSmartLibraryLight35.dll b/libs/WPFSmartLibraryLight35.dll new file mode 100644 index 0000000..cc2ebbf Binary files /dev/null and b/libs/WPFSmartLibraryLight35.dll differ