private void btnSearch3_Click(object sender, EventArgs e) { if (txbProgramName.Text != "" & cbxMatrixSize.Text != "" & cbxCellSample.Text != "" & cbxPolarity.Text != "") { try { userProgram.TemplateConfig.TemplatePath = System.AppDomain.CurrentDomain.BaseDirectory + "\\Programming\\template\\" + txbProgramName.Text + ".png"; RectangleContour rectROI1 = (RectangleContour)imageViewer3.Roi.GetContour(0).Shape; userProgram.DataMatrixConfigs[0].Rectangle.Left = rectROI1.Left; userProgram.DataMatrixConfigs[0].Rectangle.Top = rectROI1.Top; userProgram.DataMatrixConfigs[0].Rectangle.Width = rectROI1.Width; userProgram.DataMatrixConfigs[0].Rectangle.Height = rectROI1.Height; tbxDatamatrix.Text = processPicture.ProcessDatamatrix(imageViewer3.Image, userProgram.TemplateConfig, userProgram.DataMatrixConfigs); if (string.IsNullOrEmpty(tbxDatamatrix.Text)) { MessageBox.Show("There is no Datamatrix in the image!"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { MessageBox.Show("Please confirm the integrate of information!"); } }
/// <summary> /// 找到一个圆 /// </summary> /// <param name="image">图片</param> /// <param name="rect">ROI</param> /// <param name="minr">最小圆半径</param> /// <param name="maxr">最大圆半径</param> /// <param name="center">圆心</param> /// <param name="radius">半径</param> /// <param name="gain">预处理参数</param> /// <param name="offset">预处理参数</param> /// <param name="cycle">预处理参数</param> /// <returns>找到/没找到</returns> public static bool FindCircle(VisionImage image, RectangleContour rect, short minr, short maxr, ref PointContour center, ref double radius, double gain, double offset, int cycle) { if (image == null) { return(false); } for (int i = 0; i < cycle; i++) { image = Form_Main.Instance.GainOffset(image, gain, offset); } Roi roi = rect.ConvertToRoi(); short rtn = 0; try { rtn = Form_Main.Instance.CamDetect_Circle(image, roi, minr, maxr, ref center, ref radius); if (rtn != 0) { return(false); } } catch { return(false); } return(true); }
private bool MatchTemplate(ref ImageViewer imageWiewer, ref ImageViewer imageTemplate) { imageWiewer.Image.Overlays.Default.Clear(); MatchPatternOptions options = new MatchPatternOptions(MatchMode.RotationInvariant, 1); options.MinimumMatchScore = 800; options.MinimumContrast = 0; options.SubpixelAccuracy = false; Collection <PatternMatch> matches = Algorithms.MatchPattern(imageWiewer.Image, imageTemplate.Image, options, imageViewerDatamatrix.Roi); if (matches.Count < 1) { return(false); } // Display results. foreach (PatternMatch match in matches) { imageWiewer.Image.Overlays.Default.AddPolygon(new PolygonContour(match.Corners), Rgb32Value.RedColor); userProgram.TemplateConfig.Position.X = match.Position.X; userProgram.TemplateConfig.Position.Y = match.Position.Y; } RectangleContour rectROI1 = (RectangleContour)imageWiewer.Roi.GetContour(0).Shape; userProgram.TemplateConfig.Rectangle.Left = rectROI1.Left; userProgram.TemplateConfig.Rectangle.Top = rectROI1.Top; userProgram.TemplateConfig.Rectangle.Width = rectROI1.Width; userProgram.TemplateConfig.Rectangle.Height = rectROI1.Height; return(false); }
private void btnFindTemp_Click(object sender, EventArgs e) { CPKTools tools = new CPKTools(); VisionImage align = this.image_Edit.Image; VisionImage image = Form_Main.Instance.imageSet.Image; Roi roi = Form_Main.Instance.imageSet.Roi; short Score = 600; double MinR = -10; double MaxR = 10; short rtn = 0; Variable.CamReturn camReturn = new Variable.CamReturn(); // 初步匹配 rtn = Form_Main.Instance.CamDetect_SearchGeometric(image, align, roi, Score, 1, MinR, MaxR, 100, 100, 0, 25, ref camReturn, 0, 0); if (rtn != 0) { MessageBox.Show("寻找模板失败,请检查参数!!!"); } // 记录ROI 的坐标 if (roi.Count > 0) { RectangleContour rect = (RectangleContour)roi[0].Shape; // save rect string strRoi = string.Format("{0},{1},{2},{3}", rect.Top, rect.Left, rect.Width, rect.Height); this.cpkIni.IniWriteValue("vision", "TemplateRoi", strRoi); } }
public VisRectangleContour(RectangleContour rect) { this.Top = rect.Top; this.Left = rect.Left; this.Width = rect.Width; this.Height = rect.Height; }
private void btnMatch3_Click(object sender, EventArgs e) { try { imageViewer3.Image.Overlays.Default.Clear(); MatchPatternOptions options = new MatchPatternOptions(MatchMode.RotationInvariant, 1); options.MinimumMatchScore = 800; options.MinimumContrast = 0; options.SubpixelAccuracy = false; Collection <PatternMatch> matches = Algorithms.MatchPattern(imageViewer3.Image, imageViewer4.Image, options, imageViewer3.Roi); RectangleContour rectROI1 = (RectangleContour)imageViewer3.Roi.GetContour(0).Shape; userProgram.TemplateConfig.Rectangle.Left = rectROI1.Left; userProgram.TemplateConfig.Rectangle.Top = rectROI1.Top; userProgram.TemplateConfig.Rectangle.Width = rectROI1.Width; userProgram.TemplateConfig.Rectangle.Height = rectROI1.Height; // Display results. foreach (PatternMatch match in matches) { imageViewer3.Image.Overlays.Default.AddPolygon(new PolygonContour(match.Corners), Rgb32Value.RedColor); userProgram.TemplateConfig.Position.X = match.Position.X; userProgram.TemplateConfig.Position.Y = match.Position.Y; } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public RectangleContour IniReadCamResolution(string section, string key) { RectangleContour camResolution = new RectangleContour(0, 0, 1, 1); StringBuilder temp = new StringBuilder(255); string strres, strTopLeftX, strTopLeftY, strWidth, strHeight; GetPrivateProfileString(section, key, "", temp, 255, this.Path); strres = temp.ToString(); try { strTopLeftX = strres.Split(new char[] { ',' })[0]; strTopLeftY = strres.Split(new char[] { ',' })[1]; strWidth = strres.Split(new char[] { ',' })[2]; strHeight = strres.Split(new char[] { ',' })[3]; camResolution.Top = short.Parse(strTopLeftX); camResolution.Left = short.Parse(strTopLeftY); camResolution.Width = short.Parse(strWidth); camResolution.Height = short.Parse(strHeight); } catch { //Function.function.PutInLog("读取" + Path + "中参数" + section + ":" + key + "出错", false); return(camResolution); } return(camResolution); }
private void bRecordROI_Click(object sender, EventArgs e) { try { rect = Form_Main.Instance.imageSet.Roi.GetBoundingRectangle(); } catch { } }
public void IniWriteCamResolution(string section, string key, RectangleContour camResolution) { string strTopLeftX = camResolution.Top.ToString(); string strTopLeftY = camResolution.Left.ToString(); string strWidth = camResolution.Width.ToString(); string strHeight = camResolution.Height.ToString(); WritePrivateProfileString(section, key, strTopLeftX + "," + strTopLeftY + "," + strWidth + "," + strHeight, this.Path); }
public static PaletteType ProcessImage(VisionImage image) { // Initialize the IVA_Data structure to pass results and coordinate systems. IVA_Data ivaData = new IVA_Data(3, 0); // Extract Color Plane using (VisionImage plane = new VisionImage(ImageType.U8, 7)) { // Extract the green color plane and copy it to the main image. Algorithms.ExtractColorPlanes(image, ColorMode.Rgb, null, plane, null); Algorithms.Copy(plane, image); } // Creates a new, empty region of interest. Roi roi = new Roi(); // Creates a new RectangleContour using the given values. RectangleContour vaRect = new RectangleContour(20, 20, 2552, 1904); roi.Add(vaRect); // Geometric Matching string vaTemplateFile = $"{ @"./VisionModel/Polygon_20.5M/Mode.png"}"; CurveOptions vaCurveOptions = new CurveOptions(); vaCurveOptions.ColumnStepSize = 15; vaCurveOptions.ExtractionMode = ExtractionMode.NormalImage; vaCurveOptions.FilterSize = EdgeFilterSize.Normal; vaCurveOptions.MaximumEndPointGap = 10; vaCurveOptions.MinimumLength = 20; vaCurveOptions.RowStepSize = 15; vaCurveOptions.Threshold = 145; MatchGeometricPatternEdgeBasedOptions matchGPMOptions = new MatchGeometricPatternEdgeBasedOptions(); matchGPMOptions.Advanced.ContrastMode = ContrastMode.Original; matchGPMOptions.Advanced.MatchStrategy = GeometricMatchingSearchStrategy.Balanced; matchGPMOptions.MinimumMatchScore = 800; matchGPMOptions.Mode = GeometricMatchModes.RotationInvariant; matchGPMOptions.NumberOfMatchesRequested = 1; double[] vaRangesMin = { -20, 0, 50, 0 }; double[] vaRangesMax = { 20, 0, 200, 50 }; matchGPMOptions.OcclusionRange = new Range(vaRangesMin[3], vaRangesMax[3]); matchGPMOptions.RotationAngleRanges.Add(new Range(vaRangesMin[0], vaRangesMax[0])); matchGPMOptions.RotationAngleRanges.Add(new Range(vaRangesMin[1], vaRangesMax[1])); matchGPMOptions.ScaleRange = new Range(vaRangesMin[2], vaRangesMax[2]); matchGPMOptions.SubpixelAccuracy = true; gpm2Results = IVA_MatchGeometricPattern2(image, vaTemplateFile, vaCurveOptions, matchGPMOptions, ivaData, 2, roi); roi.Dispose(); // Dispose the IVA_Data structure. ivaData.Dispose(); // Return the palette type of the final image. return(PaletteType.Gray); }
private void ExtractTemplatePattern(ref ImageViewer image, ref ImageViewer imageTemplate) { if (image.Roi.Count < 1) { return; } RectangleContour rect = (RectangleContour)image.Roi.GetContour(0).Shape; Algorithms.Extract(image.Image, imageTemplate.Image, rect); Algorithms.LearnPattern(imageTemplate.Image); }
private void btnExtract3_Click(object sender, EventArgs e) { try { RectangleContour rect = (RectangleContour)imageViewer3.Roi.GetContour(0).Shape; Algorithms.Extract(imageViewer3.Image, imageViewer4.Image, rect); Algorithms.LearnPattern(imageViewer4.Image); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void button4_Click(object sender, EventArgs e) { if (Form_Main.Instance.imageSet.Roi.Count > 0 && Form_Main.Instance.imageSet.Roi[0].Shape.GetType() == typeof(RectangleContour)) { RectangleContour rect = (RectangleContour)Form_Main.Instance.imageSet.Roi[0].Shape; PointContour center = new PointContour(); center.X = rect.Left + rect.Width / 2; center.Y = rect.Top + rect.Height / 2; PointF xyPos = new PointF((float)Form_Main.Instance.X.Pos, (float)Form_Main.Instance.Y.Pos); nz4 = Form_Main.Instance.Point2CCDCenter(xyPos, center, Camera.CAM.Bottom1); isCaled4 = true; } }
public string ProcessQR(VisionImage image, List <QRConfig> qRConfigs) { string qRInfo = string.Empty; // Initialize the IVA_Data structure to pass results and coordinate systems. IVA_Data ivaData = new IVA_Data(1, 0); for (int i = 0; i < qRConfigs.Count; i++) { // Creates a new, empty region of interest. Roi roi = new Roi(); //// Creates a new RectangleContour using the given values. //RectangleContour vaRect = new RectangleContour(720, 96, 1792, 1240); RectangleContour vaRect = new RectangleContour(qRConfigs[i].Rectangle.Left, qRConfigs[i].Rectangle.Top, qRConfigs[i].Rectangle.Height, qRConfigs[i].Rectangle.Width); roi.Add(vaRect); image.Overlays.Default.AddRoi(roi); // Read QR Code QRDescriptionOptions vaQROptions = new QRDescriptionOptions(); vaQROptions.Dimensions = qRConfigs[i].QRDimension; vaQROptions.MirrorMode = QRMirrorMode.AutoDetect; vaQROptions.ModelType = QRModelType.AutoDetect; vaQROptions.Polarity = qRConfigs[i].Polarity; QRSizeOptions vaQRSizeOptions = new QRSizeOptions(3, 15); QRSearchOptions vaQRSearchOptions = new QRSearchOptions(); vaQRSearchOptions.CellFilterMode = QRCellFilterMode.AutoDetect; vaQRSearchOptions.CellSampleSize = qRConfigs[i].CellSize; vaQRSearchOptions.DemodulationMode = QRDemodulationMode.AutoDetect; vaQRSearchOptions.EdgeThreshold = 30; vaQRSearchOptions.RotationMode = QRRotationMode.Unlimited; vaQRSearchOptions.SkewDegreesAllowed = 10; vaQRSearchOptions.SkipLocation = false; vaQRCode = Algorithms.ReadQRCode(image, roi, vaQROptions, vaQRSizeOptions, vaQRSearchOptions); if (vaQRCode.Found) { image.Overlays.Default.AddPolygon(new PolygonContour(vaQRCode.Corners), Rgb32Value.RedColor, DrawingMode.DrawValue); } System.Text.ASCIIEncoding vaASCIIEncoding = new System.Text.ASCIIEncoding(); vaQRCodeData = vaASCIIEncoding.GetString(vaQRCode.GetData()); qRInfo += string.Format("{0},", vaQRCodeData); roi.Dispose(); } qRInfo = qRInfo.Substring(0, qRInfo.Length - 1); // Dispose the IVA_Data structure. ivaData.Dispose(); // Return the palette type of the final image. return(qRInfo); }
private void btnFindCircle1_Click(object sender, EventArgs e) { if (Form_Main.Instance.imageSet.Roi.Count > 0 && Form_Main.Instance.imageSet.Roi[0].Shape.GetType() == typeof(RectangleContour)) { short rMin = short.Parse(this.upCircleRmin.Text); short rMax = short.Parse(this.upCircleRmax.Text); PointContour center = new PointContour(); double radius = 0; VisionImage image = Form_Main.Instance.GrabImage2View(Camera.CAM.Top); RectangleContour rect = (RectangleContour)Form_Main.Instance.imageSet.Roi[0].Shape; CPKTools.FindCircle(image, rect, rMin, rMax, ref center, ref radius, 0, 0, 0); this.upCurR.Text = radius.ToString(); } }
private VisionResult ProgramEditCtrl_DetectUI(string arg1, RectangleContour arg2, Module arg3) { VisionResult rtn = new VisionResult(); if (this.bSet_CamLive) { this.bCamLive_Click(this, new EventArgs()); Thread.Sleep(100); } using (VisionImage img = CameraDefine.Instance.Camera[arg3][Camera.Top].Snap()) { rtn = VisionCalHelper.Instance.DetectUI(arg1, img, arg2); Algorithms.Copy(img, this.imageSet.imageSet.Image); } return(rtn); }
private void DrawFailedLED(Overlay overlay, Roi roi) { RectangleContour rect = roi.GetBoundingRectangle(); rect.Left = rect.Left - rect.Width / 1.25; rect.Top = rect.Top - rect.Height / 1.25; rect.Width = rect.Width * 2.5; rect.Height = rect.Height * 2.5; // Overlay on the image to indicate which LED failed. overlay.AddRectangle(rect, Rgb32Value.RedColor, DrawingMode.DrawValue); OverlayTextOptions textOptions = new OverlayTextOptions("Arial", 20, HorizontalTextAlignment.Center); textOptions.VerticalAlignment = VerticalTextAlignment.Baseline; textOptions.TextDecoration.Bold = true; overlay.AddText("Fail", new PointContour(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2), Rgb32Value.RedColor, textOptions); }
private Collection <ClassifierReport> IVA_Classify(VisionImage image, Roi roi, string classifierFilePath) { //retval = new VisGrainTypeCollection(); // Create a binary image that will contain the segmented image. using (VisionImage binaryImage = new VisionImage(ImageType.U8, 7)) { ParticleClassifierSession vaClassifier = new ParticleClassifierSession(); bool fileExists = System.IO.File.Exists(classifierFilePath); vaClassifier.ReadFile(classifierFilePath); // Segments the image. Functions.IVA_Classification_Segmentation(image, binaryImage, roi, vaClassifier.PreprocessingOptions); // Get the ROIs of all individual particles. Collection <Roi> rois = Functions.IVA_Classification_Extract_Particles(image, binaryImage); // Allocates the classifier reports for all objects in the image. Collection <ClassifierReport> classifierReports = new Collection <ClassifierReport>(); List <VisGrainType> listGrainType = new List <VisGrainType>(); ListShape = new List <VisRectangleContour>(); // Classifies the object located in the given ROIs. for (int i = 0; i < rois.Count; ++i) { //RectangleContour rect = binaryImage=new VisionImage() object obj1 = rois[i][0].Shape; RectangleContour rc = (RectangleContour)rois[i][0].Shape; VisRectangleContour rect = new VisRectangleContour(rc); ClassifierReport report = vaClassifier.Classify(image, rois[i]); VisGrainType grainType = new VisGrainType { Name = report.BestClassName, ScoreClassification = report.ClassificationScore, ScoreIdentification = report.IdentificationScore }; listGrainType.Add(grainType); classifierReports.Add(report); ListShape.Add(rect); } GrainResultsType = new VisGrainTypeCollection(); GrainResultsType.Items = listGrainType; return(classifierReports); } }
private void defineMeasurementsButton_Click(object sender, EventArgs e) { // Initialize search rectangle and search annulus. RectangleContour searchRectangle = new RectangleContour(470, 110, 30, 190); AnnulusContour searchAnnulus = new AnnulusContour(new PointContour(366, 201), 33, 121, 42.71, 314.13); // Overlay the search area for the distance measurement. DrawOptions drawOptions = new DrawOptions(); drawOptions.ShowEdgesFound = true; drawOptions.ShowSearchArea = true; drawOptions.ShowSearchLines = true; MeasureMaximumDistance(imageViewer1.Image, searchRectangle, RakeDirection.TopToBottom, drawOptions, new CoordinateTransform()); // Overlay the search area for the circle measurement. FindCircularEdge(imageViewer1.Image, searchAnnulus, SpokeDirection.InsideToOutside, drawOptions, new CoordinateTransform()); // Update buttons. defineMeasurementsButton.Enabled = false; runButton.Enabled = true; }
private void btnSearch1_Click(object sender, EventArgs e) { if (txbProgramName.Text != "" & cbxBarcodeNo.Text != "" & cbxFormat.Text != "" & cbxBarcodeTypes.Text != "") { try { userProgram.TemplateConfig.TemplatePath = string.Format(@"{0}\Programming\template\{1}.png", System.AppDomain.CurrentDomain.BaseDirectory, txbProgramName.Text); int barcodeNum = imageViewer1.Roi.Count; for (int i = 0; i < barcodeNum; i++) { BarcodeConfig barcodeConfig = new BarcodeConfig(); RectangleContour rect = (RectangleContour)imageViewer1.Roi.GetContour(i).Shape; barcodeConfig.Rectangle.Left = rect.Left; barcodeConfig.Rectangle.Top = rect.Top; barcodeConfig.Rectangle.Width = rect.Width; barcodeConfig.Rectangle.Height = rect.Height; barcodeConfig.Type = BarcodeTypes.Code128; if (cbxBarcodeTypes.Text == "Code39") { barcodeConfig.Type = BarcodeTypes.Code39; } barcodeConfig.Index = i; barcodeConfig.Name = string.Format("{0}{1}", barcodeConfig.Type.ToString(), i); userProgram.BarcodeConfigs.Add(barcodeConfig); } userProgram.TemplateConfig.TemplatePath = string.Format(@"{0}Programming\template\{1}.png", AppDomain.CurrentDomain.BaseDirectory, txbProgramName.Text); txbBarcode.Text = processPicture.Process1DBarcode(imageViewer1.Image, userProgram.TemplateConfig, userProgram.BarcodeConfigs); } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { MessageBox.Show("Please confirm the information Barcode format and Barcode number!"); } }
/// <summary> /// 第几条线 /// </summary> /// <param name="lineNum">线号</param> /// <param name="cpkIni">配置信息</param> /// <param name="cross">输出 角点</param> /// <param name="line1">输出 水平线</param> /// <param name="line2">输出 垂直线</param> /// <returns></returns> public static bool FindCorss(int lineNum, IniFile cpkIni, ref PointContour cross, ref LineContour line1, ref LineContour line2) { string header = string.Format("vision{0}", lineNum); int selectSearchDir = 0; int selectMode = 0; VisionImage image = Form_Main.Instance.imageSet.Image; List <LineContour> lines = new List <LineContour>(); for (int i = 0; i < 2; i++) { selectSearchDir = int.Parse(cpkIni.IniReadValue(header, string.Format("SearchDirection{0}", i))); selectMode = int.Parse(cpkIni.IniReadValue(header, string.Format("EdgePolaritySearchMode{0}", i))); string strRoi = cpkIni.IniReadValue(header, string.Format("LineROI{0}", i)); string[] array = strRoi.Split(','); RectangleContour rect = new RectangleContour(int.Parse(array[0]), int.Parse(array[1]), int.Parse(array[2]), int.Parse(array[3])); PointContour start = new PointContour(); PointContour end = new PointContour(); int rtn = CPKTools.FitLine(image, rect, 40, selectSearchDir, selectMode, ref start, ref end); if (rtn == 0) { lines.Add(new LineContour(start, end)); } else { return(false); } } cross = Algorithms.FindIntersectionPoint(lines[0], lines[1]); line1 = lines[0]; line2 = lines[1]; // show Form_Main.Instance.imageSet.Image.Overlays.Default.AddLine(line1, Rgb32Value.RedColor); Form_Main.Instance.imageSet.Image.Overlays.Default.AddLine(line2, Rgb32Value.RedColor); return(true); }
private void timer1_Tick(object sender, EventArgs e) { // Get the next image. VisionImage image = GetNextImage(); // Find the new coordinate transformation. MatchPatternOptions matchOptions = new MatchPatternOptions(MatchMode.RotationInvariant); matchOptions.MinimumMatchScore = 700; matchOptions.SubpixelAccuracy = true; DrawOptions drawOptions = new DrawOptions(); drawOptions.ShowResult = true; FindTransformWithPattern(image, imageViewer2.Image, FindTransformMode.UpdateTransform, matchOptions, drawOptions, transform); // Initialize search rectangle and search annulus. RectangleContour searchRectangle = new RectangleContour(470, 110, 30, 190); AnnulusContour searchAnnulus = new AnnulusContour(new PointContour(366, 201), 33, 121, 42.71, 314.13); // Overlay the search area for the distance measurement. drawOptions.ShowEdgesFound = true; drawOptions.ShowSearchArea = true; drawOptions.ShowSearchLines = true; drawOptions.ShowResult = true; double distance = MeasureMaximumDistance(image, searchRectangle, RakeDirection.TopToBottom, drawOptions, transform); // Overlay the search area for the circle measurement. FitCircleReport circleReport = FindCircularEdge(image, searchAnnulus, SpokeDirection.InsideToOutside, drawOptions, transform); // Display results. distanceBox.Text = String.Format("{0:0.00}", distance); centerXBox.Text = String.Format("{0:0.00}", circleReport.Center.X); centerYBox.Text = String.Format("{0:0.00}", circleReport.Center.Y); radiusBox.Text = String.Format("{0:0.00}", circleReport.Radius); // Display the image. imageViewer1.Attach(image); }
private void btnSearchDatamatrix_Click(object sender, EventArgs e) { DataMatrixConfig dataMatrixConfig = new DataMatrixConfig(); dataMatrixConfig.MatrixSize = cboMatatrixSize.Text; dataMatrixConfig.Polarity = DetectDataMatrixPolarity(cboPolarityDataMatrix.Text); dataMatrixConfig.CellSize = DetectDataMatrixCellSampleSize(cboCellSizeDatamatrix.Text); RectangleContour rectROI1 = (RectangleContour)imageViewerDatamatrix.Roi.GetContour(0).Shape; userProgram.DataMatrixConfigs[0].Rectangle.Left = rectROI1.Left; userProgram.DataMatrixConfigs[0].Rectangle.Top = rectROI1.Top; userProgram.DataMatrixConfigs[0].Rectangle.Width = rectROI1.Width; userProgram.DataMatrixConfigs[0].Rectangle.Height = rectROI1.Height; txtResultDatamatrix.Text = processPicture.ProcessDatamatrix(imageViewerDatamatrix.Image, userProgram.TemplateConfig, userProgram.DataMatrixConfigs); if (string.IsNullOrEmpty(txtResultDatamatrix.Text)) { MessageBox.Show("There is no Datamatrix in the image!"); } }
private void btnSearchQR_Click(object sender, EventArgs e) { QRConfig qRConfig = new QRConfig(); RectangleContour rectROI1 = (RectangleContour)imageViewerQR.Roi.GetContour(0).Shape; userProgram.QRConfigs[0].Rectangle.Left = rectROI1.Left; userProgram.QRConfigs[0].Rectangle.Top = rectROI1.Top; userProgram.QRConfigs[0].Rectangle.Width = rectROI1.Width; userProgram.QRConfigs[0].Rectangle.Height = rectROI1.Height; qRConfig.Rectangle.Left = rectROI1.Left; qRConfig.Rectangle.Top = rectROI1.Top; qRConfig.Rectangle.Width = rectROI1.Width; qRConfig.Rectangle.Height = rectROI1.Height; qRConfig.Index = 0; qRConfig.Name = string.Format("QRConfig0"); qRConfig.QRDimension = DetectQRDimension(cboDimensionQR.Text); qRConfig.Polarity = DetectQRPolarity(cboPolarityQR.Text); qRConfig.CellSize = DetectQRCellSampleSize(cboCellSizeQR.Text); userProgram.QRConfigs.Add(qRConfig); txtResultQR.Text = processPicture.ProcessQR(imageViewerQR.Image, userProgram.QRConfigs); }
private void btnMatch_Click(object sender, EventArgs e) { btnSaveModel.Enabled = false; btnOK.Enabled = false; RectangleContour rect = new RectangleContour(); rect.Left = 0; rect.Top = 0; rect.Width = C.Image.Width; rect.Height = C.Image.Height; PointContour p2 = new PointContour(); string TemplateFile = ""; TemplateFile = System.Windows.Forms.Application.StartupPath + "\\ModelPos.png"; if (File.Exists(TemplateFile) && C.Image != null) { imageViewerModel.Image.ReadFile(TemplateFile); CIni PosIni = new CIni(System.Windows.Forms.Application.StartupPath + "\\Doc\\Pos.ini"); float dScore = Convert.ToSingle(PosIni.IniReadValue("PatternPos", "Score"));//匹配度 p2 = MachineTool.MatchPattern(C.Image, rect, TemplateFile, 1, dScore); MessageBox.Show("X:" + p2.X.ToString("f3") + ", Y:" + p2.Y.ToString("f3")); } }
private void btnSearchBarcode_Click(object sender, EventArgs e) { try { List <BarcodeConfig> barcodeConfigs = new List <BarcodeConfig>(); int barcodeNum = imageViewerBarcodeInfo.Roi.Count; for (int i = 0; i < barcodeNum; i++) { BarcodeConfig barcodeConfig = new BarcodeConfig(); RectangleContour rect = (RectangleContour)imageViewerBarcodeInfo.Roi.GetContour(i).Shape; barcodeConfig.Rectangle.Left = rect.Left; barcodeConfig.Rectangle.Top = rect.Top; barcodeConfig.Rectangle.Width = rect.Width; barcodeConfig.Rectangle.Height = rect.Height; barcodeConfig.Type = BarcodeTypes.Code128; if (cboBarcodeTypes.Text == "Code39") { barcodeConfig.Type = BarcodeTypes.Code39; } barcodeConfig.Index = i; barcodeConfig.Name = string.Format("{0}{1}", barcodeConfig.Type.ToString(), i); barcodeConfigs.Add(barcodeConfig); } txtBarcodeResult.Text = processPicture.Process1DBarcode(imageViewerBarcodeInfo.Image, userProgram.TemplateConfig, userProgram.BarcodeConfigs); if (string.IsNullOrEmpty(txtBarcodeResult.Text)) { MessageBox.Show("There is no barcode info in the image!"); } userProgram.BarcodeConfigs = barcodeConfigs; } catch (Exception ex) { logger.WarnFormat("Searching barcode info error! Error message:{0}", ex.Message); } }
public override VisionResult Detected(VisionImage image, Dictionary <string, VisionResult> Result = null, VisionFlow parent = null, Shape newRoi = null) { VisionResult rtn = new VisionResult(); rtn.State = VisionResultState.WaitCal; try { lock (locked) { using (VisionImage temp = new VisionImage()) { var roi = this.ROI; if (newRoi != null) { roi = newRoi; } using (HImage hImage = VisionHelper.Image(image)) { RectangleContour rect = roi as RectangleContour; using (HImage reduceImage = hImage.ReduceDomain( new HRegion(rect.Top, rect.Left, rect.Top + rect.Height, rect.Left + rect.Width))) { HTuple numLevels = new HTuple(); numLevels.TupleAdd(this.MaxNumLevels); numLevels.TupleAdd(this.MinNumLevels); HTuple row, col, scaleX, scaleY, score, angle; reduceImage.FindAnisoShapeModel(this.ShapeModel, this.StartAngle, this.EndAngle - this.StartAngle, this.YMinScale, this.YMaxScale, this.XMinScale, this.XMaxScale, this.MinScore, 1, this.MaxOverlap, this.Pixel.ToString(), 0, this.Greediness, out row, out col, out angle, out scaleY, out scaleX, out score); if (score.Length > 0) { rtn.State = VisionResultState.OK; image.Overlays.Default.AddLine (new LineContour(new PointContour(col.D - 50, row.D), new PointContour(col.D + 50, row.D)), Rgb32Value.RedColor); image.Overlays.Default.AddLine (new LineContour(new PointContour(col.D, row.D - 50), new PointContour(col.D, row.D + 50)), Rgb32Value.RedColor); rtn.Point = new PointContour(col.D, row.D); rtn.Angle = angle.TupleDeg().D; this.AddVisionResc(rtn, $"轮廓匹配成功 角度:{rtn.Angle:N3} 分数:{score[0].D:N3}"); } else { rtn.State = VisionResultState.NG; this.AddVisionResc(rtn, $"没有找到匹配模板"); } } } } } } catch (HalconException ex) { this.AddVisionResc(rtn, $"轮廓匹配失败 {ex.GetErrorMessage()}"); } return(rtn); }
private void timer1_Tick(object sender, EventArgs e) { double[] classCount = new double[8]; OverlayTextOptions textOptions = new OverlayTextOptions("Arial", 14); textOptions.HorizontalAlignment = HorizontalTextAlignment.Center; // Get the next image GetNextImage(imageViewer1.Image); // Process the image VisionImage binaryImage = new VisionImage(); Algorithms.Threshold(imageViewer1.Image, binaryImage, new Range(0, 200)); Algorithms.RejectBorder(binaryImage, binaryImage); Collection <ParticleReport> reports = Algorithms.ParticleReport(binaryImage); foreach (ParticleReport report in reports) { RectangleContour contour = report.BoundingRect; contour.Left -= 10; contour.Top -= 10; contour.Height += 20; contour.Width += 20; // Classify the part ClassifierReport classifierReport = classifier.Classify(binaryImage, new Roi(new Shape[] { contour })); // Display the result if (classifierReport.ClassificationScore > 500) { textOptions.BackgroundColor = Rgb32Value.TransparentColor; int classIndex = 0; Rgb32Value textColor = Rgb32Value.BlackColor; switch (classifierReport.BestClassName) { case "Motor": textColor = Rgb32Value.WhiteColor; classIndex = 0; break; case "Bolt": textColor = new Rgb32Value(Color.Cyan); classIndex = 1; break; case "Screw": textColor = Rgb32Value.RedColor; classIndex = 2; break; case "Gear": textColor = Rgb32Value.BlackColor; classIndex = 3; break; case "Washer": textColor = new Rgb32Value(Color.Magenta); classIndex = 4; break; case "Worm Gear": textColor = Rgb32Value.GreenColor; classIndex = 5; break; case "Bracket": textColor = new Rgb32Value(0x80, 0x80, 0); classIndex = 6; break; } classCount[classIndex]++; imageViewer1.Image.Overlays.Default.AddText(classifierReport.BestClassName, report.CenterOfMass, textColor, textOptions); } else { textOptions.BackgroundColor = Rgb32Value.BlackColor; imageViewer1.Image.Overlays.Default.AddText("Unknown!", report.CenterOfMass, Rgb32Value.RedColor, textOptions); } } classificationGraph1.PlotClassifier(classCount); }
//////////////////////////////////////////////////////////////////////////////// // // Function Name: IVA_Classification_Segmentation // // Description : Segments the classification image // // Parameters : image - Input Image // imageMask - Segmented image // roi - Region of Interest // preprocessingOptions - Preprocessing options // // Return Value : None // //////////////////////////////////////////////////////////////////////////////// public static void IVA_Classification_Segmentation(VisionImage image, VisionImage imageMask, Roi roi, ParticleClassifierPreprocessingOptions preprocessingOptions) { int useExpandedROI = 0; RectangleContour boundingBox = roi.GetBoundingRectangle(), expandedBox = roi.GetBoundingRectangle(), reducedBox = roi.GetBoundingRectangle(); // Local Threshold method uses a kernel size, and the ROI must be larger than the kernel size for the function to work // Take care of making the ROI to extract larger if needed for the local threshold case if (preprocessingOptions.ThresholdType == ThresholdType.Local) { // Get the image size int xRes, yRes; xRes = image.Width; yRes = image.Height; boundingBox = roi.GetBoundingRectangle(); // Take into account clipping of ROI. Just get ROI that's within bounds of image. if (Math.Min(xRes, (boundingBox.Left + boundingBox.Width)) - Math.Max(0, boundingBox.Left) < preprocessingOptions.LocalThresholdOptions.WindowWidth || Math.Min(yRes, (boundingBox.Top + boundingBox.Height)) - Math.Max(0, boundingBox.Top) < preprocessingOptions.LocalThresholdOptions.WindowHeight) { // The ROI is smaller than the kernel. Try to expand the kernel in the directions needed to meet the minimum size required by the kernel. int expandX = (int)(preprocessingOptions.LocalThresholdOptions.WindowWidth / 2); int expandY = (int)(preprocessingOptions.LocalThresholdOptions.WindowHeight / 2); int leftExpand = expandX; int rightExpand = expandX; int leftSlack = (int)boundingBox.Left; int rightSlack = (int)(xRes - (boundingBox.Left + boundingBox.Width)); if (leftExpand > leftSlack) { rightExpand += (leftExpand - leftSlack); } if (rightExpand > rightSlack) { leftExpand += (rightExpand - rightSlack); } int leftOut = (int)boundingBox.Left - leftExpand; if (leftOut < 0) { leftOut = 0; } int rightOut = (int)(boundingBox.Left + boundingBox.Width + rightExpand); if (rightOut > xRes) { rightOut = xRes; } int topExpand = expandY; int bottomExpand = expandY; int topSlack = (int)boundingBox.Top; int bottomSlack = (int)(yRes - (boundingBox.Top + boundingBox.Height)); if (topExpand > topSlack) { bottomExpand += (topExpand - topSlack); } if (bottomExpand > bottomSlack) { topExpand += (bottomExpand - bottomSlack); } int topOut = (int)(boundingBox.Top - topExpand); if (topOut < 0) { topOut = 0; } int bottomOut = (int)(boundingBox.Top + boundingBox.Height + bottomExpand); if (bottomOut > yRes) { bottomOut = yRes; } expandedBox.Initialize(leftOut, topOut, rightOut - leftOut, bottomOut - topOut); // Create the reduced Rect so after performing the local threshold, we can reduce the size back to the original ROI dimensions. reducedBox.Initialize(Math.Max(boundingBox.Left - leftOut, 0), Math.Max(boundingBox.Top - topOut, 0), boundingBox.Width + Math.Min(boundingBox.Left, 0), boundingBox.Height + Math.Min(boundingBox.Top, 0)); // Set this flag so the image can be reduced after performing the local threshold. useExpandedROI = 1; } } // if Expanded Box hasn't been updated, use the boundingBox passed in to extract. if (useExpandedROI == 0) { expandedBox = boundingBox; } // Extract the region of interest into the mask image. Algorithms.Extract(image, imageMask, expandedBox, 1, 1); // Create a temporary ROI that will be used to mask the extracted image, to get rid of // the pixels outside of the rotated rectangle. Roi tmpROI = new Roi(roi); // If the ROI is a rotated rectangle, then compute the new location of the search ROI. if ((roi[0].Type == ContourType.RotatedRectangle) && (((RotatedRectangleContour)roi[0].Shape).Angle > 0.01)) { CoordinateSystem baseSystem = new CoordinateSystem(); baseSystem.Origin.X = (roi.GetBoundingRectangle().Left < 0 ? 0 : roi.GetBoundingRectangle().Left); baseSystem.Origin.Y = (roi.GetBoundingRectangle().Top < 0 ? 0 : roi.GetBoundingRectangle().Top); baseSystem.Angle = 0; baseSystem.AxisOrientation = AxisOrientation.Direct; CoordinateSystem newSystem = new CoordinateSystem(new PointContour(0, 0), 0, AxisOrientation.Direct); CoordinateTransform transform = new CoordinateTransform(baseSystem, newSystem); Algorithms.TransformRoi(tmpROI, transform); } // Create a temporary image. using (VisionImage tmpImageMask = new VisionImage(ImageType.U8, 7)) { double thresholdMin; double thresholdMax; switch (preprocessingOptions.ThresholdType) { case ThresholdType.Manual: thresholdMin = preprocessingOptions.ManualThresholdRange.Minimum; thresholdMax = preprocessingOptions.ManualThresholdRange.Maximum; Algorithms.Threshold(imageMask, imageMask, new Range(thresholdMin, thresholdMax), true, 1); break; case ThresholdType.Auto: Collection <ThresholdData> thresholdData; thresholdData = Algorithms.AutoThreshold(image, tmpImageMask, 2, preprocessingOptions.AutoThresholdOptions.Method); if (preprocessingOptions.AutoThresholdOptions.ParticleType == ParticleType.Bright) { thresholdMin = (thresholdData[0].Range.Maximum > preprocessingOptions.AutoThresholdOptions.Limits.Minimum ? thresholdData[0].Range.Maximum : preprocessingOptions.AutoThresholdOptions.Limits.Minimum); thresholdMax = 255; } else { thresholdMin = 0; thresholdMax = (thresholdData[0].Range.Maximum < preprocessingOptions.AutoThresholdOptions.Limits.Maximum ? thresholdData[0].Range.Maximum : preprocessingOptions.AutoThresholdOptions.Limits.Maximum); } Algorithms.Threshold(imageMask, imageMask, new Range(thresholdMin, thresholdMax), true, 1); break; case ThresholdType.Local: LocalThresholdOptions Options = new LocalThresholdOptions(preprocessingOptions.LocalThresholdOptions.ParticleType, preprocessingOptions.LocalThresholdOptions.Method, 1.0, preprocessingOptions.LocalThresholdOptions.WindowWidth, preprocessingOptions.LocalThresholdOptions.WindowHeight); Options.DeviationWeight = preprocessingOptions.LocalThresholdOptions.DeviationWeight; Algorithms.LocalThreshold(imageMask, imageMask, Options); break; default: break; } /// If the expanded ROI was used, reduce it so no particles are found outside requested ROI. if (useExpandedROI == 1) { Algorithms.Extract(imageMask, imageMask, reducedBox, 1, 1); } // Cast the image to 8 bit. imageMask.Type = ImageType.U8; // Eliminates particles that touch the border of the image. if (preprocessingOptions.RejectBorder) { if ((roi[0].Type == ContourType.RotatedRectangle) && (((RotatedRectangleContour)roi[0].Shape).Angle > 0.01)) { // Special case for the rotated rectangle. Algorithms.Label(imageMask, imageMask, Connectivity.Connectivity8); Collection <short> lookupTable = new Collection <short>(); lookupTable.Add(0); for (int i = 1; i < 256; i++) { lookupTable.Add(1); } RoiProfileReport roiProfile = Algorithms.RoiProfile(imageMask, tmpROI); for (int i = 0; i < roiProfile.Report.ProfileData.Count; i++) { lookupTable[0] = (short)roiProfile.Report.ProfileData[i]; } Algorithms.UserLookup(imageMask, imageMask, lookupTable); } else { Algorithms.RejectBorder(imageMask, imageMask, Connectivity.Connectivity8); } } // Remove small particles. if (preprocessingOptions.NumberOfErosions > 0) { Algorithms.RemoveParticle(imageMask, imageMask, preprocessingOptions.NumberOfErosions, SizeToKeep.KeepLarge); } // If the rectangle is rotated, mask out the areas of the image that are not in the ROI. if ((roi[0].Type == ContourType.RotatedRectangle) && (((RotatedRectangleContour)roi[0].Shape).Angle > 0.01)) { // Perform the mask Algorithms.RoiToMask(tmpImageMask, tmpROI, new PixelValue(255)); Algorithms.And(imageMask, tmpImageMask, imageMask); } // Sets the mask offset. imageMask.MaskOffset.X = Math.Max(0, roi.GetBoundingRectangle().Left); imageMask.MaskOffset.Y = Math.Max(0, roi.GetBoundingRectangle().Top); } tmpROI.Dispose(); }
private void btnSearch5_Click(object sender, EventArgs e) { if (txbProgramName.Text != "" & cbxQRSize.Text != "" & cbxQRPolarity.Text != "" & cbxQRCell.Text != "") { QRConfig qRConfig = new QRConfig(); try { RectangleContour rectROI1 = (RectangleContour)imageViewer5.Roi.GetContour(0).Shape; userProgram.QRConfigs[0].Rectangle.Left = rectROI1.Left; userProgram.QRConfigs[0].Rectangle.Top = rectROI1.Top; userProgram.QRConfigs[0].Rectangle.Width = rectROI1.Width; userProgram.QRConfigs[0].Rectangle.Height = rectROI1.Height; qRConfig.Rectangle.Left = rectROI1.Left; qRConfig.Rectangle.Top = rectROI1.Top; qRConfig.Rectangle.Width = rectROI1.Width; qRConfig.Rectangle.Height = rectROI1.Height; qRConfig.Index = 0; qRConfig.Name = string.Format("QRConfig0"); qRConfig.QRDimension = QRDimension.AutoDetect; if (cbxQRSize.Text == "11*11") { qRConfig.QRDimension = QRDimension.Size11x11; } else if (cbxQRSize.Text == "21*21") { qRConfig.QRDimension = QRDimension.Size21x21; } else if (cbxQRSize.Text == "25*25") { qRConfig.QRDimension = QRDimension.Size25x25; } qRConfig.Polarity = QRPolarity.AutoDetect; if (cbxQRPolarity.Text == "Black on White") { qRConfig.Polarity = QRPolarity.BlackOnWhite; } else if (cbxQRPolarity.Text == "White on Black") { qRConfig.Polarity = QRPolarity.WhiteOnBlack; } qRConfig.CellSize = QRCellSampleSize.AutoDetect; if (cbxCellSample.Text == "3*3") { qRConfig.CellSize = QRCellSampleSize.Size3x3; } userProgram.QRConfigs.Add(qRConfig); tbxQR.Text = processPicture.ProcessQR(imageViewer5.Image, userProgram.QRConfigs); } catch (Exception ex) { MessageBox.Show(ex.Message + "Please select a ROI which contains the QR code! "); } } else { MessageBox.Show("Please confirm the information Barcode format and Barcode number!"); } }