diff --git a/HisenceYoloDetection/CheckDiffSciHelper.cs b/HisenceYoloDetection/CheckDiffSciHelper.cs new file mode 100644 index 0000000..5dad985 --- /dev/null +++ b/HisenceYoloDetection/CheckDiffSciHelper.cs @@ -0,0 +1,331 @@ +using OpenCvSharp; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using Point = OpenCvSharp.Point; +using Size = OpenCvSharp.Size; + + + +namespace HisenceYoloDetection +{ + public static class CheckDiffSciHelper + { + + /// + /// + /// + /// 标准图像 + /// 要对比的图像 + /// 白板黑字为true + /// 存储路径 + public static bool CheckDiffSci(string path1, Mat MatDet,Rect sqlrect,Rect detrect, bool IfWhiteWord, string saveDir) + { + // 读取和处理第一张图片 + Mat img1 = Cv2.ImRead(path1, ImreadModes.Color); + if (img1.Empty()) + { + Console.WriteLine($"Error loading image {path1}"); + return false; + } + Cv2.Resize(img1, img1, new Size(550, 270)); + Mat gimg1 = new Mat(); + Cv2.CvtColor(img1, gimg1, ColorConversionCodes.BGR2GRAY); + Mat thr1 = new Mat(); + + if(IfWhiteWord) + { + Cv2.Threshold(gimg1, thr1, 0, 255, ThresholdTypes.BinaryInv | ThresholdTypes.Otsu); + } + else + { + Cv2.Threshold(gimg1, thr1, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu); + } + + + + + // 读取和处理第二张图片 + Mat img2 = MatDet.Clone(); + if (img2.Empty()) + { + // Console.WriteLine($"Error loading image {path2}"); + return false; + } + Cv2.Resize(img2, img2, new Size(550, 270)); + Mat gimg2 = new Mat(); + Cv2.CvtColor(img2, gimg2, ColorConversionCodes.BGR2GRAY); + Mat thr2 = new Mat(); + //Cv2.Threshold(gimg2, thr2, 0, 255, ThresholdTypes.BinaryInv | ThresholdTypes.Otsu); + if (IfWhiteWord) + { + Cv2.Threshold(gimg2, thr2, 0, 255, ThresholdTypes.BinaryInv | ThresholdTypes.Otsu); + } + else + { + Cv2.Threshold(gimg2, thr2, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu); + } + // Cv2.Threshold(gimg2, thr2, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu); + + + + //Rect area2 = new Rect(148,30,229,222); + sqlrect.Width += 20; + detrect.Width += 20; + Mat matCutblack1 = new Mat(thr1, sqlrect); + if (IfWhiteWord) + { + matCutblack1.SetTo(Scalar.Black); + } + else + { + matCutblack1.SetTo(Scalar.Black); + } + Mat matCutblack2 = new Mat(thr2, detrect); + if (IfWhiteWord) + { + matCutblack2.SetTo(Scalar.Black); + } + else + { + matCutblack2.SetTo(Scalar.Black); + } + + string savePath4 = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path1) + "_thr1.png"); + // 保存结果 + + Cv2.ImWrite(savePath4, thr1); + string savePath3 = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path1) + "_thr2.png"); + // 保存结果 + + Cv2.ImWrite(savePath3, thr2); + + // 创建卷积核 + Mat filter1 = new Mat(17, 17, MatType.CV_32F, new Scalar(0)); + filter1.Row(8).SetTo(new Scalar(0.025)); + filter1.Col(8).SetTo(new Scalar(0.025)); + + // 应用卷积 + Mat final_result1 = new Mat(); + Cv2.Filter2D(thr1, final_result1, -1, filter1, anchor: new Point(-1, -1), 0, BorderTypes.Reflect); + Cv2.Filter2D(final_result1, final_result1, -1, filter1, anchor: new Point(-1, -1), 0, BorderTypes.Reflect); + Cv2.Filter2D(final_result1, final_result1, -1, filter1, anchor: new Point(-1, -1), 0, BorderTypes.Reflect); + + Mat final_result2 = new Mat(); + Cv2.Filter2D(thr2, final_result2, -1, filter1, anchor: new Point(-1, -1), 0, BorderTypes.Reflect); + Cv2.Filter2D(final_result2, final_result2, -1, filter1, anchor: new Point(-1, -1), 0, BorderTypes.Reflect); + Cv2.Filter2D(final_result2, final_result2, -1, filter1, anchor: new Point(-1, -1), 0, BorderTypes.Reflect); + //裁剪才行 + + + //string savePath2 = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path1) + "_final_result1.png"); + //// 保存结果 + ////string savePath = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path2) + "_diff.png"); + //Cv2.ImWrite(savePath2, final_result1); + //string savePath = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path1) + "_final_result2.png"); + //// 保存结果 + ////string savePath = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path2) + "_diff.png"); + //Cv2.ImWrite(savePath, final_result2); + + + + + + + + // 计算图像差异 + Mat devIMG = new Mat(); + Mat devIMG_ = new Mat(); + Cv2.Subtract(final_result1, final_result2, devIMG); + Cv2.Subtract(final_result2, final_result1, devIMG_); + + // 对差异图像应用阈值 + Cv2.Threshold(devIMG, devIMG, 50, 255, ThresholdTypes.Binary); + Cv2.Threshold(devIMG_, devIMG_, 50, 255, ThresholdTypes.Binary); + + // 结合差异 + Mat sumIMG = new Mat(); + Cv2.Add(devIMG, devIMG_, sumIMG); + + // 应用形态学操作 + Mat kernelCL = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3)); + Mat blackhatImg = new Mat(); + Cv2.Dilate(sumIMG, blackhatImg, kernelCL); + + // 处理轮廓和保存结果 + Point[][] contours = new Point[10000][]; + Cv2.FindContours(blackhatImg, out contours, out _, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple); + bool isMatch = true; + foreach (var contour in contours) + { + if (Cv2.ContourArea(contour) <= 100) + { + Cv2.DrawContours(blackhatImg, new Point[][] { contour }, -1, Scalar.Black, thickness: Cv2.FILLED); + // 框选轮廓 + + } + else + { + Rect boundingRect = Cv2.BoundingRect(contour); + Cv2.Rectangle(img2, boundingRect, Scalar.Red, thickness: 2); + isMatch= false; + } + } + + string savePath2 = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path1) + "_Rect.png"); + // 保存结果 + //string savePath = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path2) + "_diff.png"); + Cv2.ImWrite(savePath2, img2); + string savePath = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path1) + "_diff.png"); + // 保存结果 + //string savePath = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path2) + "_diff.png"); + Cv2.ImWrite(savePath, blackhatImg); + return isMatch; + } + + public static Rect strChangeRect(string strrect) + { + string[] rectstr = strrect.Split(","); + int areaX = int.Parse(rectstr[0]); + int areaY = int.Parse(rectstr[1]); + int areaWidth = int.Parse(rectstr[2]); + int areaHeight = int.Parse(rectstr[3]); + + Rect rect = new Rect(areaX, areaY, areaWidth, areaHeight); + return rect; + } + + public static string rectChangeStr(Rect area) + { + string[] rectsql = new string[4]; + rectsql[0] = Convert.ToString(area.X); + rectsql[1] = Convert.ToString(area.Y); + rectsql[2] = Convert.ToString(area.Width); + rectsql[3] = Convert.ToString(area.Height); + + string strrect = rectsql.Join(","); + return strrect; + } + //public static void CheckDiffSci(string path1, string path2, bool IfWhiteWord, string saveDir) + //{ + // // 读取和处理第一张图片 + // Mat img1 = Cv2.ImRead(path1, ImreadModes.Color); + // if (img1.Empty()) + // { + // Console.WriteLine($"Error loading image {path1}"); + // return; + // } + // Cv2.Resize(img1, img1, new Size(550, 270)); + // Mat gimg1 = new Mat(); + // Cv2.CvtColor(img1, gimg1, ColorConversionCodes.BGR2GRAY); + // Mat thr1 = new Mat(); + + // if (IfWhiteWord) + // { + // Cv2.Threshold(gimg1, thr1, 0, 255, ThresholdTypes.BinaryInv | ThresholdTypes.Otsu); + // } + // else + // { + // Cv2.Threshold(gimg1, thr1, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu); + // } + + + // string savePath4 = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path2) + "_thr1.png"); + // // 保存结果 + // //string savePath = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path2) + "_diff.png"); + // Cv2.ImWrite(savePath4, thr1); + + // // 读取和处理第二张图片 + // Mat img2 = Cv2.ImRead(path2, ImreadModes.Color); + // if (img2.Empty()) + // { + // Console.WriteLine($"Error loading image {path2}"); + // return; + // } + // Cv2.Resize(img2, img2, new Size(550, 270)); + // Mat gimg2 = new Mat(); + // Cv2.CvtColor(img2, gimg2, ColorConversionCodes.BGR2GRAY); + // Mat thr2 = new Mat(); + // //Cv2.Threshold(gimg2, thr2, 0, 255, ThresholdTypes.BinaryInv | ThresholdTypes.Otsu); + // if (IfWhiteWord) + // { + // Cv2.Threshold(gimg2, thr2, 0, 255, ThresholdTypes.BinaryInv | ThresholdTypes.Otsu); + // } + // else + // { + // Cv2.Threshold(gimg2, thr2, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu); + // } + // // Cv2.Threshold(gimg2, thr2, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu); + + // string savePath3 = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path2) + "_thr2.png"); + // // 保存结果 + // //string savePath = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path2) + "_diff.png"); + // Cv2.ImWrite(savePath3, thr2); + + // // 创建卷积核 + // Mat filter1 = new Mat(17, 17, MatType.CV_32F, new Scalar(0)); + // filter1.Row(8).SetTo(new Scalar(0.025)); + // filter1.Col(8).SetTo(new Scalar(0.025)); + + // // 应用卷积 + // Mat final_result1 = new Mat(); + // Cv2.Filter2D(thr1, final_result1, -1, filter1, anchor: new Point(-1, -1), 0, BorderTypes.Reflect); + // Cv2.Filter2D(final_result1, final_result1, -1, filter1, anchor: new Point(-1, -1), 0, BorderTypes.Reflect); + // Cv2.Filter2D(final_result1, final_result1, -1, filter1, anchor: new Point(-1, -1), 0, BorderTypes.Reflect); + + // Mat final_result2 = new Mat(); + // Cv2.Filter2D(thr2, final_result2, -1, filter1, anchor: new Point(-1, -1), 0, BorderTypes.Reflect); + // Cv2.Filter2D(final_result2, final_result2, -1, filter1, anchor: new Point(-1, -1), 0, BorderTypes.Reflect); + // Cv2.Filter2D(final_result2, final_result2, -1, filter1, anchor: new Point(-1, -1), 0, BorderTypes.Reflect); + + // // 计算图像差异 + // Mat devIMG = new Mat(); + // Mat devIMG_ = new Mat(); + // Cv2.Subtract(final_result1, final_result2, devIMG); + // Cv2.Subtract(final_result2, final_result1, devIMG_); + + // // 对差异图像应用阈值 + // Cv2.Threshold(devIMG, devIMG, 50, 255, ThresholdTypes.Binary); + // Cv2.Threshold(devIMG_, devIMG_, 50, 255, ThresholdTypes.Binary); + + // // 结合差异 + // Mat sumIMG = new Mat(); + // Cv2.Add(devIMG, devIMG_, sumIMG); + + // // 应用形态学操作 + // Mat kernelCL = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3)); + // Mat blackhatImg = new Mat(); + // Cv2.Dilate(sumIMG, blackhatImg, kernelCL); + + // // 处理轮廓和保存结果 + // Point[][] contours = new Point[10000][]; + // Cv2.FindContours(blackhatImg, out contours, out _, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple); + + // foreach (var contour in contours) + // { + // if (Cv2.ContourArea(contour) <= 100) + // { + // Cv2.DrawContours(blackhatImg, new Point[][] { contour }, -1, Scalar.Black, thickness: Cv2.FILLED); + // // 框选轮廓 + + // } + // else + // { + // Rect boundingRect = Cv2.BoundingRect(contour); + // Cv2.Rectangle(img2, boundingRect, Scalar.Red, thickness: 2); + // } + // } + // string savePath2 = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path2) + "_Rect.png"); + // // 保存结果 + // //string savePath = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path2) + "_diff.png"); + // Cv2.ImWrite(savePath2, img2); + // string savePath = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path2) + "_diff.png"); + // // 保存结果 + // //string savePath = Path.Combine(saveDir, Path.GetFileNameWithoutExtension(path2) + "_diff.png"); + // Cv2.ImWrite(savePath, blackhatImg); + //} + } +} diff --git a/HisenceYoloDetection/Form1.Designer.cs b/HisenceYoloDetection/Form1.Designer.cs new file mode 100644 index 0000000..7a211f6 --- /dev/null +++ b/HisenceYoloDetection/Form1.Designer.cs @@ -0,0 +1,763 @@ +namespace HisenceYoloDetection +{ + partial class Form1 + { + /// + /// 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() + { + tableLayoutPanel1 = new TableLayoutPanel(); + 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(); + tableLayoutPanel1.SuspendLayout(); + panel1.SuspendLayout(); + groupBox5.SuspendLayout(); + groupBox4.SuspendLayout(); + ModeleShow.SuspendLayout(); + SuspendLayout(); + // + // tableLayoutPanel1 + // + tableLayoutPanel1.ColumnCount = 1; + tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F)); + tableLayoutPanel1.Controls.Add(panel1, 0, 0); + tableLayoutPanel1.Dock = DockStyle.Fill; + tableLayoutPanel1.Location = new Point(0, 0); + tableLayoutPanel1.Name = "tableLayoutPanel1"; + tableLayoutPanel1.RowCount = 1; + tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 50F)); + tableLayoutPanel1.Size = new Size(1057, 450); + tableLayoutPanel1.TabIndex = 0; + // + // panel1 + // + panel1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + panel1.AutoSize = true; + 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(3, 3); + panel1.Name = "panel1"; + panel1.Size = new Size(1051, 444); + panel1.TabIndex = 5; + // + // 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; + // + // SetHandleSpeed + // + SetHandleSpeed.Location = new Point(8, 258); + SetHandleSpeed.Name = "SetHandleSpeed"; + SetHandleSpeed.Size = new Size(88, 23); + SetHandleSpeed.TabIndex = 28; + SetHandleSpeed.Text = "设置手动速度"; + SetHandleSpeed.UseVisualStyleBackColor = true; + // + // 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; + // + // 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; + // + // 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; + // + // 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; + // + // 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; + // + // 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; + // + // 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; + // + // 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; + // + // 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; + // + // PLCPostion + // + PLCPostion.Location = new Point(6, 258); + PLCPostion.Name = "PLCPostion"; + PLCPostion.Size = new Size(97, 101); + PLCPostion.TabIndex = 2; + PLCPostion.Text = "定位"; + PLCPostion.UseVisualStyleBackColor = true; + // + // PLCDiskZero + // + PLCDiskZero.Location = new Point(6, 141); + PLCDiskZero.Name = "PLCDiskZero"; + PLCDiskZero.Size = new Size(97, 101); + PLCDiskZero.TabIndex = 1; + PLCDiskZero.Text = "归零"; + PLCDiskZero.UseVisualStyleBackColor = true; + // + // 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; + // + // 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; + // + // 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; + // + // 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; + // + // 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; + // + // Form1 + // + AutoScaleDimensions = new SizeF(7F, 17F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1057, 450); + Controls.Add(tableLayoutPanel1); + Name = "Form1"; + Text = "Form1"; + tableLayoutPanel1.ResumeLayout(false); + tableLayoutPanel1.PerformLayout(); + panel1.ResumeLayout(false); + panel1.PerformLayout(); + groupBox5.ResumeLayout(false); + groupBox5.PerformLayout(); + groupBox4.ResumeLayout(false); + groupBox4.PerformLayout(); + ModeleShow.ResumeLayout(false); + ResumeLayout(false); + } + + #endregion + + private TableLayoutPanel tableLayoutPanel1; + private Panel panel1; + private GroupBox groupBox5; + private TextBox DistanceShow; + private Label label21; + private TextBox txtSetValue; + private GroupBox groupBox4; + private Button SetAutoSpeed; + private Button SetHandleSpeed; + private TextBox SetlnEditmiZOP; + private TextBox SetlnEditmiYOP; + private TextBox SetlnEditmiXOP; + private TextBox SetlnEditmiZH; + private TextBox SetlnEditmiYH; + private TextBox SetlnEditmiXH; + 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 Label ZPostion; + private Label YPostion; + private Label XPostion; + private Label XCurrentPostion; + private Label label14; + private Label label13; + private Label label12; + private Label label11; + private GroupBox ModeleShow; + private RadioButton ZBackwardrbx; + private RadioButton YBackwardrbx; + private RadioButton XBackwardrbx; + private RadioButton ZForwardrbx; + private RadioButton YForwardrbx; + private RadioButton XForwardrbx; + private RadioButton ZZerorbx; + private RadioButton YZerorbx; + private RadioButton XZerorbx; + private Button PLCPostion; + private Button PLCDiskZero; + private Button PLCPowerON; + private TextBox writePLCValue; + private Label label9; + private Label label10; + private Button wirteAdressBtn; + private TextBox PLCValue; + private TextBox WriteAdress; + private Label label6; + private Label label3; + private Button ConnectPLC; + private Button readAdress; + private TextBox showPLC; + private TextBox readPLc; + } +} \ No newline at end of file diff --git a/HisenceYoloDetection/Form1.cs b/HisenceYoloDetection/Form1.cs new file mode 100644 index 0000000..b4eef98 --- /dev/null +++ b/HisenceYoloDetection/Form1.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace HisenceYoloDetection +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + } +} diff --git a/HisenceYoloDetection/InsertSqlFrm.resx b/HisenceYoloDetection/Form1.resx similarity index 100% rename from HisenceYoloDetection/InsertSqlFrm.resx rename to HisenceYoloDetection/Form1.resx diff --git a/HisenceYoloDetection/InsertSqlFrm.Designer.cs b/HisenceYoloDetection/InsertSqlFrm.Designer.cs deleted file mode 100644 index d991067..0000000 --- a/HisenceYoloDetection/InsertSqlFrm.Designer.cs +++ /dev/null @@ -1,394 +0,0 @@ -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 deleted file mode 100644 index 3096eee..0000000 --- a/HisenceYoloDetection/InsertSqlFrm.cs +++ /dev/null @@ -1,198 +0,0 @@ -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/MainForm.Designer.cs b/HisenceYoloDetection/MainForm.Designer.cs index 6b4c77b..3c418a8 100644 --- a/HisenceYoloDetection/MainForm.Designer.cs +++ b/HisenceYoloDetection/MainForm.Designer.cs @@ -143,6 +143,10 @@ ResultMatShow = new PictureBox(); tabPage3 = new TabPage(); panel2 = new Panel(); + WhiteBanCbx = new CheckBox(); + label33 = new Label(); + label28 = new Label(); + button1 = new Button(); openModelBtn = new Button(); modelChangeCbx = new TextBox(); label34 = new Label(); @@ -164,7 +168,6 @@ moveTwoXbox = new TextBox(); label27 = new Label(); moveZbox = new TextBox(); - label28 = new Label(); moveYbox = new TextBox(); label29 = new Label(); moveXbox = new TextBox(); @@ -1343,6 +1346,10 @@ // // panel2 // + panel2.Controls.Add(WhiteBanCbx); + panel2.Controls.Add(label33); + panel2.Controls.Add(label28); + panel2.Controls.Add(button1); panel2.Controls.Add(openModelBtn); panel2.Controls.Add(modelChangeCbx); panel2.Controls.Add(label34); @@ -1364,7 +1371,6 @@ 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); @@ -1379,6 +1385,46 @@ panel2.Name = "panel2"; panel2.Size = new Size(1260, 533); panel2.TabIndex = 1; + panel2.Paint += panel2_Paint; + // + // WhiteBanCbx + // + WhiteBanCbx.AutoSize = true; + WhiteBanCbx.Checked = true; + WhiteBanCbx.CheckState = CheckState.Checked; + WhiteBanCbx.Location = new Point(577, 245); + WhiteBanCbx.Name = "WhiteBanCbx"; + WhiteBanCbx.Size = new Size(39, 21); + WhiteBanCbx.TabIndex = 40; + WhiteBanCbx.Text = "是"; + WhiteBanCbx.UseVisualStyleBackColor = true; + // + // label33 + // + label33.AutoSize = true; + label33.Location = new Point(373, 245); + label33.Name = "label33"; + label33.Size = new Size(140, 17); + label33.TabIndex = 39; + label33.Text = "面板第二块区域是白板吗"; + // + // label28 + // + label28.AutoSize = true; + label28.Location = new Point(18, 199); + label28.Name = "label28"; + label28.Size = new Size(87, 17); + label28.TabIndex = 14; + label28.Text = "第一次拍照Z轴"; + // + // button1 + // + button1.Location = new Point(896, 110); + button1.Name = "button1"; + button1.Size = new Size(93, 23); + button1.TabIndex = 38; + button1.Text = "识别到log"; + button1.UseVisualStyleBackColor = true; // // openModelBtn // @@ -1409,7 +1455,7 @@ // // button4 // - button4.Location = new Point(696, 152); + button4.Location = new Point(691, 110); button4.Name = "button4"; button4.Size = new Size(75, 23); button4.TabIndex = 32; @@ -1419,7 +1465,7 @@ // // OpenTwoDirBtn // - OpenTwoDirBtn.Location = new Point(696, 241); + OpenTwoDirBtn.Location = new Point(691, 199); OpenTwoDirBtn.Name = "OpenTwoDirBtn"; OpenTwoDirBtn.Size = new Size(75, 23); OpenTwoDirBtn.TabIndex = 31; @@ -1429,7 +1475,7 @@ // // OpenDirBtn // - OpenDirBtn.Location = new Point(696, 193); + OpenDirBtn.Location = new Point(691, 151); OpenDirBtn.Name = "OpenDirBtn"; OpenDirBtn.Size = new Size(75, 23); OpenDirBtn.TabIndex = 30; @@ -1439,16 +1485,16 @@ // // Cam2MatCbx // - Cam2MatCbx.Location = new Point(478, 244); + Cam2MatCbx.Location = new Point(473, 202); Cam2MatCbx.Name = "Cam2MatCbx"; Cam2MatCbx.Size = new Size(218, 23); Cam2MatCbx.TabIndex = 29; - Cam2MatCbx.Text = "D:\\Hisence\\4\\202452915599711.jpg"; + Cam2MatCbx.Text = "D:\\Hisence\\类型\\Lp\\002jpg"; // // label22 // label22.AutoSize = true; - label22.Location = new Point(371, 244); + label22.Location = new Point(366, 202); label22.Name = "label22"; label22.Size = new Size(80, 17); label22.TabIndex = 28; @@ -1456,16 +1502,16 @@ // // Cam1MatCbx // - Cam1MatCbx.Location = new Point(478, 193); + Cam1MatCbx.Location = new Point(473, 151); Cam1MatCbx.Name = "Cam1MatCbx"; Cam1MatCbx.Size = new Size(218, 23); Cam1MatCbx.TabIndex = 27; - Cam1MatCbx.Text = "D:\\Hisence\\4\\202452915596701.jpg"; + Cam1MatCbx.Text = "D:\\Hisence\\类型\\Lp\\001.jpg"; // // label23 // label23.AutoSize = true; - label23.Location = new Point(372, 199); + label23.Location = new Point(367, 157); label23.Name = "label23"; label23.Size = new Size(80, 17); label23.TabIndex = 26; @@ -1483,16 +1529,16 @@ // // DetectBArMatbox // - DetectBArMatbox.Location = new Point(477, 152); + DetectBArMatbox.Location = new Point(472, 110); DetectBArMatbox.Name = "DetectBArMatbox"; DetectBArMatbox.Size = new Size(219, 23); DetectBArMatbox.TabIndex = 24; - DetectBArMatbox.Text = "D:\\Hisence\\202452414231.jpg"; + DetectBArMatbox.Text = "D:\\Hisence\\类型\\Lp202452414231.jpg"; // // label24 // label24.AutoSize = true; - label24.Location = new Point(402, 158); + label24.Location = new Point(397, 116); label24.Name = "label24"; label24.Size = new Size(56, 17); label24.TabIndex = 23; @@ -1510,7 +1556,7 @@ // // moveTwoZbox // - moveTwoZbox.Location = new Point(477, 101); + moveTwoZbox.Location = new Point(472, 59); moveTwoZbox.Name = "moveTwoZbox"; moveTwoZbox.Size = new Size(219, 23); moveTwoZbox.TabIndex = 21; @@ -1519,7 +1565,7 @@ // label25 // label25.AutoSize = true; - label25.Location = new Point(371, 107); + label25.Location = new Point(366, 65); label25.Name = "label25"; label25.Size = new Size(87, 17); label25.TabIndex = 20; @@ -1527,7 +1573,7 @@ // // moveTwoYbox // - moveTwoYbox.Location = new Point(477, 54); + moveTwoYbox.Location = new Point(472, 12); moveTwoYbox.Name = "moveTwoYbox"; moveTwoYbox.Size = new Size(213, 23); moveTwoYbox.TabIndex = 19; @@ -1536,7 +1582,7 @@ // label26 // label26.AutoSize = true; - label26.Location = new Point(371, 60); + label26.Location = new Point(366, 18); label26.Name = "label26"; label26.Size = new Size(87, 17); label26.TabIndex = 18; @@ -1544,7 +1590,7 @@ // // moveTwoXbox // - moveTwoXbox.Location = new Point(477, 12); + moveTwoXbox.Location = new Point(122, 242); moveTwoXbox.Name = "moveTwoXbox"; moveTwoXbox.Size = new Size(213, 23); moveTwoXbox.TabIndex = 17; @@ -1553,7 +1599,7 @@ // label27 // label27.AutoSize = true; - label27.Location = new Point(371, 18); + label27.Location = new Point(16, 248); label27.Name = "label27"; label27.Size = new Size(88, 17); label27.TabIndex = 16; @@ -1563,24 +1609,15 @@ // moveZbox.Location = new Point(111, 193); moveZbox.Name = "moveZbox"; - moveZbox.Size = new Size(188, 23); + moveZbox.Size = new Size(224, 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.Size = new Size(224, 23); moveYbox.TabIndex = 13; moveYbox.Text = "0"; // @@ -1597,7 +1634,7 @@ // moveXbox.Location = new Point(111, 104); moveXbox.Name = "moveXbox"; - moveXbox.Size = new Size(188, 23); + moveXbox.Size = new Size(224, 23); moveXbox.TabIndex = 11; moveXbox.Text = "8974"; // @@ -1614,7 +1651,7 @@ // OcrBarBox.Location = new Point(111, 54); OcrBarBox.Name = "OcrBarBox"; - OcrBarBox.Size = new Size(188, 23); + OcrBarBox.Size = new Size(224, 23); OcrBarBox.TabIndex = 5; OcrBarBox.Text = "1234567890"; // @@ -1631,7 +1668,7 @@ // TypeBox.Location = new Point(111, 12); TypeBox.Name = "TypeBox"; - TypeBox.Size = new Size(188, 23); + TypeBox.Size = new Size(224, 23); TypeBox.TabIndex = 3; TypeBox.Text = "1"; // @@ -1895,5 +1932,8 @@ private Button openModelBtn; private TextBox modelChangeCbx; private Label label34; + private Button button1; + private Label label33; + private CheckBox WhiteBanCbx; } } diff --git a/HisenceYoloDetection/MainForm.cs b/HisenceYoloDetection/MainForm.cs index dcbdf39..dc1b259 100644 --- a/HisenceYoloDetection/MainForm.cs +++ b/HisenceYoloDetection/MainForm.cs @@ -4,18 +4,24 @@ using OpenCvSharp; using OpenCvSharp.Dnn; using OpenCvSharp.Extensions; using OpenCvSharp.XFeatures2D; +using System; using System.Data; +using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder; +using System.Data.SQLite; using System.Diagnostics; +using System.Diagnostics.Eventing.Reader; using System.Drawing; using System.Drawing.Drawing2D; using System.Net; using System.Numerics; +using System.Text; 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; +using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView; namespace HisenceYoloDetection @@ -32,6 +38,10 @@ namespace HisenceYoloDetection TCPClienDriver Scanner = new TCPClienDriver(); MelsecPLCTCPDriver melsecPLCTCPDriver = new MelsecPLCTCPDriver(); SimboObjectDetection simboObjectDetection = new SimboObjectDetection(); + SimboObjectDetection simboObjectDetButton = new SimboObjectDetection(); + // CheckDiffSciHelper checkDiffSciHelper = new CheckDiffSciHelper(); + // ManagerModelHelper managerModelHelper = new ManagerModelHelper(); + PaddleOcrModel paddleOcrModel = new PaddleOcrModel(); PaddleOcrModelCountry paddleOcrModelCountry = new PaddleOcrModelCountry(); List xKHisences = new List(); @@ -53,6 +63,7 @@ namespace HisenceYoloDetection Mat Cam2ImgShowBar = new Mat();//ʵʱ2Ƭ ʶ XKHisence xKNow;//ݿеϴ» + XK_HisenceWord xK_HisenceSQLWord = new XK_HisenceWord(); bool bOn = false; //////////////////////////// public static int m_CamCount = 0; @@ -69,6 +80,7 @@ namespace HisenceYoloDetection bool ifXBackward = false; bool ifYBackward = false; bool ifZBackward = false; + string LablePath = ""; //¼ݿ string BarPath = ""; string Cam1OnePath = ""; @@ -160,12 +172,19 @@ namespace HisenceYoloDetection /// 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 vBarPath = "D:\\Hisence\\\\Lp\\202452414231.jpg"; + string vCam1OnePath = "D:\\Hisence\\\\Lp\\001.jpg"; + string vCam1TwoPath = "D:\\Hisence\\\\Lp\\002.jpg"; string vModelChangePath = "D:\\Hisence\\config\\chinese.json"; - if (File.Exists(vBarPath) && File.Exists(vCam1OnePath) && File.Exists(vCam1TwoPath) && File.Exists(vModelChangePath)) + string LablePathstr = "D:\\Hisence\\ClassName.txt";//ǩ· + string LablePathButtonstr = "D:\\Hisence\\ClassNameButton.txt";//ǩ· + if (File.Exists(LablePathButtonstr) && File.Exists(vBarPath) && File.Exists(vCam1OnePath) && File.Exists(vCam1TwoPath) && File.Exists(vModelChangePath)) { + BarPath = vBarPath; Cam1OnePath = vCam1OnePath; Cam1TwoPath = vCam1TwoPath; @@ -177,17 +196,20 @@ namespace HisenceYoloDetection this.WindowState = FormWindowState.Maximized; string Dectionstr = "D:\\Hisence\\best.onnx"; + string DectionButtonstr = "D:\\Hisence\\HisenceButton.onnx"; string CountryStr = "D:\\Hisence\\config\\chinese.json"; - if (File.Exists(Dectionstr) && File.Exists(CountryStr)) + if (File.Exists(LablePathstr) && File.Exists(Dectionstr) && File.Exists(CountryStr) && File.Exists(DectionButtonstr)) { + LablePath = LablePathstr; } else { - MessageBox.Show("" + Dectionstr + " " + CountryStr + "ģ"); + MessageBox.Show("" + Dectionstr + " " + CountryStr + " " + LablePathstr + "ģ"); return; } //ʼ simboObjectDetection.Load(Dectionstr, "CPU", "images", 640, 640); + simboObjectDetButton.Load(DectionButtonstr, "CPU", "images", 640, 640); paddleOcrModelCountry.Load(CountryStr, "CPU"); paddleOcrModel.Load(CountryStr, "CPU"); IfChangeLanguage = CountryStr; @@ -195,7 +217,6 @@ namespace HisenceYoloDetection StartDecBtn.Enabled = false; - //myThread = new Thread(doWork); myDelegateUI = new MyDelegateUI(initAll);//ί @@ -206,12 +227,6 @@ namespace HisenceYoloDetection //ʼPLC melsecPLCTCPDriver.Start(); - - - - //bool ismatch = IsMatchOcrText("WF3S7021BB", strMatListListOne); - //ص - melsecPLCTCPDriver.Heartbeat -= PLcHeratAdress; melsecPLCTCPDriver.Heartbeat += PLcHeratAdress; @@ -441,10 +456,6 @@ namespace HisenceYoloDetection 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) { @@ -516,19 +527,20 @@ namespace HisenceYoloDetection } } + /// /// ȫͼϴ» ü֮ OCRʶĽ /// /// ȫͼͼƬ /// ȫͼƬϵĿ궨λλο /// صĶλĽ - private void InsertSqlRunData(ref Mat currentMatC, MLResult cam1TwoML, ref List strMatListList, ref PaddleOcrModel IOcrModel) + private void InsertSqlRunData2(ref Mat currentMatC, MLResult cam1TwoML, ref List strMatListList, ref PaddleOcrModel IOcrModel) { - + #if true - try + try { List mats = new List(); @@ -547,14 +559,17 @@ namespace HisenceYoloDetection //OCRʶüͼƬ MLRequest reqcut = new MLRequest(); reqcut.currentMat = matroi.Clone(); - MLResultModel mLcut = IOcrModel.RunInferenceFixed(reqcut); + MLResult mLcut = IOcrModel.RunInferenceFixed(reqcut); for (int j = 0; j < mLcut.ResultDetails.Count; j++) { string jdetial = mLcut.ResultDetails[j].LabelDisplay; - strMatListList.Add(jdetial); - OcrTextinsert += jdetial + "##"; + string result = Regex.Replace(jdetial, "[ \\[ \\] \\^ \\-_*DD(^)$%~!@#$&%+=<>!??:?`,.;/\"-]", ""); + + + strMatListList.Add(result); + OcrTextinsert += result + "##"; } @@ -570,7 +585,6 @@ namespace HisenceYoloDetection } - /// /// ݿӦOCRıǷʶı /// @@ -581,12 +595,12 @@ namespace HisenceYoloDetection { try { - xKNow = GetModeFromBar(WashBar);//ݿвѯֵ + List strMatListListB = new List(); - if (xKNow.OcrText.Contains("##")) + if (WashBar.Contains("##")) { - string[] sArray = Regex.Split(xKNow.OcrText, "##", RegexOptions.IgnoreCase); + string[] sArray = Regex.Split(WashBar, "##", RegexOptions.IgnoreCase); for (int i = 0; i < sArray.Count(); i++) @@ -615,6 +629,45 @@ namespace HisenceYoloDetection return false; } } + + private bool IsFuzzyMatchOcrText(string WashBar, List DetMatstrList) + { + try + { + + List strMatListListB = new List(); + if (WashBar.Contains("##")) + { + + string[] sArray = Regex.Split(WashBar, "##", RegexOptions.IgnoreCase); + + + for (int i = 0; i < sArray.Count(); i++) + { + if (sArray[i] != "") + { + strMatListListB.Add(sArray[i]); + } + + + } + + + } + var firstNotSecond = DetMatstrList.Intersect(strMatListListB, StringComparer.OrdinalIgnoreCase).ToList(); + //var secondNotFirst = strMatListListB.Except(DetMatstrList, StringComparer.OrdinalIgnoreCase).ToList(); + if (firstNotSecond.Count() > (strMatListListB.Count) / 2) + { + return true; + } + return false; + + } + catch (Exception ex) + { + return false; + } + } /// /// ʵʱƶģ /// @@ -900,10 +953,10 @@ namespace HisenceYoloDetection myLog("һβɼͼ", DateTime.Now); //ƶģ βĵַ Ƿǰƶ - MoveToP(8974, 0, 0); + MoveToP(8974, 0, 0); + // Thread.Sleep(2000);//ɾ - List DisList = new List(); for (int i = 0; i < 5; i++) @@ -918,24 +971,27 @@ namespace HisenceYoloDetection double disreal = average * (-0.54054) + 1324.3232; //-׼=Ҫƶľ double dismove = disreal - 876; - if(dismove>0&& dismove<4000) + if (dismove > 0 && dismove < 4000) { MoveToP(8974, 0, (int)(dismove)); } + Thread.Sleep(2000);//ɾ Thread.Sleep(500); Cam1.SnapshotCount = 0; Cam1.Snapshot(); + IfCam2Triger = true; Cam2.SnapshotCount = 0; Cam2.Snapshot(); - // myLog("ڶβɼͼ", DateTime.Now); + myLog("ڶβɼͼ", DateTime.Now); //if (xKNow != null) //{ // MoveToP(xKNow.MoveTwoX, xKNow.MoveTwoY, xKNow.MoveTwoZ); //} - // currentXP = 54964; - MoveToP(54964, 0, (int)(dismove)); + //currentXP = 54964; + //Thread.Sleep(2000);//ɾ + MoveToP(54964, 0, (int)(dismove)); Cam1.Snapshot(); - MoveToP(8974, 0, 0); + MoveToP(8974, 0, 0); //if (xKNow != null) //{ // MoveToP(xKNow.MoveX, xKNow.MoveY, xKNow.MoveZ); @@ -1004,7 +1060,9 @@ namespace HisenceYoloDetection //һ if (SnapshotCount == 1) { - // Mat mat = Cv2.ImRead("F:\\ϴ»\\cam1\\2024517161641.jpg"); + // Mat mat = Cv2.ImRead("D:\\Hisence\\1\\202451716511.jpg"); + //Mat mat = Cv2.ImRead("D:\\Hisence\\\\Lp\\2024517171911.jpg"); + //Cam1ImgOne = mat; Cam1ImgOne = cameraMat; IfCam1OneTriger = true; originMatShow.Image = cameraMat.ToBitmap(); @@ -1015,7 +1073,9 @@ namespace HisenceYoloDetection //ڶ if (SnapshotCount == 2) { - // Mat mat = Cv2.ImRead("F:\\ϴ»\\cam1\\2024517164541.jpg"); + // Mat mat = Cv2.ImRead("D:\\Hisence\\1\\2024517164541.jpg"); + //Mat mat = Cv2.ImRead("D:\\Hisence\\\\Lp\\002.jpg"); + //Cam1ImgTwo = mat; Cam1ImgTwo = cameraMat; IfCam1TwoTriger = true; @@ -1042,15 +1102,15 @@ namespace HisenceYoloDetection { Directory.CreateDirectory(fitImageFolder); } - - // Mat mat = Cv2.ImRead("F:\\ϴ»\\cam1\\2024517161641.jpg"); - Cam2ImgShowBar = cameraMat; - IfCam2Triger = true; - originMat2Show.Image = cameraMat.ToBitmap(); - //pictureBox1.Image = cameraMat.ToBitmap(); + + // Mat mat = Cv2.ImRead("F:\\ϴ»\\cam1\\2024517161641.jpg"); + Cam2ImgShowBar = cameraMat; + IfCam2Triger = true; + originMat2Show.Image = cameraMat.ToBitmap(); + //pictureBox1.Image = cameraMat.ToBitmap(); + - pictureBox2.Image = cameraMat.ToBitmap(); @@ -1065,7 +1125,7 @@ namespace HisenceYoloDetection /// public void ReadyDetect() { - Task.Run(() => + Task.Run((Action)(() => { Thread.CurrentThread.Priority = ThreadPriority.Highest; while (true) @@ -1079,19 +1139,36 @@ namespace HisenceYoloDetection //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);//ݿвѯֵ + // req.currentMat = Cv2.ImRead("D:\\Hisence\\\\Lp\\202453015229201.jpg"); + MLResult mL = paddleOcrModelCountry.RunInferenceFixed(req); + //ʶַ + string IOcrBAr = ""; + for (int v = 0; v < Enumerable.Count(mL.ResultDetails); v++) + { + string iv = mL.ResultDetails[v].LabelDisplay; + string result = Regex.Replace(iv, "[ \\[ \\] \\^ \\-_*DD(^)$%~!@#$&%+=<>!??:?`,.;/\"-]", ""); + + IOcrBAr += result; + } + //IOcrBAr = "LR1006G4SILVERWJ060480U0SW901N120105"; + //ݿȶ + xKNow = GetModeFromBar(IOcrBAr);//ݿвѯֵ + List xkWordList = ManagerModelHelper.GetModeWordFromBar(IOcrBAr); + if (xkWordList.Count() == 1) + { + xK_HisenceSQLWord = xkWordList[0]; + } + + if (xKNow.OcrBar == null) { myLog("δƥɹ" + IfChangeLanguage, DateTime.Now); break; } - if (xKNow.OcrText != "" && xKNow.Detect != "") + if ( xKNow.Detect != "") { //ʱеϴ»Ǻ֮ǰһģ - if (IfChangeLanguage == mL.WashMachineBar) + if (IfChangeLanguage == IOcrBAr) { } @@ -1102,7 +1179,7 @@ namespace HisenceYoloDetection { paddleOcrModel.Load(xKNow.OcrParm, "CPU"); - IfChangeLanguage = mL.WashMachineBar; + IfChangeLanguage = IOcrBAr; } } @@ -1120,6 +1197,8 @@ namespace HisenceYoloDetection //1ڶ if (IfCam1TwoTriger && bBarTriger) { + XK_HisenceWord xK_MatchDet = new XK_HisenceWord(); + xK_MatchDet.TwoIFWhile = xK_HisenceSQLWord.TwoIFWhile; AllDsums++; // MLRequest req = new MLRequest(); @@ -1127,46 +1206,57 @@ namespace HisenceYoloDetection req.ResizeWidth = 640; req.ResizeHeight = 640; req.Score = 0.3f; - req.in_lable_path = "D:\\Hisence\\ClassName.txt";//ǩ· + req.in_lable_path = LablePath;//ǩ· req.confThreshold = 0.3f;//ģŶ req.iouThreshold = 0.4f;//IOU req.out_node_name = "output"; MLResult mL = simboObjectDetection.RunInferenceFixed(req); - DateTime dt = DateTime.Now; + MLResult mLButton = simboObjectDetButton.RunInferenceFixed(req); + + DateTime dt = DateTime.Now; //еĿü ʶַԱַ - List strMatListListOne = new List(); + List strMatListOne = new List(); + List strMatFuzzyListOne = new List(); Mat mResultCut = req.currentMat.Clone(); + Mat mCut = new Mat(); + ManagerModelHelper.InsertSqlRunDataButton(false,ref mCut, ref mResultCut, mL, mLButton, ref xK_MatchDet, /*ref strMatListOne, ref strMatFuzzyListOne, */ref paddleOcrModel); - InsertSqlRunData(ref mResultCut, mL, ref strMatListListOne, ref paddleOcrModel); + if(mL.ResultMap!=null) + { + 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; - - 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.in_lable_path = LablePath;//ǩ· req2.confThreshold = 0.3f;//ģŶ req2.iouThreshold = 0.4f;//IOU req2.out_node_name = "output"; MLResult mL2 = simboObjectDetection.RunInferenceFixed(req2); - List strMatListListTwo = new List(); + List strMatListTwo = new List(); + List strMatFuzzyListTwo = 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; + ManagerModelHelper.InsertSqlRunData(false, ref mResultCut2, mL2, ref xK_MatchDet, /*ref strMatListTwo, ref strMatFuzzyListTwo,*/ ref paddleOcrModel); - //ִбȶ ģ23һ + if (mL2.ResultMap != null) + { + 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; + } + + //ִжλ string[] listLabels = xKNow.Detect.Split(","); MLResult MLsum = mL; for (int i = 0; i < mL2.ResultDetails.Count; i++) { - MLsum.ResultDetails.Add(mL2.ResultDetails[i]); + MLsum.ResultDetails.Add((DetectionResultDetail)mL2.ResultDetails[i]); } string[] RealLabels = new string[MLsum.ResultDetails.Count]; string detstr = ""; @@ -1183,47 +1273,23 @@ namespace HisenceYoloDetection } } + ///ִбȶ Сͼ + bool MatchStr = ManagerModelHelper.IsMatchSQLText(ref mCut, ref xK_HisenceSQLWord, ref xK_MatchDet); + + + + 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) + if (MatchStr) { 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); + InsertXK_HisenceWordMatchData(xK_MatchDet, true); OKOrNGShow.Image = OKbitmap; } else @@ -1231,9 +1297,7 @@ namespace HisenceYoloDetection 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); + InsertXK_HisenceWordMatchData(xK_MatchDet, false); OKOrNGShow.Image = NGbitmap; } @@ -1255,7 +1319,7 @@ namespace HisenceYoloDetection Thread.Sleep(10); } - }); + })); } /// @@ -1268,10 +1332,20 @@ namespace HisenceYoloDetection //ģ DataSet ds = SQLiteHelper.Query($"select * from XK_Hisence where OCRBar='{SkBar}' "); + + + + XKHisence XK_hisence = new XKHisence(); //cbx.DataSource = ds; DataTableReader rdr = ds.CreateDataReader(); + + //autxRecords = new List(); + + + + //cbx.Rows.Clear(); while (rdr.Read())//ȡ @@ -1290,6 +1364,7 @@ namespace HisenceYoloDetection XK_hisence.MoveTwoZ = (int)rdr["MoveTwoZ"]; XK_hisence.OcrParm = (string)rdr["OcrParm"]; XK_hisence.Language = (string)rdr["Language"]; + XK_hisence.FuzzyOcrText = (string)rdr["FuzzyOcrText"]; //xKHisences.Add(XK_hisence); return XK_hisence; //additem(XK_hisence); @@ -1482,10 +1557,7 @@ namespace HisenceYoloDetection 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) @@ -1767,6 +1839,8 @@ namespace HisenceYoloDetection private void InsertBtn_Click(object sender, EventArgs e) { + + try { string type = TypeBox.Text; @@ -1778,6 +1852,20 @@ namespace HisenceYoloDetection string movetwoX = moveTwoXbox.Text; string movetwoY = moveTwoYbox.Text; string movetwoZ = moveTwoZbox.Text; + bool whiteBan = true; + if (WhiteBanCbx.CheckState == CheckState.Checked)//ѡ + { + whiteBan = true; + + } + else if (WhiteBanCbx.CheckState == CheckState.Unchecked)//ûѡ + { + whiteBan = false; + } + else + { + whiteBan = false; + } if (!Regex.IsMatch(moveX, @"^[0-9]+$")) { @@ -1810,7 +1898,7 @@ namespace HisenceYoloDetection return; } - if (OcrBar != "" && Detect != "" && BarPath != "" && Cam1OnePath != "" && Cam1TwoPath != "" && ModelChangePath != "") + if (Detect != "" && BarPath != "" && Cam1OnePath != "" && Cam1TwoPath != "" && ModelChangePath != "") { int HmoveX = (int)Convert.ToInt64(moveX); int HmoveY = (int)Convert.ToInt64(moveY); @@ -1818,7 +1906,7 @@ namespace HisenceYoloDetection 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); + InsertXK_Hisence(whiteBan,HmoveX, HmoveY, HmoveZ, HmovetwoX, HmovetwoY, HmovetwoZ); } @@ -1830,82 +1918,117 @@ namespace HisenceYoloDetection } catch (Exception es) { + MessageBox.Show(es.Message); } } - public void InsertXK_Hisence(int MoveX, int MoveY, int MoveZ, int MoveTwoX, int MoveTwoY, int MoveTwoZ) + public void InsertXK_Hisence(bool ifwhiteBan,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); + MLResult mL2 = paddleOcrModelCountry.RunInferenceFixed(OcrBari); + string IOcrBAr = ""; for (int v = 0; v < mL2.ResultDetails.Count(); v++) { - string iv = mL2.ResultDetails[v].LabelDisplay; - IOcrBAr += iv; + string ivi = mL2.ResultDetails[v].LabelDisplay; + string result = Regex.Replace(ivi, "[ \\[ \\] \\^ \\-_*DD(^)$%~!@#$&%+=<>!??:?`,.;/\"-]", ""); + + IOcrBAr += result; } + OcrBarBox.Text = IOcrBAr; + XK_HisenceWord xkWord = new XK_HisenceWord(); + xkWord.OcrBar = IOcrBAr; + xkWord.TwoIFWhile = ifwhiteBan; using (StreamWriter sw = new StreamWriter("D://123.log", true)) { sw.WriteLine("\n"); sw.WriteLine(IOcrBAr); sw.Flush(); } + + + //еĿü ʶַԱַ + + + + // + + + + + + //ӵһȫͼΧĿȻOCRʶ 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.in_lable_path = LablePath;//ǩ· 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"); + MLResult mLButton = simboObjectDetButton.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(); + //} + List strMatListOne = new List(); + List strMatFuzzyListOne = new List(); Mat mResultCut = CamOneI.currentMat.Clone(); + Mat mCut = new Mat(); + ManagerModelHelper.InsertSqlRunDataButton(true,ref mCut, ref mResultCut, mL3, mLButton,ref xkWord, /*ref strMatListOne, ref strMatFuzzyListOne,*/ ref paddleOcrModel); + - 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.in_lable_path = LablePath;//ǩ· 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"); + //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(); + //} + List strMatListTwo = new List(); + List strMatFuzzyListTwo = new List(); Mat mResultCut2 = CamTwoI.currentMat.Clone(); - InsertSqlRunData(ref mResultCut2, mL4, ref strMatListListTwo, ref IpaddleOcrModel); + ManagerModelHelper.InsertSqlRunData(true, ref mResultCut2, mL4, ref xkWord,/* ref strMatListTwo, ref strMatFuzzyListTwo,*/ ref paddleOcrModel); + + + + InsertXKHisenceWordData( xkWord);//ؼֱвһ //ı - string OcrTextinsert = ""; - List bingji = strMatListListOne.Union(strMatListListTwo).ToList();//ȫ - for (int j = 0; j < bingji.Count; j++) - { - string jdetial = bingji[j]; - OcrTextinsert += jdetial + "##"; - } + List bingji = strMatListOne.Union(strMatListTwo).ToList();//ȫ + List Fuzzybingji = strMatFuzzyListOne.Union(strMatFuzzyListTwo).ToList();//ȫ + string OcrTextone = bingji.Join("##"); + string OcrTextTwo = Fuzzybingji.Join("##"); + + //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; + + //ҵʶ + MLResult MLsum = mL3; for (int v = 0; v < mL4.ResultDetails.Count; v++) { MLsum.ResultDetails.Add(mL4.ResultDetails[v]); @@ -1919,27 +2042,237 @@ namespace HisenceYoloDetection } else { - detstr += MLsum.ResultDetails[v].LabelName ; + detstr += MLsum.ResultDetails[v].LabelName; } } - - XKHisence xK = new XKHisence("1", IOcrBAr, MoveX, MoveY, MoveZ, detstr, OcrTextinsert, MoveTwoX, MoveTwoY, MoveTwoZ, ModelChangePath, ""); - - + DateTime dt2 = DateTime.Now; + XKHisence xK = new XKHisence("1", IOcrBAr, MoveX, MoveY, MoveZ, detstr, OcrTextone, MoveTwoX, MoveTwoY, MoveTwoZ, ModelChangePath, "", OcrTextTwo); + //string log="D:\\Hisence\\detImages\\" + dt2.Year.ToString() + dt2.Month.ToString() + dt2.Day.ToString() + dt2.Hour.ToString() + dt2.Minute.ToString() + dt2.Millisecond.ToString() + "2result.log"; + // using (StreamWriter sw=new StreamWriter(log, true)) + // { + // // sw.WriteLine(xK.OcrBar+"\n"); + // sw.WriteLine(xK.OcrText); + // sw.WriteLine(xK.FuzzyOcrText); + // } //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 + "')"; + 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 + "','" + xK.FuzzyOcrText + "')"; int i = SQLiteHelper.ExecuteSql(sql); if (i == 1) { - MessageBox.Show("һ"); + MessageBox.Show("XK_Hisenceһ"); } //bool ismatch = IsMatchOcrText("WF3S7021BB", strMatListListOne); //ص } + public void InsertXKHisenceWordData(XK_HisenceWord xkWord) + { + StringBuilder strSql = new StringBuilder(); + strSql.Append("insert into XK_HisenceWord("); + strSql.Append("OcrBar,OneblockPath,OneblockMainWord,OneblockText,TwoRect,TwoIFWhile,TwoblockPath,TwoblockMainWord,TwoblockText,ThreeblockPath," + + "ThreeblockMainWord,ThreeblockText,FourblockPath,FourblockMainWord,FourblockText,FiveblockPath,FiveblockMainWord,FiveblockText," + + "SixblockPath,SixblockMainWord,SixblockText,SevenblockPath,SevenblockMainWord,SevenblockText,EightblockPath,EightblockMainWord,EightblockText)"); + strSql.Append(" values ("); + strSql.Append("@OcrBar,@OneblockPath,@OneblockMainWord,@OneblockText,@TwoRect,@TwoIFWhile,@TwoblockPath,@TwoblockMainWord,@TwoblockText,@ThreeblockPath," + + "@ThreeblockMainWord,@ThreeblockText,@FourblockPath,@FourblockMainWord,@FourblockText,@FiveblockPath,@FiveblockMainWord,@FiveblockText," + + "@SixblockPath,@SixblockMainWord,@SixblockText,@SevenblockPath,@SevenblockMainWord,@SevenblockText,@EightblockPath,@EightblockMainWord,@EightblockText)"); + SQLiteParameter[] parameters = { + new SQLiteParameter("@OcrBar", DbType.String), + new SQLiteParameter("@OneblockPath", DbType.String), + new SQLiteParameter("@OneblockMainWord", DbType.String), + new SQLiteParameter("@OneblockText", DbType.String), + new SQLiteParameter("@TwoRect",DbType.String), + new SQLiteParameter("@TwoIFWhile",DbType.String), + new SQLiteParameter("@TwoblockPath", DbType.String), + new SQLiteParameter("@TwoblockMainWord",DbType.String), + new SQLiteParameter("@TwoblockText", DbType.String), + new SQLiteParameter("@ThreeblockPath", DbType.String), + new SQLiteParameter("@ThreeblockMainWord", DbType.String), + new SQLiteParameter("@ThreeblockText", DbType.String), + new SQLiteParameter("@FourblockPath", DbType.String), + new SQLiteParameter("@FourblockMainWord", DbType.String), + new SQLiteParameter("@FourblockText", DbType.String), + new SQLiteParameter("@FiveblockPath", DbType.String), + new SQLiteParameter("@FiveblockMainWord", DbType.String), + new SQLiteParameter("@FiveblockText", DbType.String), + new SQLiteParameter("@SixblockPath", DbType.String), + new SQLiteParameter("@SixblockMainWord", DbType.String), + new SQLiteParameter("@SixblockText", DbType.String), + new SQLiteParameter("@SevenblockPath", DbType.String), + new SQLiteParameter("@SevenblockMainWord", DbType.String), + new SQLiteParameter("@SevenblockText", DbType.String), + new SQLiteParameter("@EightblockPath", DbType.String), + new SQLiteParameter("@EightblockMainWord", DbType.String), + new SQLiteParameter("@EightblockText", DbType.String)}; + + parameters[0].Value = xkWord.OcrBar; + parameters[1].Value = xkWord.OneblockPath; + parameters[2].Value = xkWord.OneblockMainWord; + parameters[3].Value = xkWord.OneblockText; + + parameters[4].Value = xkWord.TwoRect; + parameters[5].Value = xkWord.TwoIFWhile; + parameters[6].Value = xkWord.TwoblockPath; + parameters[7].Value = xkWord.TwoblockMainWord; + parameters[8].Value = xkWord.TwoblockText; + + parameters[9].Value = xkWord.ThreeblockPath; + parameters[10].Value = xkWord.ThreeblockMainWord; + parameters[11].Value = xkWord.ThreeblockText; + + parameters[12].Value = xkWord.FourblockPath; + parameters[13].Value = xkWord.FourblockMainWord; + parameters[14].Value = xkWord.FourblockText; + + parameters[15].Value = xkWord.FiveblockPath; + parameters[16].Value = xkWord.FiveblockMainWord; + parameters[17].Value = xkWord.FiveblockText; + + + parameters[18].Value = xkWord.SixblockPath; + parameters[19].Value = xkWord.SixblockMainWord; + parameters[20].Value = xkWord.SixblockText; + + parameters[21].Value = xkWord.SevenblockPath; + parameters[22].Value = xkWord.SevenblockMainWord; + parameters[23].Value = xkWord.SevenblockText; + + parameters[24].Value = xkWord.EightblockPath; + parameters[25].Value = xkWord.EightblockMainWord; + parameters[26].Value = xkWord.EightblockText; + int iv = SQLiteHelper.ExecuteSql(strSql.ToString(), parameters); + if (iv == 1) + { + MessageBox.Show("ؼXK_HisenceWordһ"); + } + } + public void InsertXK_HisenceWordMatchData(XK_HisenceWord xkWord,bool ifMatch) + { + StringBuilder strSql = new StringBuilder(); + strSql.Append("insert into XK_HisenceWordMatch("); + strSql.Append("OcrBar,OneblockPath,OneblockMainWord,OneblockText,TwoRect,TwoIFWhile,TwoblockPath,TwoblockMainWord,TwoblockText,ThreeblockPath," + + "ThreeblockMainWord,ThreeblockText,FourblockPath,FourblockMainWord,FourblockText,FiveblockPath,FiveblockMainWord,FiveblockText," + + "SixblockPath,SixblockMainWord,SixblockText,SevenblockPath,SevenblockMainWord,SevenblockText,EightblockPath,EightblockMainWord,EightblockText,Datetime,IfMatch)"); + strSql.Append(" values ("); + strSql.Append("@OcrBar,@OneblockPath,@OneblockMainWord,@OneblockText,@TwoRect,@TwoIFWhile,@TwoblockPath,@TwoblockMainWord,@TwoblockText,@ThreeblockPath," + + "@ThreeblockMainWord,@ThreeblockText,@FourblockPath,@FourblockMainWord,@FourblockText,@FiveblockPath,@FiveblockMainWord,@FiveblockText," + + "@SixblockPath,@SixblockMainWord,@SixblockText,@SevenblockPath,@SevenblockMainWord,@SevenblockText,@EightblockPath,@EightblockMainWord,@EightblockText,@Datetime,@IfMatch)"); + SQLiteParameter[] parameters = { + new SQLiteParameter("@OcrBar", DbType.String), + new SQLiteParameter("@OneblockPath", DbType.String), + new SQLiteParameter("@OneblockMainWord", DbType.String), + new SQLiteParameter("@OneblockText", DbType.String), + new SQLiteParameter("@TwoRect",DbType.String), + new SQLiteParameter("@TwoIFWhile",DbType.String), + new SQLiteParameter("@TwoblockPath", DbType.String), + new SQLiteParameter("@TwoblockMainWord",DbType.String), + new SQLiteParameter("@TwoblockText", DbType.String), + new SQLiteParameter("@ThreeblockPath", DbType.String), + new SQLiteParameter("@ThreeblockMainWord", DbType.String), + new SQLiteParameter("@ThreeblockText", DbType.String), + new SQLiteParameter("@FourblockPath", DbType.String), + new SQLiteParameter("@FourblockMainWord", DbType.String), + new SQLiteParameter("@FourblockText", DbType.String), + new SQLiteParameter("@FiveblockPath", DbType.String), + new SQLiteParameter("@FiveblockMainWord", DbType.String), + new SQLiteParameter("@FiveblockText", DbType.String), + new SQLiteParameter("@SixblockPath", DbType.String), + new SQLiteParameter("@SixblockMainWord", DbType.String), + new SQLiteParameter("@SixblockText", DbType.String), + new SQLiteParameter("@SevenblockPath", DbType.String), + new SQLiteParameter("@SevenblockMainWord", DbType.String), + new SQLiteParameter("@SevenblockText", DbType.String), + new SQLiteParameter("@EightblockPath", DbType.String), + new SQLiteParameter("@EightblockMainWord", DbType.String), + new SQLiteParameter("@EightblockText", DbType.String), + new SQLiteParameter("@Datetime", DbType.String), + new SQLiteParameter("@IfMatch", DbType.Boolean)}; + + parameters[0].Value = xkWord.OcrBar; + parameters[1].Value = xkWord.OneblockPath; + parameters[2].Value = xkWord.OneblockMainWord; + parameters[3].Value = xkWord.OneblockText; + + parameters[4].Value = xkWord.TwoRect; + parameters[5].Value = xkWord.TwoIFWhile; + parameters[6].Value = xkWord.TwoblockPath; + parameters[7].Value = xkWord.TwoblockMainWord; + parameters[8].Value = xkWord.TwoblockText; + + parameters[9].Value = xkWord.ThreeblockPath; + parameters[10].Value = xkWord.ThreeblockMainWord; + parameters[11].Value = xkWord.ThreeblockText; + + parameters[12].Value = xkWord.FourblockPath; + parameters[13].Value = xkWord.FourblockMainWord; + parameters[14].Value = xkWord.FourblockText; + + parameters[15].Value = xkWord.FiveblockPath; + parameters[16].Value = xkWord.FiveblockMainWord; + parameters[17].Value = xkWord.FiveblockText; + + + parameters[18].Value = xkWord.SixblockPath; + parameters[19].Value = xkWord.SixblockMainWord; + parameters[20].Value = xkWord.SixblockText; + + parameters[21].Value = xkWord.SevenblockPath; + parameters[22].Value = xkWord.SevenblockMainWord; + parameters[23].Value = xkWord.SevenblockText; + + parameters[24].Value = xkWord.EightblockPath; + parameters[25].Value = xkWord.EightblockMainWord; + parameters[26].Value = xkWord.EightblockText; + + parameters[27].Value = DateTime.Now; + parameters[28].Value = ifMatch; + int iv = SQLiteHelper.ExecuteSql(strSql.ToString(), parameters); + if (iv == 1) + { + MessageBox.Show("ؼXK_HisenceWordMatchһ"); + } + } + + public void InsertXKHisenceDET(XKHisence xkWord) + { + StringBuilder strSql = new StringBuilder(); + strSql.Append("insert into XKHisenceDet("); + strSql.Append("Type,OcrBar,MoveX,MoveY,MoveZ,Detect,OcrText,MoveTwoX,MoveTwoY,MoveTwoZ,Datetime,IfMatch)"); + strSql.Append(" values ("); + strSql.Append("@Type,@OcrBar,@MoveX,@MoveY,@MoveZ,@Detect,@OcrText,@MoveTwoX,@MoveTwoY,@MoveTwoZ,@Datetime,@IfMatch)"); + SQLiteParameter[] parameters = { + new SQLiteParameter("@OcrBar", DbType.String), + new SQLiteParameter("@MoveX", DbType.String), + new SQLiteParameter("@MoveY", DbType.String), + new SQLiteParameter("@MoveZ", DbType.String), + new SQLiteParameter("@Detect",DbType.String), + new SQLiteParameter("@OcrText", DbType.String), + new SQLiteParameter("@MoveTwoX",DbType.String), + new SQLiteParameter("@MoveTwoY", DbType.String), + new SQLiteParameter("@MoveTwoZ", DbType.String), + new SQLiteParameter("@Datetime", DbType.String), + new SQLiteParameter("@IfMatch", DbType.String)}; + parameters[0].Value = xkWord.OcrBar; + parameters[1].Value = xkWord.MoveX; + parameters[2].Value = xkWord.MoveY; + parameters[3].Value = xkWord.MoveZ; + + parameters[4].Value = xkWord.Detect; + parameters[5].Value = xkWord.OcrText; + parameters[6].Value = xkWord.MoveTwoX; + parameters[7].Value = xkWord.MoveTwoY; + + parameters[8].Value = xkWord.MoveTwoZ; + + int iv = SQLiteHelper.ExecuteSql(strSql.ToString(), parameters); + if (iv == 1) + { + MessageBox.Show("ؼXK_HisenceWordһ"); + } + } private void queryALLBtn_Click(object sender, EventArgs e) { try @@ -2043,5 +2376,10 @@ namespace HisenceYoloDetection tbExposure2.Text = Cam2.dvpGetExposure().ToString(); tbGain2.Text = Cam2.dvpGetAnalogGain().ToString(); } + + private void panel2_Paint(object sender, PaintEventArgs e) + { + + } } } diff --git a/HisenceYoloDetection/ManagerModelHelper.cs b/HisenceYoloDetection/ManagerModelHelper.cs new file mode 100644 index 0000000..04c595e --- /dev/null +++ b/HisenceYoloDetection/ManagerModelHelper.cs @@ -0,0 +1,479 @@ +using OpenCvSharp; +using System; +using System.Collections.Generic; +using System.Data.SQLite; +using System.Data; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using XKRS.Device.SimboVision.SimboHelper; +using System.Diagnostics.Eventing.Reader; +using static System.Runtime.InteropServices.JavaScript.JSType; +using System.Drawing; +using Microsoft.VisualBasic; + +namespace HisenceYoloDetection +{ + + public static class ManagerModelHelper + { + public static string RootPath = "D:\\Hisence\\SQLImages\\"; + + + + + /// + /// 全图洗衣机 裁剪之后 OCR识别的结果 + /// + /// + /// + /// 全图图片 + /// 全局图片上的目标定位结果(包括定位矩形框) + /// + /// + /// 返回的定位框的结果 + /// + /// + public static void InsertSqlRunDataButton(bool saveimage,ref Mat CutMat, ref Mat currentMatC, MLResult cam1TwoML, MLResult cam1Button, ref XK_HisenceWord xK_HisenceWord, /*ref List strMatList, ref List strMatRefList, */ref PaddleOcrModel IOcrModel) + { +#if true + //try + //{ + + Mat mResultCut = currentMatC.Clone(); + Rect areaBlack=new Rect(); + //旋钮的位置 + if (cam1Button.ResultDetails.Count == 1) + { + Mat mResultCuti = mResultCut.Clone(); + int rectsx = cam1Button.ResultDetails[0].Rect.X; + int rectsy = cam1Button.ResultDetails[0].Rect.Y; + int rectsWidth = cam1Button.ResultDetails[0].Rect.Width; + int rectsHeight = cam1Button.ResultDetails[0].Rect.Height; + areaBlack = new Rect(rectsx, rectsy, rectsWidth, rectsHeight); + + } + 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; + + string blockIndex = cam1TwoML.ResultDetails[i].LabelDisplay; + Rect area2 = new Rect(); + if (blockIndex == "2")//根据旋钮扩大范围 + { + areaBlack.X -= rectsx; + areaBlack.Y -= rectsy; + area2 = areaBlack; + string TwoRectStr= CheckDiffSciHelper.rectChangeStr(area2); + xK_HisenceWord.TwoRect = TwoRectStr; + //Mat matCutblack = new Mat(mResultCuti, area2); + //if((bool)xK_HisenceWord.TwoIFWhile) + //{ + // matCutblack.SetTo(Scalar.Black); + //} + //else + //{ + // matCutblack.SetTo(Scalar.Black); + //} + + + //rectsx -= rectsWidth; + //rectsy -= 50; + //rectsWidth = rectsWidth + 2 * rectsWidth; + //rectsHeight = rectsHeight + 2 + 50; + + Rect area = new Rect(rectsx, rectsy, rectsWidth, rectsHeight); + + Mat matCut = new Mat(mResultCuti, area); + CutMat = matCut.Clone(); + + //Mat TwoCut = new Mat(mResultCuti, area2); + //TwoCut.SetTo(Scalar.Black); + //OCR识别裁剪图片 + MLRequest reqcut = new MLRequest(); + reqcut.currentMat = matCut.Clone(); + MLResult mLCut = IOcrModel.RunInferenceFixed(reqcut); + + //if (mLCut.IsSuccess) + //{ + // DateTime dt = DateTime.Now; + // mLCut.ResultMap.Save("D:\\Hisence\\detImages\\OCR" + dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Millisecond.ToString() + "2result.jpg"); + + //} + + BlockChangeFun(saveimage, blockIndex, ref matCut, ref mLCut, ref xK_HisenceWord); + } + else + { + Rect area = new Rect(rectsx, rectsy, rectsWidth, rectsHeight); + + Mat matCut = new Mat(mResultCuti, area); + + //OCR识别裁剪图片 + MLRequest reqcut = new MLRequest(); + reqcut.currentMat = matCut.Clone(); + MLResult mLCut = IOcrModel.RunInferenceFixed(reqcut); + //if (mLCut.IsSuccess) + //{ + // DateTime dt = DateTime.Now; + // mLCut.ResultMap.Save("D:\\Hisence\\detImages\\OCR" + dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Millisecond.ToString() + "2result.jpg"); + + //} + + BlockChangeFun(saveimage, blockIndex, ref matCut, ref mLCut, ref xK_HisenceWord); + } + + + //插入数据库 + + } + + + //} + //catch (Exception ex) + //{ + + //} +#endif + + + } + + /// + /// 全图洗衣机 裁剪之后 OCR识别的结果 + /// + /// 全图图片 + /// 全局图片上的目标定位结果(包括定位矩形框) + /// 返回的定位框的结果 + public static void InsertSqlRunData(bool saveimage, ref Mat currentMatC, MLResult cam1TwoML, ref XK_HisenceWord xK_HisenceWord, /*ref List strMatList, ref List strMatRefList,*/ ref PaddleOcrModel IOcrModel) + { +#if true + //try + //{ + + + Mat mResultCut = currentMatC.Clone(); + + 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; + string blockIndex = cam1TwoML.ResultDetails[i].LabelDisplay; + + + Rect area = new Rect(rectsx, rectsy, rectsWidth, rectsHeight); + Mat matCut = new Mat(mResultCuti, area); + + //OCR识别裁剪图片 + MLRequest reqcut = new MLRequest(); + reqcut.currentMat = matCut.Clone(); + MLResult mLCut = IOcrModel.RunInferenceFixed(reqcut); + //if (mLCut.IsSuccess) + //{ + // DateTime dt = DateTime.Now; + // mLCut.ResultMap.Save("D:\\Hisence\\detImages\\OCR" + dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Millisecond.ToString() + "2result.jpg"); + + //} + + BlockChangeFun(saveimage, blockIndex, ref matCut, ref mLCut, ref xK_HisenceWord); + //插入数据库 + + } + + + //} + //catch (Exception ex) + //{ + + //} +#endif + + + } + + + /// + /// + /// + /// 是否保存 + /// 裁剪的一块索引 + /// 裁剪的一张图片 + /// 裁剪图片的一些信息 + /// 要存储入数据库的东西 + public static void BlockChangeFun(bool saveimage, string blockIndex, ref Mat CutBlockMat, ref MLResult mLcut, ref XK_HisenceWord xK_HisenceWord) + { + string ocrBar = xK_HisenceWord.OcrBar; + //存放关键字和所有字符串 + List OcrTextinsert = new List();//存放关键字 + List OcrFuzzyTextInsert = new List();//存放模糊字 + string CutSavePath = ""; + CombineMessage(saveimage, ocrBar, blockIndex, ref CutBlockMat, ref mLcut, ref OcrTextinsert, ref OcrFuzzyTextInsert, ref CutSavePath); + + switch (blockIndex) + { + case "1"://完全匹配 重量信息 + { + xK_HisenceWord.OneblockPath = CutSavePath; + xK_HisenceWord.OneblockMainWord = OcrTextinsert.Join("##"); + xK_HisenceWord.OneblockText = OcrFuzzyTextInsert.Join("##"); + + } + break; + case "2"://控制面板 匹配 + { + xK_HisenceWord.TwoblockPath = CutSavePath; + xK_HisenceWord.TwoblockMainWord = OcrTextinsert.Join("##"); + xK_HisenceWord.TwoblockText = OcrFuzzyTextInsert.Join("##"); + } + break; + case "3"://第三块板匹配 + { + xK_HisenceWord.ThreeblockPath = CutSavePath; + xK_HisenceWord.ThreeblockMainWord = OcrTextinsert.Join("##"); + xK_HisenceWord.ThreeblockText = OcrFuzzyTextInsert.Join("##"); + } + break; + case "4"://贴纸匹配 + { + xK_HisenceWord.FourblockPath = CutSavePath; + xK_HisenceWord.FourblockMainWord = OcrTextinsert.Join("##"); + xK_HisenceWord.FourblockText = OcrFuzzyTextInsert.Join("##"); + } + break; + case "5"://贴纸匹配 + { + xK_HisenceWord.FiveblockPath = CutSavePath; + xK_HisenceWord.FiveblockMainWord = OcrTextinsert.Join("##"); + xK_HisenceWord.FiveblockText = OcrFuzzyTextInsert.Join("##"); + } + break; + case "6"://贴纸匹配 + { + xK_HisenceWord.SixblockPath = CutSavePath; + xK_HisenceWord.SixblockMainWord = OcrTextinsert.Join("##"); + xK_HisenceWord.SixblockText = OcrFuzzyTextInsert.Join("##"); + } + break; + case "7"://贴纸匹配 + { + xK_HisenceWord.SevenblockPath = CutSavePath; + xK_HisenceWord.SevenblockMainWord = OcrTextinsert.Join("##"); + xK_HisenceWord.SevenblockText = OcrFuzzyTextInsert.Join("##"); + } + break; + case "8"://贴纸匹配 + { + xK_HisenceWord.EightblockPath = CutSavePath; + xK_HisenceWord.EightblockMainWord = OcrTextinsert.Join("##"); + xK_HisenceWord.EightblockText = OcrFuzzyTextInsert.Join("##"); + } + break; + } + + } + /// + /// + /// + /// 是否保存本地图片 + /// 唯一条形码 + /// 区块号 + /// 图像 + /// 图像上的数据 + /// 关键字 + /// 所有字 + /// 图片保存路径 + public static void CombineMessage(bool saveimage, string OcrBar, string blockIndex, ref Mat CutBlockMat, ref MLResult mLcut, ref List OcrTextinsert, ref List OcrFuzzyTextInsert, ref string cutSavepath) + { + //在这里面找到带数字的关键字 将所有字也存放在数据库中 + for (int j = 0; j < mLcut.ResultDetails.Count; j++) + { + string jdetial = mLcut.ResultDetails[j].LabelDisplay; + string result = Regex.Replace(jdetial, "[ \\[ \\] \\^ \\-_*×――(^)$%~!@#$…&%¥—+=<>《》!!???::?`·、。,;,.;/\"‘’“”-]", ""); + if (Regex.IsMatch(result, @"\d")) + { + OcrTextinsert.Add(result); + } + OcrFuzzyTextInsert.Add(result); + } + + if (saveimage) + { + DateTime dt = DateTime.Now; + string namecutSavepath = OcrBar + "\\" + blockIndex + "\\" + OcrBar + "result.jpg"; + + cutSavepath = Path.Combine(RootPath, namecutSavepath); + //得到目录 + if (!Directory.Exists(Path.GetDirectoryName(cutSavepath))) + { + Directory.CreateDirectory(Path.GetDirectoryName(cutSavepath)); + } + + Cv2.ImWrite(cutSavepath, CutBlockMat); + } + + } + + public static List GetModeWordFromBar(string SkBar) + { + List cslist = SQLiteHelper.ExecuteQuery($"select * from XK_HisenceWord where OCRBar='{SkBar}' ", r => new XK_HisenceWord + { + OcrBar = r["OcrBar"].ToString(), + OneblockPath = r["OneblockPath"].ToString(), + OneblockMainWord = r["OneblockMainWord"].ToString(), + OneblockText = r["OneblockText"].ToString(), + TwoRect = r["TwoRect"].ToString(), + TwoIFWhile = r["TwoIFWhile"].ToBool(), + TwoblockPath = r["TwoblockPath"].ToString(), + TwoblockMainWord = r["TwoblockMainWord"].ToString(), + TwoblockText = r["TwoblockText"].ToString(), + ThreeblockPath = r["ThreeblockPath"].ToString(), + ThreeblockMainWord = r["ThreeblockMainWord"].ToString(), + ThreeblockText = r["ThreeblockText"].ToString(), + FourblockPath = r["FourblockPath"].ToString(), + FourblockMainWord = r["FourblockMainWord"].ToString(), + FourblockText = r["FourblockText"].ToString(), + FiveblockPath = r["FiveblockPath"].ToString(), + FiveblockMainWord = r["FiveblockMainWord"].ToString(), + FiveblockText = r["FiveblockText"].ToString(), + SixblockPath = r["SixblockPath"].ToString(), + SixblockMainWord = r["SixblockMainWord"].ToString(), + SixblockText = r["SixblockText"].ToString(), + SevenblockPath = r["SevenblockPath"].ToString(), + SevenblockMainWord = r["SevenblockMainWord"].ToString(), + SevenblockText = r["SevenblockText"].ToString(), + EightblockPath = r["EightblockPath"].ToString(), + EightblockMainWord = r["EightblockMainWord"].ToString(), + EightblockText = r["EightblockText"].ToString() + + }); + return cslist; + + } + public static bool IsMatchSQLText(ref Mat detMat, ref XK_HisenceWord XKSQL, ref XK_HisenceWord XKDet) + { + + try + { + string TwoRectstr=XKSQL.TwoRect; + string oneBlockWordSql = XKSQL.OneblockMainWord; + string twoBlockWordSql = XKSQL.TwoblockMainWord; + string threeBlockWordSql = XKSQL.ThreeblockMainWord; + string fourBlockWordSql = XKSQL.FourblockMainWord; + string fiveBlockWordSql = XKSQL.FiveblockMainWord; + string sixBlockWordSql = XKSQL.SixblockMainWord; + string sevenBlockWordSql = XKSQL.SevenblockMainWord; + string eightBlockWordSql = XKSQL.EightblockMainWord; + + string oneBlockWordDet = XKDet.OneblockMainWord; + string twoBlockWordDet = XKDet.TwoblockMainWord; + string threeBlockWordDet = XKDet.ThreeblockMainWord; + string fourBlockWordDet = XKDet.FourblockMainWord; + string fiveBlockWordDet = XKDet.FiveblockMainWord; + string sixBlockWordDet = XKDet.SixblockMainWord; + string sevenBlockWordDet = XKDet.SevenblockMainWord; + string eightBlockWordDet = XKDet.EightblockMainWord; + + + + bool OneIF = isMatchStr(oneBlockWordSql, oneBlockWordDet); + bool TwoIF = isMatchStr(twoBlockWordSql, twoBlockWordDet); + bool ThreeIF = isMatchStr(threeBlockWordSql, threeBlockWordDet); + bool FourIF = isMatchStr(fourBlockWordSql, fourBlockWordDet); + bool FiveIF = isMatchStr(fiveBlockWordSql, fiveBlockWordDet); + bool SixIF = isMatchStr(sixBlockWordSql, sixBlockWordDet); + bool SenvenIF = isMatchStr(sevenBlockWordSql, sevenBlockWordDet); + bool EightIF = isMatchStr(eightBlockWordSql, eightBlockWordDet); + //第二快 卷积匹配 + string PathSql = XKSQL.TwoblockPath; + // + Rect rectsql = CheckDiffSciHelper.strChangeRect(TwoRectstr); + Rect rectDet = CheckDiffSciHelper.strChangeRect(XKDet.TwoRect); + bool twoif2 = CheckDiffSciHelper.CheckDiffSci(PathSql, detMat, rectsql, rectDet,(bool)XKSQL.TwoIFWhile, "D://"); + //第三块区域一直都是false + if (OneIF && TwoIF && ThreeIF && FourIF && FiveIF && SixIF && SenvenIF && EightIF&& twoif2) + { + return true; + } + else + { + return false; + } + + + + + } + catch (Exception ex) + { + return false; + } + + } + public static bool isMatchStr(string SqlText, string DetText) + { + if (SqlText.Contains("##") && DetText.Contains("##")) + { + // 计算Levenshtein距离 + int distance = LevenshteinDistance(SqlText, DetText); + + // 计算相似度(相似度等于1减去标准化的Levenshtein距离) + double similarity = 1 - ((double)distance / Math.Max(SqlText.Length, DetText.Length)); + bool areEqual = false; + if (similarity<0.5) + { + areEqual = false; + } + else + { + areEqual = true; + } + //string[] sArraysql = Regex.Split(SqlText, "##", RegexOptions.IgnoreCase); + //string[] sArraydet = Regex.Split(DetText, "##", RegexOptions.IgnoreCase); + //bool areEqual = sArraysql.OrderBy(x => x).SequenceEqual(sArraydet.OrderBy(x => x)); + return areEqual; + + } + else if ((SqlText == "" || SqlText == null) && (DetText == "" || DetText == null)) + { + return true; + } + else + { + return false; + } + } + // 计算Levenshtein距离 + static int LevenshteinDistance(string string1, string string2) + { + int[,] dp = new int[string1.Length + 1, string2.Length + 1]; + + for (int i = 0; i <= string1.Length; i++) + dp[i, 0] = i; + + for (int j = 0; j <= string2.Length; j++) + dp[0, j] = j; + + for (int i = 1; i <= string1.Length; i++) + { + for (int j = 1; j <= string2.Length; j++) + { + int cost = string1[i - 1] == string2[j - 1] ? 0 : 1; + + dp[i, j] = Math.Min(Math.Min(dp[i - 1, j] + 1, dp[i, j - 1] + 1), dp[i - 1, j - 1] + cost); + } + } + + return dp[string1.Length, string2.Length]; + } + + + } +} diff --git a/HisenceYoloDetection/MelsecPLCTCPDriver.cs b/HisenceYoloDetection/MelsecPLCTCPDriver.cs index ad6e1bf..bc8b626 100644 --- a/HisenceYoloDetection/MelsecPLCTCPDriver.cs +++ b/HisenceYoloDetection/MelsecPLCTCPDriver.cs @@ -11,7 +11,7 @@ using static OpenCvSharp.FileStorage; -public class MelsecPLCTCPDriver +public class MelsecPLCTCPDriver1 { private MelsecMcNet melsecMc = new MelsecMcNet(); // private HslCommunication.ModBus.ModbusTcpNet melsecMc = new HslCommunication.ModBus.ModbusTcpNet(); diff --git a/HisenceYoloDetection/PaddleOcrModel.cs b/HisenceYoloDetection/PaddleOcrModel.cs index 73a3551..a9cdc33 100644 --- a/HisenceYoloDetection/PaddleOcrModel.cs +++ b/HisenceYoloDetection/PaddleOcrModel.cs @@ -111,7 +111,7 @@ namespace XKRS.Device.SimboVision.SimboHelper #endif [HandleProcessCorruptedStateExceptions] - public MLResultModel RunInference(MLRequest req) + public MLResult RunInference(MLRequest req) { #if USE_MULTI_THREAD MLResult mlResult = null; @@ -139,7 +139,7 @@ namespace XKRS.Device.SimboVision.SimboHelper } - private void ConvertJsonResult(string json, ref MLResultModel result) + 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]}]}"; // @@ -199,9 +199,9 @@ namespace XKRS.Device.SimboVision.SimboHelper [HandleProcessCorruptedStateExceptions] - public MLResultModel RunInferenceFixed(MLRequest req) + public MLResult RunInferenceFixed(MLRequest req) { - MLResultModel mlResult = new MLResultModel(); + MLResult mlResult = new MLResult(); Mat originMat = new Mat(); try @@ -237,7 +237,7 @@ namespace XKRS.Device.SimboVision.SimboHelper mlResult.ResultMap = BitmapConverter.ToBitmap(maskWeighted);//4ms //将字节数组转换为字符串 - mlResult.ResultMap = originMat.ToBitmap();//4ms + //mlResult.ResultMap = originMat.ToBitmap();//4ms string strGet = System.Text.Encoding.Default.GetString(labellist, 0, labellist.Length); diff --git a/HisenceYoloDetection/PaddleOcrModelCountry.cs b/HisenceYoloDetection/PaddleOcrModelCountry.cs index 607e670..59e244f 100644 --- a/HisenceYoloDetection/PaddleOcrModelCountry.cs +++ b/HisenceYoloDetection/PaddleOcrModelCountry.cs @@ -111,7 +111,7 @@ namespace XKRS.Device.SimboVision.SimboHelper #endif [HandleProcessCorruptedStateExceptions] - public MLResultModel RunInference(MLRequest req) + public MLResult RunInference(MLRequest req) { #if USE_MULTI_THREAD MLResult mlResult = null; @@ -139,7 +139,7 @@ namespace XKRS.Device.SimboVision.SimboHelper } - private void ConvertJsonResult(string json, ref MLResultModel result) + 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]}]}"; // @@ -220,9 +220,9 @@ namespace XKRS.Device.SimboVision.SimboHelper [HandleProcessCorruptedStateExceptions] - public MLResultModel RunInferenceFixed(MLRequest req) + public MLResult RunInferenceFixed(MLRequest req) { - MLResultModel mlResult = new MLResultModel(); + MLResult mlResult = new MLResult(); Mat originMat = new Mat(); try diff --git a/HisenceYoloDetection/Program.cs b/HisenceYoloDetection/Program.cs index 79884d0..95859f2 100644 --- a/HisenceYoloDetection/Program.cs +++ b/HisenceYoloDetection/Program.cs @@ -3,6 +3,7 @@ namespace HisenceYoloDetection internal static class Program { static MainForm? mainFrm = null; + static Form1? form1 = null; /// /// The main entry point for the application. /// @@ -17,6 +18,8 @@ namespace HisenceYoloDetection ApplicationConfiguration.Initialize(); mainFrm = new MainForm(); Application.Run(mainFrm); + //form1 = new Form1(); + //Application.Run(form1); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ThreadException += Application_ThreadException; }catch (Exception ex) diff --git a/HisenceYoloDetection/SQLiteHelper.cs b/HisenceYoloDetection/SQLiteHelper.cs index 2352527..a48d03e 100644 --- a/HisenceYoloDetection/SQLiteHelper.cs +++ b/HisenceYoloDetection/SQLiteHelper.cs @@ -4,6 +4,8 @@ using System.Collections.Specialized; using System.Data; using System.Data.SQLite; using System.Configuration; +using System.Data.SqlClient; +using System.Data.SqlTypes; public class SQLiteHelper @@ -358,8 +360,33 @@ using System.Configuration; return ds; } } + // ִһѯӳ䵽һб + public static List ExecuteQuery(string SQLString, Func selector, params SQLiteParameter[] parameters) + { + using (SQLiteConnection connection = new SQLiteConnection(connectionString)) + { + using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection)) + { + // Ӳ + cmd.Parameters.AddRange(parameters); + // + connection.Open(); + // DataReader󲢶ȡݣÿӳ䵽ӵб + using (SQLiteDataReader reader = cmd.ExecuteReader()) + { + List list = new List(); + while (reader.Read()) + { + list.Add(selector(reader)); + } + return list; + } + } + } + } - public static DataSet Query(string SQLString, string TableName) + + public static DataSet Query(string SQLString, string TableName) { using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { diff --git a/HisenceYoloDetection/SimboVisionMLBase.cs b/HisenceYoloDetection/SimboVisionMLBase.cs index d38cf56..23d998f 100644 --- a/HisenceYoloDetection/SimboVisionMLBase.cs +++ b/HisenceYoloDetection/SimboVisionMLBase.cs @@ -6,6 +6,74 @@ using System.Drawing; using System.Runtime.InteropServices; +public class XK_HisenceWord +{ + public string? OcrBar; + public string? OneblockPath; + public string? OneblockMainWord; + public string? OneblockText; + public string? TwoRect; + public bool? TwoIFWhile; + public string? TwoblockPath; + public string? TwoblockMainWord; + public string? TwoblockText; + public string? ThreeblockPath; + public string? ThreeblockMainWord; + public string? ThreeblockText; + public string? FourblockPath; + public string? FourblockMainWord; + public string? FourblockText; + public string? FiveblockPath; + public string? FiveblockMainWord; + public string? FiveblockText; + public string? SixblockPath; + public string? SixblockMainWord; + public string? SixblockText; + public string? SevenblockPath; + public string? SevenblockMainWord; + public string? SevenblockText; + public string? EightblockPath; + public string? EightblockMainWord; + public string? EightblockText; + + public XK_HisenceWord() + { + + } + + public XK_HisenceWord(string? ocrBar, string? oneblockPath, string? oneblockMainWord, string? oneblockText, string? twoRect, bool? twoIFWhile, string? twoblockPath, string? twoblockMainWord, string? twoblockText, string? threeblockPath, string? threeblockMainWord, string? threeblockText, string? fourblockPath, string? fourblockMainWord, string? fourblockText, string? fiveblockPath, string? fiveblockMainWord, string? fiveblockText, string? sixblockPath, string? sixblockMainWord, string? sixblockText, string? sevenblockPath, string? sevenblockMainWord, string? sevenblockText, string? eightblockPath, string? eightblockMainWord, string? eightblockText) + { + OcrBar = ocrBar; + OneblockPath = oneblockPath; + OneblockMainWord = oneblockMainWord; + OneblockText = oneblockText; + TwoRect = twoRect; + TwoIFWhile = twoIFWhile; + TwoblockPath = twoblockPath; + TwoblockMainWord = twoblockMainWord; + TwoblockText = twoblockText; + ThreeblockPath = threeblockPath; + ThreeblockMainWord = threeblockMainWord; + ThreeblockText = threeblockText; + FourblockPath = fourblockPath; + FourblockMainWord = fourblockMainWord; + FourblockText = fourblockText; + FiveblockPath = fiveblockPath; + FiveblockMainWord = fiveblockMainWord; + FiveblockText = fiveblockText; + SixblockPath = sixblockPath; + SixblockMainWord = sixblockMainWord; + SixblockText = sixblockText; + SevenblockPath = sevenblockPath; + SevenblockMainWord = sevenblockMainWord; + SevenblockText = sevenblockText; + EightblockPath = eightblockPath; + EightblockMainWord = eightblockMainWord; + EightblockText = eightblockText; + } + + } + public class XKHisence { @@ -23,12 +91,13 @@ public class XKHisence public int MoveTwoZ; public string ?OcrParm; public string ?Language; + public string? FuzzyOcrText; 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) + 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,string FuzzyOcrText) { this.Type = type; this.OcrBar = ocrBar; @@ -42,6 +111,7 @@ public class XKHisence this.MoveTwoZ = MoveTwoZ; this.OcrParm = OcrParm; this.Language = Language; + this.FuzzyOcrText = FuzzyOcrText; } @@ -69,12 +139,13 @@ public class MLRequest public int ResizeImageSize; public int segmentWidth; public int ImageWidth; - - - - public float Score; + public MLRequest() + { + + } + } public class DetectionResultDetail { @@ -111,17 +182,7 @@ public class MLResult 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 { diff --git a/HisenceYoloDetection/StaticHelper.cs b/HisenceYoloDetection/StaticHelper.cs index b8a3168..ece9334 100644 --- a/HisenceYoloDetection/StaticHelper.cs +++ b/HisenceYoloDetection/StaticHelper.cs @@ -9,634 +9,641 @@ using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; +using System.Text.RegularExpressions; - public static class StaticHelper +public static class StaticHelper +{ + //判断是否为正整数 + public static bool IsInt(string inString) { - /// - /// 数值转换为byte数组 高位在前,低位在后 - /// - /// - /// - /// - public static byte[] IntToBytes(this int number, int size = 2) + Regex regex = new Regex("^[0-9]*[1-9][0-9]*$"); + return regex.IsMatch(inString.Trim()); + } + /// + /// 数值转换为byte数组 高位在前,低位在后 + /// + /// + /// + /// + public static byte[] IntToBytes(this int number, int size = 2) + { + byte[] result = new byte[size]; + + int temp = size; + while (temp > 0) { - byte[] result = new byte[size]; + result[size - temp] = (byte)(number >> ((temp - 1) * 8) & 0xff); - int temp = size; - while (temp > 0) + 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) { - result[size - temp] = (byte)(number >> ((temp - 1) * 8) & 0xff); - - temp--; + index = data.Length - 1 - i; } - return result; + res += data[index] << (8 * i); } - /// - /// 字节数组转换为整数 - /// - /// 字节数组 - /// true:数组序号低的在高位 false:数组序号低的在低位 - /// - public static int BytesToInt(this byte[] data, bool HtL = true) - { - int res = 0; + return res; + } - for (int i = 0; i < data.Length; i++) + /// + /// 获取一个类指定的属性值 + /// + /// 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) { - 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 }; - } + return new List() { high, low }; } else { - if (num < 0) - { - num = ushort.MaxValue + 1 + num; - } - - return new List() { (ushort)num }; + return new List() { low, high }; } } - - /// - /// 将32位整形数组拆分为无符号16位整形数组 - /// - /// 需要拆分的32位整形 - /// 拆分为16位整形的位数 1或者2 - /// true:高位在前,低位在后;false:高位在后,低位在前 - /// - public static List ParseIntToUnsignShortList(this List list, int bitNum = 2, bool HtL = false) + else { - 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) + if (num < 0) { - 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; + num = ushort.MaxValue + 1 + num; } - 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); + return new List() { (ushort)num }; } } - public class Compare : IEqualityComparer + /// + /// 将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) diff --git a/HisenceYoloDetection/VirtualPLCTCPDriver.cs b/HisenceYoloDetection/VirtualPLCTCPDriver.cs index cb6e723..d52874e 100644 --- a/HisenceYoloDetection/VirtualPLCTCPDriver.cs +++ b/HisenceYoloDetection/VirtualPLCTCPDriver.cs @@ -12,7 +12,7 @@ using static OpenCvSharp.FileStorage; -public class MelsecPLCTCPDriver1 +public class MelsecPLCTCPDriver { // private MelsecMcNet melsecMc = new MelsecMcNet(); // private HslCommunication.ModBus.ModbusTcpNet melsecMc = new HslCommunication.ModBus.ModbusTcpNet();