public static Bitmap HObject2Bitmap(HObject myHObject) { HTuple pointerRed = null; HTuple pointerGreen = null; HTuple pointerBlue = null; HTuple type; HTuple width; HTuple height; HOperatorSet.GetImagePointer3(myHObject, out pointerRed, out pointerGreen, out pointerBlue, out type, out width, out height); Bitmap bitmap = new Bitmap((Int32)width, (Int32)height, PixelFormat.Format32bppRgb); BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width / 4, bitmap.Height / 4), ImageLockMode.ReadWrite, bitmap.PixelFormat); IntPtr source_scan = bmpData.Scan0; unsafe { byte* source_p = (byte*)source_scan.ToPointer(); byte* Red = (byte*)pointerRed.IP.ToPointer(); byte* Blue = (byte*)pointerBlue.IP.ToPointer(); byte* Green = (byte*)pointerGreen.IP.ToPointer(); for (int h = 0; h < bitmap.Height; h++) { for (int w = 0; w < bitmap.Width; w++) { source_p[0] = Blue[0]; //A source_p++; Blue++; source_p[0] = Green[0]; //R source_p++; Green++; source_p[0] = Red[0]; //G source_p++; Red++; //source_p[0] = Blue[0]; //B source_p++; } } } bitmap.UnlockBits(bmpData); return bitmap; }
private void button1_Click(object sender, EventArgs e) { openFileDialog1.Title = "Select Picture"; openFileDialog1.Filter = "Image Files (*.bmp, *.gif, *.jpg,*.png)|*.bmp; *.gif*;*.jpg;*.png"; openFileDialog1.InitialDirectory = "C:/Users/User/Desktop/ZQSFP_ detection2015_12_09/ZQSFP_ detection"; openFileDialog1.AddExtension = true; openFileDialog1.CheckFileExists = true; openFileDialog1.CheckPathExists = true; if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (Image != null) { Image.Dispose(); } HOperatorSet.GenEmptyObj(out Image); HOperatorSet.ReadImage(out Image, openFileDialog1.FileName); HOperatorSet.GetImageSize(Image, out hv_Width, out hv_Height); } else { Image = null; } HOperatorSet.GetImageSize(Image, out hv_Width, out hv_Height); HOperatorSet.SetSystem("width", hv_Width); HOperatorSet.SetSystem("height", hv_Height); HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, hv_Height - 1, hv_Width - 1); HOperatorSet.ClearWindow(hWindowControl1.HalconWindow); HOperatorSet.DispObj(Image, hWindowControl1.HalconWindow); }
public void Initialize(HImage image, HTuple modelRow, HTuple modelColumn, HTuple modelAngle) { ho_Image = image; hv_AllModelRow = new HTuple(modelRow); hv_AllModelColumn = new HTuple(modelColumn); hv_AllModelAngle = new HTuple(modelAngle); }
public HDevelopExport1(HObject ho_Image) { // Default settings used in HDevelop HOperatorSet.SetSystem("width", 512); HOperatorSet.SetSystem("height", 512); if (HalconAPI.isWindows) HOperatorSet.SetSystem("use_window_thread","true"); action(ho_Image); }
public void Add_Object_disp(HObject obj, HTuple color, HTuple Draw, HTuple LineWidth) { setObjectdisplay OD = new setObjectdisplay(); OD.color = color; OD.Draw = Draw; OD.LineWidth = LineWidth; Object_disp.Add(obj); setObject_display.Add(OD); }
/// <summary> /// Evaluates the gray value contrast between the marks and the calibration /// plate and the homogeneity of the used illumination. /// </summary> public void eval_caltab_contrast_homogeneity(HObject ho_Image, HObject ho_Marks, out HTuple hv_Contrast, out HTuple hv_ContrastScore, out HTuple hv_HomogeneityScore) { // Local iconic variables HObject ho_Region, ho_RegionDilation; // Local control variables HTuple hv_Number, hv_Min, hv_Max, hv_Range; HTuple hv_MinContrast, hv_MaxContrast, hv_DeviationMax; // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_Region); HOperatorSet.GenEmptyObj(out ho_RegionDilation); hv_ContrastScore = 0.0; hv_Contrast = 0.0; hv_HomogeneityScore = 0.0; HOperatorSet.CountObj(ho_Marks, out hv_Number); if ((int)(new HTuple(hv_Number.TupleLess(4))) != 0) { ho_Region.Dispose(); ho_RegionDilation.Dispose(); return; } ho_Region.Dispose(); HOperatorSet.GenRegionContourXld(ho_Marks, out ho_Region, "margin"); ho_RegionDilation.Dispose(); HOperatorSet.DilationCircle(ho_Region, out ho_RegionDilation, 5.5); HOperatorSet.MinMaxGray(ho_RegionDilation, ho_Image, 3, out hv_Min, out hv_Max, out hv_Range); //Calculate contrast score hv_Contrast = hv_Range.TupleMean(); hv_MinContrast = 70; hv_MaxContrast = 160; if ((int)(new HTuple(hv_Contrast.TupleGreater(hv_MinContrast))) != 0) { hv_ContrastScore = (hv_Contrast - hv_MinContrast) / (hv_MaxContrast - hv_MinContrast); hv_ContrastScore = ((hv_ContrastScore.TupleConcat(1.0))).TupleMin(); } //Now for the homogeneity score HOperatorSet.TupleDeviation(hv_Max, out hv_DeviationMax); hv_HomogeneityScore = 1.1 - (hv_DeviationMax / 40.0); hv_HomogeneityScore = ((((((hv_HomogeneityScore.TupleConcat(1.0))).TupleMin() )).TupleConcat(0.0))).TupleMax(); ho_Region.Dispose(); ho_RegionDilation.Dispose(); return; }
// Main procedure private void action(DrawlinetoRectangle2 Rectangle2, int Sigma, int threshold, HObject hv_image) { HObject hv_image_c; //複製一份主圖進來運算 hv_image_c = hv_image.Clone(); //Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_Cross); HOperatorSet.GenEmptyObj(out ho_Cross1); HOperatorSet.GetImageSize(hv_image_c, out hv_Width, out hv_Height); //得到影像大小(2448*2048) HOperatorSet.GenMeasureRectangle2(Rectangle2.get_rectangle_Row, //產生測量矩形 Rectangle2.get_rectangle_Column, Rectangle2.get_rectangle_Phi, Rectangle2.get_rectangle_Length1,Rectangle2.get_rectangle_Length2, hv_Width, hv_Height, "nearest_neighbor", out hv_MeasureHandle); //--------------------------------------------------------------------------------- //HOperatorSet.MeasurePairs(hv_image_c, hv_MeasureHandle, 1.5, 30, "negative", "all", //out hv_RowEdgeFirst, out hv_ColumnEdgeFirst, out hv_AmplitudeFirst, out hv_RowEdgeSecond, //out hv_ColumnEdgeSecond, out hv_AmplitudeSecond, out hv_PinWidth, out hv_PinDistance); ////Delete the measure object //ho_Cross.Dispose(); //HOperatorSet.GenCrossContourXld(out ho_Cross, hv_RowEdgeFirst, hv_ColumnEdgeFirst, // Rectangle2.get_rectangle_Length2 * 2, Rectangle2.get_rectangle_Phi); //ho_Cross1.Dispose(); //HOperatorSet.GenCrossContourXld(out ho_Cross1, hv_RowEdgeSecond, hv_ColumnEdgeSecond, // Rectangle2.get_rectangle_Length2 * 2, Rectangle2.get_rectangle_Phi); //HOperatorSet.DispObj(hv_image_c, hv_ExpDefaultWinHandle); //HOperatorSet.SetColor(hv_ExpDefaultWinHandle, "red"); //HOperatorSet.DispObj(ho_Cross, hv_ExpDefaultWinHandle); //HOperatorSet.SetColor(hv_ExpDefaultWinHandle, "blue"); //HOperatorSet.DispObj(ho_Cross1, hv_ExpDefaultWinHandle); //HOperatorSet.CloseMeasure(hv_MeasureHandle); //關閉測量控制器 hv_MeasureHandle //hv_image_c.Dispose(); //------------------------------------------------------------------------------------- HOperatorSet.MeasurePos(hv_image_c, hv_MeasureHandle, Sigma, threshold, //設定測量參數 並且輸出測量錨點 "all", "all", out hv_RowEdge, out hv_ColumnEdge, out hv_Amplitude, out hv_Distance); ho_Cross.Dispose(); HOperatorSet.SetColor(hv_ExpDefaultWinHandle, "blue"); //設定顏色及型態 HOperatorSet.SetDraw(hv_ExpDefaultWinHandle, "margin"); HOperatorSet.GenCrossContourXld(out ho_Cross, hv_RowEdge, hv_ColumnEdge, //產生錨點標記十字 Rectangle2.get_rectangle_Length2 * 2, Rectangle2.get_rectangle_Phi); HOperatorSet.DispObj(hv_image_c, hv_ExpDefaultWinHandle); HOperatorSet.DispObj(ho_Cross, hv_ExpDefaultWinHandle); HOperatorSet.CloseMeasure(hv_MeasureHandle); //關閉測量控制器 hv_MeasureHandle hv_image_c.Dispose(); }
private void button2_Click(object sender, EventArgs e) { HOperatorSet.ReadImage(out Image2, "C:/Users/User/Desktop/ccd+25mm.bmp"); Image = Image2; HOperatorSet.GetImageSize(Image, out hv_Width, out hv_Height); HOperatorSet.SetSystem("width", hv_Width); HOperatorSet.SetSystem("height", hv_Height); HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, hv_Height - 1, hv_Width - 1); HOperatorSet.ClearWindow(hWindowControl1.HalconWindow); HOperatorSet.DispObj(Image, hWindowControl1.HalconWindow); }
public void captrue(out HObject ho_Image_capture) { if (open == true) { HOperatorSet.GrabImageAsync(out ho_Image_capture, hv_AcqHandle, -1);//影像擷取序列打開. } else { MessageBox.Show("相機沒打開"); ho_Image_capture = null; } }
/// <summary> /// 找到匹配模型 /// </summary> /// <param name="hImage">影像</param> /// <param name="trainingModelfilepath">匹配模型數據檔案路徑</param> /// <returns></returns> public ShapeModel Find(HObject hImage, string trainingModelfilepath) { ShapeModel shapeModel = null; if (File.Exists(trainingModelfilepath)) { try { Hanbo.Log.LogManager.Trace("ShapeFinder @Find() => readShapeModel()"); HTuple hv_A1LModelId = ReadShapeModel(trainingModelfilepath); shapeModel = findShapeModel(hImage, hv_A1LModelId); } catch (Exception ex) { Hanbo.Log.LogManager.Error("ShapeFinder exception:" + ex.Message); } } return shapeModel; }
private FitLineResult fitline(HObject rectifyImage, bool isImage) { HObject edges, contoursSplit; HOperatorSet.GenEmptyObj(out edges); HOperatorSet.GenEmptyObj(out contoursSplit); //Edgesubpix var alpha = mMeasAssist.EdgesAlpha; var grayHigh = mMeasAssist.EdgesGrayHigh; HOperatorSet.EdgesSubPix(rectifyImage, out edges, _filter, alpha, _low, grayHigh); HOperatorSet.SegmentContoursXld(edges, out contoursSplit, _mode, _smoothCont, _maxLineDist1, _maxLineDist2); return fitline(contoursSplit); }
// Main procedure #region 循环执行 private void actionMiaUsed() { // Stack for temporary objects 临时对象堆栈 HObject[] OTemp = new HObject[20]; // Local variables 变量 HObject ho_InfoModelContours, ho_SignModelContours; HObject ho_Image = null, ho_SymbolRegions = null, ho_ROI_OCR_01_0 = null; HObject ho_EDGE = null, ho_ObjectSelected = null, ho_InfoTransContours = null; HObject ho_SignTransContours = null; // Local control variables 全局变量 HTuple hv_BarWidth = new HTuple(), hv_BarHeight = new HTuple(); HTuple hv_BarCodeHandle = new HTuple(), hv_InfoModel = new HTuple(); HTuple hv_SignModel = new HTuple(), hv_WindowHandle = new HTuple(); HTuple hv_AcqHandle = new HTuple(), hv_InfoRow = new HTuple(); HTuple hv_InfoColumn = new HTuple(), hv_InfoAngle = new HTuple(); HTuple hv_InfoScore = new HTuple(), hv_DecodedDataStrings = new HTuple(); HTuple hv_someitem = new HTuple(), hv_SignRow = new HTuple(); HTuple hv_SignColumn = new HTuple(), hv_SignAngle = new HTuple(); HTuple hv_SignScore = new HTuple(), hv_SymbolNames_OCR_01_0 = new HTuple(); HTuple hv_Ocr_Split = new HTuple(), hv_Area = new HTuple(); HTuple hv_IDRow = new HTuple(), hv_IDColumn = new HTuple(); HTuple hv_IDRow1 = new HTuple(), hv_IDColumn1 = new HTuple(); HTuple hv_IDRow2 = new HTuple(), hv_IDColumn2 = new HTuple(); HTuple hv_IDHeight = new HTuple(), hv_IDWidth = new HTuple(); HTuple hv_IDRatio = new HTuple(), hv_HeadSignScale = new HTuple(); HTuple hv_HeadSignRow = new HTuple(), hv_HeadSignCol = new HTuple(); HTuple hv_HeadPhi = new HTuple(), hv_sign = new HTuple(); HTuple hv_BarIndex = new HTuple(), hv_Row = new HTuple(); HTuple hv_Column = new HTuple(), hv_InfoHomMat2D = new HTuple(); HTuple hv_SignHomMat2D = new HTuple(), hv_Exception = new HTuple(); // Initialize local and output iconic variables 初始化本地和输出图标变量 HOperatorSet.GenEmptyObj(out ho_InfoModelContours); HOperatorSet.GenEmptyObj(out ho_SignModelContours); HOperatorSet.GenEmptyObj(out ho_Image); HOperatorSet.GenEmptyObj(out ho_SymbolRegions); HOperatorSet.GenEmptyObj(out ho_ROI_OCR_01_0); HOperatorSet.GenEmptyObj(out ho_EDGE); HOperatorSet.GenEmptyObj(out ho_ObjectSelected); HOperatorSet.GenEmptyObj(out ho_InfoTransContours); HOperatorSet.GenEmptyObj(out ho_SignTransContours); try { //*** //** INIT //* INIT CONST 常量 hv_BarWidth.Dispose(); hv_BarWidth = 800; hv_BarHeight.Dispose(); hv_BarHeight = 100; //* INIT IMAGE 图像 //* INIT BARCODE 条形码 hv_BarCodeHandle.Dispose(); HOperatorSet.CreateBarCodeModel(new HTuple(), new HTuple(), out hv_BarCodeHandle); HOperatorSet.SetBarCodeParam(hv_BarCodeHandle, "quiet_zone", "true"); //* INIT LOC 位置 //* Info: hv_InfoModel.Dispose(); HOperatorSet.ReadShapeModel("C:/Users/zhang-sh/source/repos/repo/Model/file/InvV1CaliSign.shm", out hv_InfoModel); ho_InfoModelContours.Dispose(); HOperatorSet.GetShapeModelContours(out ho_InfoModelContours, hv_InfoModel, 1); //* Sign 标志 hv_SignModel.Dispose(); HOperatorSet.ReadShapeModel("C:/Users/zhang-sh/source/repos/repo/Model/file/InvV1CaliSign.shm", out hv_SignModel); ho_SignModelContours.Dispose(); HOperatorSet.GetShapeModelContours(out ho_SignModelContours, hv_SignModel, 1); //*** //** DISPLAY //* DISPLAY INIT hDevelo.dev_update_off(); //dev_close_window(...); //dev_open_window(...); //*** //** LOOP //Image Acquisition 01: Code generated by Image Acquisition 01 图像采集01:图像采集01生成的代码 hv_AcqHandle.Dispose(); hv_AcqHandle = acqHandle; while ((int)(1) != 0) { ho_Image.Dispose(); HOperatorSet.GrabImage(out ho_Image, hv_AcqHandle); if (ho_Image != null) { HOperatorSet.Intensity(ho_Image, ho_Image, out hv_Mean, out hv_Deviation); // 求图片平均值和方差 } { HObject ExpTmpOutVar_0; hDevelo.image_cali_map(ho_Image, out ExpTmpOutVar_0, new HTuple(), new HTuple()); ho_Image.Dispose(); ho_Image = ExpTmpOutVar_0; HOperatorSet.DispObj(ho_Image, hv_ExpImageRawWinHandle); } try { //** PRE using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_InfoRow.Dispose(); hv_InfoColumn.Dispose(); hv_InfoAngle.Dispose(); hv_InfoScore.Dispose(); HOperatorSet.FindShapeModel(ho_Image, hv_InfoModel, (new HTuple(0)).TupleRad() , (new HTuple(360)).TupleRad(), 0.3, 1, 0.5, "least_squares", (new HTuple(7)).TupleConcat( 1), 0.6, out hv_InfoRow, out hv_InfoColumn, out hv_InfoAngle, out hv_InfoScore); } using (HDevDisposeHelper dh = new HDevDisposeHelper()) { HObject ExpTmpOutVar_0; HOperatorSet.RotateImage(ho_Image, out ExpTmpOutVar_0, ((-hv_InfoAngle)).TupleDeg() , "constant"); ho_Image.Dispose(); ho_Image = ExpTmpOutVar_0; } HOperatorSet.DispObj(ho_Image, hv_ExpDefaultWinHandle); //** RECOGNITION //* BARCODE ho_SymbolRegions.Dispose(); hv_DecodedDataStrings.Dispose(); hv_someitem.Dispose(); hDevelo.image_get_bar(ho_Image, out ho_SymbolRegions, hv_BarCodeHandle, out hv_DecodedDataStrings, out hv_someitem); //* LOC //* Info: using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_InfoRow.Dispose(); hv_InfoColumn.Dispose(); hv_InfoAngle.Dispose(); hv_InfoScore.Dispose(); HOperatorSet.FindShapeModel(ho_Image, hv_InfoModel, (new HTuple(0)).TupleRad() , (new HTuple(360)).TupleRad(), 0.3, 1, 0.5, "least_squares", (new HTuple(7)).TupleConcat( 1), 0.7, out hv_InfoRow, out hv_InfoColumn, out hv_InfoAngle, out hv_InfoScore); } //* HaedSign using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_SignRow.Dispose(); hv_SignColumn.Dispose(); hv_SignAngle.Dispose(); hv_SignScore.Dispose(); HOperatorSet.FindShapeModel(ho_Image, hv_SignModel, (new HTuple(0)).TupleRad() , (new HTuple(360)).TupleRad(), 0.3, 1, 0.5, "least_squares", (new HTuple(7)).TupleConcat( 1), 0.7, out hv_SignRow, out hv_SignColumn, out hv_SignAngle, out hv_SignScore); } //* Ocr using (HDevDisposeHelper dh = new HDevDisposeHelper()) { ho_ROI_OCR_01_0.Dispose(); HOperatorSet.GenRectangle2(out ho_ROI_OCR_01_0, hv_InfoRow + 70, hv_InfoColumn - 700, hv_InfoAngle, 100, 30); } hv_SymbolNames_OCR_01_0.Dispose(); hv_Ocr_Split.Dispose(); hDevelo.region_ocr_num_svm(ho_Image, ho_ROI_OCR_01_0, new HTuple(), new HTuple(), out hv_SymbolNames_OCR_01_0, out hv_Ocr_Split); hv_Area.Dispose(); hv_IDRow.Dispose(); hv_IDColumn.Dispose(); HOperatorSet.AreaCenter(ho_ROI_OCR_01_0, out hv_Area, out hv_IDRow, out hv_IDColumn); hv_IDRow1.Dispose(); hv_IDColumn1.Dispose(); hv_IDRow2.Dispose(); hv_IDColumn2.Dispose(); HOperatorSet.SmallestRectangle1(ho_ROI_OCR_01_0, out hv_IDRow1, out hv_IDColumn1, out hv_IDRow2, out hv_IDColumn2); hv_IDHeight.Dispose(); hv_IDWidth.Dispose(); hv_IDRatio.Dispose(); HOperatorSet.HeightWidthRatio(ho_ROI_OCR_01_0, out hv_IDHeight, out hv_IDWidth, out hv_IDRatio); //* Sign hv_HeadSignScale.Dispose(); hv_HeadSignScale = 1; hv_HeadSignRow.Dispose(); hv_HeadSignRow = new HTuple(hv_SignRow); hv_HeadSignCol.Dispose(); hv_HeadSignCol = new HTuple(hv_SignColumn); hv_HeadPhi.Dispose(); hv_HeadPhi = new HTuple(hv_SignAngle); ho_EDGE.Dispose(); hv_sign.Dispose(); hDevelo.region_judge_sign(ho_Image, out ho_EDGE, hv_HeadSignScale, hv_HeadSignRow, hv_HeadSignCol, hv_HeadPhi, hv_WindowHandle, out hv_sign); //** DISPLAY //* DISPLAY BARCODE 显示条形码 hDevelo.set_display_font(hv_ExpDefaultWinHandle, 14, "mono", "true", "false"); HOperatorSet.SetDraw(hv_ExpDefaultWinHandle, "margin"); HOperatorSet.SetLineWidth(hv_ExpDefaultWinHandle, 3); HOperatorSet.SetColor(hv_ExpDefaultWinHandle, "forest green"); HOperatorSet.DispObj(ho_SymbolRegions, hv_ExpDefaultWinHandle); for (hv_BarIndex = 1; (int)hv_BarIndex <= (int)(new HTuple(hv_DecodedDataStrings.TupleLength() )); hv_BarIndex = (int)hv_BarIndex + 1) { ho_ObjectSelected.Dispose(); HOperatorSet.SelectObj(ho_SymbolRegions, out ho_ObjectSelected, hv_BarIndex); hv_Area.Dispose(); hv_Row.Dispose(); hv_Column.Dispose(); HOperatorSet.AreaCenter(ho_ObjectSelected, out hv_Area, out hv_Row, out hv_Column); using (HDevDisposeHelper dh = new HDevDisposeHelper()) { HOperatorSet.SetTposition(hv_ExpDefaultWinHandle, hv_Row - hv_BarHeight, hv_Column - (0.25 * hv_BarWidth)); } using (HDevDisposeHelper dh = new HDevDisposeHelper()) { HOperatorSet.WriteString(hv_ExpDefaultWinHandle, hv_DecodedDataStrings.TupleSelect( hv_BarIndex - 1)); } } //* DISPLAY LOC HOperatorSet.SetLineWidth(hv_ExpDefaultWinHandle, 1); //* Info: hv_InfoHomMat2D.Dispose(); HOperatorSet.HomMat2dIdentity(out hv_InfoHomMat2D); { HTuple ExpTmpOutVar_0; HOperatorSet.HomMat2dRotate(hv_InfoHomMat2D, hv_InfoAngle, 0, 0, out ExpTmpOutVar_0); hv_InfoHomMat2D.Dispose(); hv_InfoHomMat2D = ExpTmpOutVar_0; } { HTuple ExpTmpOutVar_0; HOperatorSet.HomMat2dTranslate(hv_InfoHomMat2D, hv_InfoRow, hv_InfoColumn, out ExpTmpOutVar_0); hv_InfoHomMat2D.Dispose(); hv_InfoHomMat2D = ExpTmpOutVar_0; } ho_InfoTransContours.Dispose(); HOperatorSet.AffineTransContourXld(ho_InfoModelContours, out ho_InfoTransContours, hv_InfoHomMat2D); HOperatorSet.SetColor(hv_ExpDefaultWinHandle, "green"); HOperatorSet.DispObj(ho_InfoTransContours, hv_ExpDefaultWinHandle); //* Ocr //dev_disp_text (Ocr_Split, 'image', IDRow1 + IDHeight, IDColumn1, 'blue', [], []) 开发显示文本 //* HeadSign hv_SignHomMat2D.Dispose(); HOperatorSet.HomMat2dIdentity(out hv_SignHomMat2D); { HTuple ExpTmpOutVar_0; HOperatorSet.HomMat2dRotate(hv_SignHomMat2D, hv_SignAngle, 0, 0, out ExpTmpOutVar_0); hv_SignHomMat2D.Dispose(); hv_SignHomMat2D = ExpTmpOutVar_0; } { HTuple ExpTmpOutVar_0; HOperatorSet.HomMat2dTranslate(hv_SignHomMat2D, hv_SignRow, hv_SignColumn, out ExpTmpOutVar_0); hv_SignHomMat2D.Dispose(); hv_SignHomMat2D = ExpTmpOutVar_0; } ho_SignTransContours.Dispose(); HOperatorSet.AffineTransContourXld(ho_SignModelContours, out ho_SignTransContours, hv_SignHomMat2D); HOperatorSet.SetColor(hv_ExpDefaultWinHandle, "green"); HOperatorSet.DispObj(ho_SignTransContours, hv_ExpDefaultWinHandle); //* Sign HOperatorSet.SetColored(hv_ExpDefaultWinHandle, 12); HOperatorSet.DispObj(ho_EDGE, hv_ExpDefaultWinHandle); //dump_window_image (ImageResult, WindowHandle) 转储窗口图像 // 手动保存图片和数据 if (ImgAuto.state == ImgAutoState.imgAutoFalse && SaveData.state == SaveDataState.saveDataTrue) { // 时间 string ScanDate = DateTime.Now.ToString("yyyyMMddHHmmssfff"); MainFormDAL mainFormDAL = new MainFormDAL(); ImgHelper imgHelper = new ImgHelper(); // 保存图片 imgHelper.SaveImg(ScanDate, ho_Image); SaveData.state = SaveDataState.saveDataFalse; // 保存数据 UsedInfo usedInfo; usedInfo = mainFormDAL.ConvertStruct(hv_Ocr_Split, hv_DecodedDataStrings, hv_sign); mainFormDAL.SaveTemp(usedInfo, ScanDate); imgNumber = imgNumber + 1; usedInfo.ImgCount = imgNumber; } ; // 自动保存图片和数据 if (ImgAuto.state == ImgAutoState.imgAutoTrue) { // 时间 string ScanDate = DateTime.Now.ToString("yyyyMMddHHmmssfff"); MainFormDAL mainFormDAL = new MainFormDAL(); ImgHelper imgHelper = new ImgHelper(); // 保存图片 imgHelper.SaveImg(ScanDate, ho_Image); SaveData.state = SaveDataState.saveDataFalse; // 保存数据 UsedInfo usedInfo; usedInfo = mainFormDAL.ConvertStruct(hv_Ocr_Split, hv_DecodedDataStrings, hv_sign); mainFormDAL.SaveTemp(usedInfo, ScanDate); imgNumber += imgNumber; usedInfo.ImgCount = imgNumber; Thread.Sleep(5000); } //stop () } // catch (Exception) catch (HalconException HDevExpDefaultException1) { HDevExpDefaultException1.ToHTuple(out hv_Exception); } } HOperatorSet.CloseFramegrabber(hv_AcqHandle); } catch (HalconException HDevExpDefaultException) { ho_InfoModelContours.Dispose(); ho_SignModelContours.Dispose(); ho_Image.Dispose(); ho_SymbolRegions.Dispose(); ho_ROI_OCR_01_0.Dispose(); ho_EDGE.Dispose(); ho_ObjectSelected.Dispose(); ho_InfoTransContours.Dispose(); ho_SignTransContours.Dispose(); hv_BarWidth.Dispose(); hv_BarHeight.Dispose(); hv_BarCodeHandle.Dispose(); hv_InfoModel.Dispose(); hv_SignModel.Dispose(); hv_WindowHandle.Dispose(); hv_AcqHandle.Dispose(); hv_InfoRow.Dispose(); hv_InfoColumn.Dispose(); hv_InfoAngle.Dispose(); hv_InfoScore.Dispose(); hv_DecodedDataStrings.Dispose(); hv_someitem.Dispose(); hv_SignRow.Dispose(); hv_SignColumn.Dispose(); hv_SignAngle.Dispose(); hv_SignScore.Dispose(); hv_SymbolNames_OCR_01_0.Dispose(); hv_Ocr_Split.Dispose(); hv_Area.Dispose(); hv_IDRow.Dispose(); hv_IDColumn.Dispose(); hv_IDRow1.Dispose(); hv_IDColumn1.Dispose(); hv_IDRow2.Dispose(); hv_IDColumn2.Dispose(); hv_IDHeight.Dispose(); hv_IDWidth.Dispose(); hv_IDRatio.Dispose(); hv_HeadSignScale.Dispose(); hv_HeadSignRow.Dispose(); hv_HeadSignCol.Dispose(); hv_HeadPhi.Dispose(); hv_sign.Dispose(); hv_BarIndex.Dispose(); hv_Row.Dispose(); hv_Column.Dispose(); hv_InfoHomMat2D.Dispose(); hv_SignHomMat2D.Dispose(); hv_Exception.Dispose(); throw HDevExpDefaultException; } ho_InfoModelContours.Dispose(); ho_SignModelContours.Dispose(); ho_Image.Dispose(); ho_SymbolRegions.Dispose(); ho_ROI_OCR_01_0.Dispose(); ho_EDGE.Dispose(); ho_ObjectSelected.Dispose(); ho_InfoTransContours.Dispose(); ho_SignTransContours.Dispose(); hv_BarWidth.Dispose(); hv_BarHeight.Dispose(); hv_BarCodeHandle.Dispose(); hv_InfoModel.Dispose(); hv_SignModel.Dispose(); hv_WindowHandle.Dispose(); hv_AcqHandle.Dispose(); hv_InfoRow.Dispose(); hv_InfoColumn.Dispose(); hv_InfoAngle.Dispose(); hv_InfoScore.Dispose(); hv_DecodedDataStrings.Dispose(); hv_someitem.Dispose(); hv_SignRow.Dispose(); hv_SignColumn.Dispose(); hv_SignAngle.Dispose(); hv_SignScore.Dispose(); hv_SymbolNames_OCR_01_0.Dispose(); hv_Ocr_Split.Dispose(); hv_Area.Dispose(); hv_IDRow.Dispose(); hv_IDColumn.Dispose(); hv_IDRow1.Dispose(); hv_IDColumn1.Dispose(); hv_IDRow2.Dispose(); hv_IDColumn2.Dispose(); hv_IDHeight.Dispose(); hv_IDWidth.Dispose(); hv_IDRatio.Dispose(); hv_HeadSignScale.Dispose(); hv_HeadSignRow.Dispose(); hv_HeadSignCol.Dispose(); hv_HeadPhi.Dispose(); hv_sign.Dispose(); hv_BarIndex.Dispose(); hv_Row.Dispose(); hv_Column.Dispose(); hv_InfoHomMat2D.Dispose(); hv_SignHomMat2D.Dispose(); hv_Exception.Dispose(); }
private void action() { // Stack for temporary objects HObject[] OTemp = new HObject[20]; long SP_O = 0; // Local iconic variables HObject ho_Circle, region; HObject ho_SelectedRegions, ho_outCircle; // Local control variables //HTuple hv_blackOrwhite, hv_threshold_value; //HTuple hv_method, hv_andOror, hv_method_min_value, hv_method_max_value; HTuple hv_outer_Row, hv_outer_Column; HTuple hv_outer_Radius, hv_Circularity; HTuple hv_Number = new HTuple(), hv_result = new HTuple(); // Initialize local and output iconic variables //HOperatorSet.GenEmptyObj(out ho_Image); HOperatorSet.GenEmptyObj(out ho_Circle); HOperatorSet.GenEmptyObj(out ho_SelectedRegions); HOperatorSet.GenEmptyObj(out ho_outCircle); HOperatorSet.GenEmptyObj(out region); try { //HOperatorSet.SetColor(this.LWindowHandle, "green"); // out hv_Radius); ho_Circle.Dispose(); HOperatorSet.GenCircle(out ho_Circle, DCenterRow, DCenterColumn, DRadius); HOperatorSet.Intersection(ho_Circle, algorithm.Region, out region); region_outer_circle(region, out ho_outCircle, out hv_outer_Row, out hv_outer_Column, out hv_outer_Radius, out hv_Circularity); //HOperatorSet.DispObj(ho_outCircle, this.LWindowHandle); RegionToDisp.Dispose(); if (!RegionToDisp.IsInitialized()) { HOperatorSet.CopyObj(ho_outCircle, out RegionToDisp, 1, 1); } else { HOperatorSet.ConcatObj(ho_outCircle, RegionToDisp, out RegionToDisp); } //RegionToDisp HOperatorSet.CountObj(ho_outCircle, out hv_Number); if ((int)(new HTuple(hv_Number.TupleEqual(1))) != 0) { hv_result = hv_result.TupleConcat("center_row"); hv_result = hv_result.TupleConcat(hv_outer_Row * pixeldist); hv_result = hv_result.TupleConcat("center_column"); hv_result = hv_result.TupleConcat(hv_outer_Column * pixeldist); hv_result = hv_result.TupleConcat("diameter"); hv_result = hv_result.TupleConcat(2 * hv_outer_Radius * pixeldist); hv_result = hv_result.TupleConcat("circularity"); hv_result = hv_result.TupleConcat(hv_Circularity); result = hv_result.Clone(); } else { hv_result = hv_result.TupleConcat("center_row"); hv_result = hv_result.TupleConcat(0); hv_result = hv_result.TupleConcat("center_column"); hv_result = hv_result.TupleConcat(0); hv_result = hv_result.TupleConcat("diameter"); hv_result = hv_result.TupleConcat(0); hv_result = hv_result.TupleConcat("circularity"); hv_result = hv_result.TupleConcat(0); result = hv_result.Clone(); } } catch (HalconException HDevExpDefaultException) { this.Result = new HTuple(); MyDebug.ShowMessage("CircleToolsError:=" + HDevExpDefaultException); hv_result = hv_result.TupleConcat("center_row"); hv_result = hv_result.TupleConcat(0); hv_result = hv_result.TupleConcat("center_column"); hv_result = hv_result.TupleConcat(0); hv_result = hv_result.TupleConcat("diameter"); hv_result = hv_result.TupleConcat(0); hv_result = hv_result.TupleConcat("circularity"); hv_result = hv_result.TupleConcat(0); result = hv_result.Clone(); } finally { ho_Circle.Dispose(); region.Dispose(); ho_SelectedRegions.Dispose(); ho_outCircle.Dispose(); algorithm.Region.Dispose(); } }
//Circle**************************************************************************************** /// <summary> /// 找圆-使用ROI-RectangleRegion /// </summary> /// <param name="img">图片</param> /// <param name="rectRoi">ROI</param> /// <param name="MinRadius">最小半径</param> /// <param name="MaxRadius">最大半径</param> /// <param name="Center">中心点</param> /// <param name="Radius">半径</param> /// <param name="ho_Contcircle">圆轮廓</param> /// <param name="ho_cross">圆中心</param> /// <returns></returns> public static bool DetectCircle(HObject img, RectangleContour rectRoi, double MinRadius, double MaxRadius, out PointF Center, out double Radius, out HObject ho_Contcircle, out HObject ho_cross) { //************************************************************************************************* ho_Contcircle = null; ho_cross = null; Center = new PointF(); Radius = 0; HObject ho_ImageROI, Roi, hCircles, countour; HOperatorSet.GenEmptyObj(out ho_ImageROI); HOperatorSet.GenEmptyObj(out hCircles); HOperatorSet.GenEmptyObj(out countour); HOperatorSet.GenRectangle1(out Roi, rectRoi.Left, rectRoi.Top, rectRoi.Left + rectRoi.Height, rectRoi.Width); //************************************************************************************************* HTuple hv_numbers, CoutourType;//返回拟合圆个数 try { HOperatorSet.ReduceDomain(img, Roi, out ho_ImageROI); //获取图像区域 形态学处理后 HOperatorSet.EdgesSubPix(ho_ImageROI, out ho_ImageROI, "canny", 1.5, 50, 75); HOperatorSet.SegmentContoursXld(ho_ImageROI, out ho_ImageROI, "lines_circles", 5, 4, 2); HOperatorSet.SelectShapeXld(ho_ImageROI, out ho_ImageROI, "circularity", "and", 0.5, 1); HOperatorSet.SelectShapeXld(ho_ImageROI, out ho_ImageROI, "outer_radius", "and", MinRadius, MaxRadius); HOperatorSet.CountObj(ho_ImageROI, out hv_numbers); if (hv_numbers.D != 0) { for (int i = 0; i < hv_numbers.D; i++) { HOperatorSet.SelectObj(ho_ImageROI, out countour, i); HOperatorSet.GetContourAttribXld(countour, "cont_approx", out CoutourType); if (CoutourType.D != -1)//-1=line 0- 1-circle { HOperatorSet.ConcatObj(hCircles, countour, out hCircles); } } HOperatorSet.CountObj(hCircles, out hv_numbers); if (hv_numbers.D == 0) { Roi.Dispose(); ho_ImageROI.Dispose(); hCircles.Dispose(); countour.Dispose(); return(false); } HTuple hv_Row, hv_Column, hv_Radius, hv_startPhi, hv_endPhi, hv_PointOrder; HOperatorSet.FitCircleContourXld(hCircles, "geometric", -1, 2, 0, 3, 2, out hv_Row, out hv_Column, out hv_Radius, out hv_startPhi, out hv_endPhi, out hv_PointOrder); hv_numbers = new HTuple(hv_Row.TupleLength()); if (hv_numbers.D == 0) { Roi.Dispose(); ho_ImageROI.Dispose(); hCircles.Dispose(); countour.Dispose(); return(false); } Center.X = (float)(hv_Column[0].D); Center.Y = (float)(hv_Row[0].D); Radius = hv_Radius[0].D; HOperatorSet.GenCircleContourXld(out ho_Contcircle, hv_Row[0], hv_Column[0], hv_Radius[0], 0, 6.28, "positive", 1); HOperatorSet.GenCrossContourXld(out ho_cross, hv_Row[0], hv_Column[0], 10, 0); Roi.Dispose(); ho_ImageROI.Dispose(); hCircles.Dispose(); countour.Dispose(); return(true); } else { Roi.Dispose(); ho_ImageROI.Dispose(); hCircles.Dispose(); countour.Dispose(); return(false); } } catch { Roi.Dispose(); ho_ImageROI.Dispose(); hCircles.Dispose(); countour.Dispose(); return(false); } }
public HObjectWithColor(HObject _hbj, string _color, string _drow) { hObject = _hbj; color = _color; draw = _drow; }
public void setImage(HObject obj) { Image = obj; HOperatorSet.GetImageSize(obj, out ImageWidth, out ImageHeight); }
///<summary> ///初始化函数 ///</summary> public void Initialization() { FittingLine = new FittingLine(); ImageProcessing = new ImageProcessing(); hv_MeasureRow1 = new HTuple(); hv_MeasureColumn1 = new HTuple(); hv_MeasureRow2 = new HTuple(); hv_MeasureColumn2 = new HTuple(); hv_MeasureLength2 = new HTuple(); hv_MeasureDistance = new HTuple(); hv_MetrologyHandle = new HTuple(); hv_MeasureLength1 = 20; hv_MeasureSigma = 1.0; hv_MeasureThreshold = 30; hv_MeasureInterpolation = "bicubic"; //插值类型 hv_MeasureTransition = "positive"; //明暗方向 hv_MeasureSelect = "first"; //边缘选取 hv_MeasurePointsNum = 20; //Roi数量 hv_MeasureMinScore = 0.3; //最低得分 hv_MeasureNumInstances = 1; //直线拟合数量 hv_MeasureDistThreshold = 2; //距离剔除 hv_MaxNumIterations = -1; //迭代次数 hv_MeasureIORegions = "false"; //对测量结果的验证 hv_ImageProcessing = "None"; //对图像预处理 hv_MaskWidth = 1; //均值滤波宽度 hv_MaskHeight = 10; //均值滤波高度 hv_MaskType = "square"; //中值滤波形状 hv_Radius = 10; //中值滤波半径 hv_MaskSize = 7; //Laplace滤波模型大小 hv_FilterMask = "n_4"; //Laplace滤波模型 hv_MultImage_Mult = 0.03; //图像乘法增益 hv_AddImage_Mult = 0.8; //图像加法增益 hv_ScaleImage_Add = 0; //阈值拉伸偏移 hv_ScaleImage_Mult = 2; //阈值拉伸增益 hv_Index = null; DetectLineFlag = false; ho_Contours = null; ho_Cross = null; hv_CrossRow = null; hv_CrossColumn = null; ho_RegionLines = null; xmlRW = new XmlRW(); hv_LineRowBegin = 0; //拟合直线像素坐标 hv_LineColumnBegin = 0; hv_LineRowEnd = 0; hv_LineColumnEnd = 0; hv_LineRowBegin_Real = 0; //拟合直线实际坐标 hv_LineColumnBegin_Real = 0; hv_LineRowEnd_Real = 0; hv_LineColumnEnd_Real = 0; RefreshParams(); }
// Procedures // External procedures // Chapter: Develop // Short Description: Open a new graphics window that preserves the aspect ratio of the given image. public void dev_open_window_fit_image(HObject ho_Image, HTuple hv_Row, HTuple hv_Column, HTuple hv_WidthLimit, HTuple hv_HeightLimit, out HTuple hv_WindowHandle) { // Local iconic variables // Local control variables HTuple hv_MinWidth = new HTuple(), hv_MaxWidth = new HTuple(); HTuple hv_MinHeight = new HTuple(), hv_MaxHeight = new HTuple(); HTuple hv_ResizeFactor = null, hv_ImageWidth = null, hv_ImageHeight = null; HTuple hv_TempWidth = null, hv_TempHeight = null, hv_WindowWidth = null; HTuple hv_WindowHeight = null; // Initialize local and output iconic variables //This procedure opens a new graphics window and adjusts the size //such that it fits into the limits specified by WidthLimit //and HeightLimit, but also maintains the correct image aspect ratio. // //If it is impossible to match the minimum and maximum extent requirements //at the same time (f.e. if the image is very long but narrow), //the maximum value gets a higher priority, // //Parse input tuple WidthLimit if (hv_WidthLimit.TupleLength() == 0 || hv_WidthLimit.TupleLess(0)) { hv_MinWidth = 500; hv_MaxWidth = 800; } else if (hv_WidthLimit.TupleLength() == 1) { hv_MinWidth = 0; hv_MaxWidth = hv_WidthLimit.Clone(); } else { hv_MinWidth = hv_WidthLimit.TupleSelect(0); hv_MaxWidth = hv_WidthLimit.TupleSelect(1); } //Parse input tuple HeightLimit if (hv_HeightLimit.TupleLength() == 0 || hv_HeightLimit.TupleLess(0)) { hv_MinHeight = 400; hv_MaxHeight = 600; } else if (hv_HeightLimit.TupleLength() == 1) { hv_MinHeight = 0; hv_MaxHeight = hv_HeightLimit.Clone(); } else { hv_MinHeight = hv_HeightLimit.TupleSelect(0); hv_MaxHeight = hv_HeightLimit.TupleSelect(1); } // //Test, if window size has to be changed. hv_ResizeFactor = 1; HOperatorSet.GetImageSize(ho_Image, out hv_ImageWidth, out hv_ImageHeight); //First, expand window to the minimum extents (if necessary). //if (hv_MinWidth.TupleGreater(hv_ImageWidth)||hv_MinHeight.TupleGreater(hv_ImageHeight)) if (hv_MinWidth > hv_ImageWidth || hv_MinHeight > hv_ImageHeight) { hv_ResizeFactor = (((((hv_MinWidth.TupleReal()) / hv_ImageWidth)).TupleConcat( (hv_MinHeight.TupleReal()) / hv_ImageHeight))).TupleMax(); } hv_TempWidth = hv_ImageWidth * hv_ResizeFactor; hv_TempHeight = hv_ImageHeight * hv_ResizeFactor; //Then, shrink window to maximum extents (if necessary). if (hv_MaxWidth.TupleLess(hv_TempWidth) || hv_MaxHeight.TupleLess(hv_TempHeight)) { hv_ResizeFactor = hv_ResizeFactor * ((((((hv_MaxWidth.TupleReal()) / hv_TempWidth)).TupleConcat( (hv_MaxHeight.TupleReal()) / hv_TempHeight))).TupleMin()); } hv_WindowWidth = hv_ImageWidth * hv_ResizeFactor; hv_WindowHeight = hv_ImageHeight * hv_ResizeFactor; //Resize window HOperatorSet.SetWindowAttr("background_color", "black"); HOperatorSet.OpenWindow(hv_Row, hv_Column, hv_WindowWidth, hv_WindowHeight, 0, "visible", "", out hv_WindowHandle); HDevWindowStack.Push(hv_WindowHandle); if (HDevWindowStack.IsOpen()) { HOperatorSet.SetPart(HDevWindowStack.GetActive(), 0, 0, hv_ImageHeight - 1, hv_ImageWidth - 1); } return; }
public MeasureResult Action() { #region 輸出結果 CircleResult mResult = null; #endregion // Local iconic variables HObject ho_R5_Circle = null; HObject ho_R5_ROI_Image = null, ho_R5_Region = null, ho_R5_ImageReduced = null; HObject ho_R5_Edges = null, ho_R5_ContoursSplit = null, ho_R5_SingleSegment = null; HObject ho_R5_ContEllipse = null; // Local control variables HTuple hv_msgOffsetY, hv_msgOffsetX; HTuple hv_STD_Row; HTuple hv_STD_Col, hv_Img_Row, hv_Img_Col, hv_Img_Rotate_Angle; HTuple hv_OffsetRow, hv_OffsetCol, hv_R5_R; HTuple hv_STD_R5_Row = new HTuple(), hv_STD_R5_Col = new HTuple(); HTuple hv_STD_R5_V_Row = new HTuple(), hv_STD_R5_V_Col = new HTuple(); HTuple hv_R5_X = new HTuple(), hv_R5_Y = new HTuple(), hv_R5_Pos_Row = new HTuple(); HTuple hv_R5_Pos_Col = new HTuple(), hv_alpha = new HTuple(); HTuple hv_R5_low = new HTuple(), hv_R5_high = new HTuple(); HTuple hv_R5_NumSegments = new HTuple(), hv_NumCircles = new HTuple(); HTuple hv_Num_Circle_Point = new HTuple(), hv_R5 = new HTuple(); HTuple hv_i = new HTuple(), hv_Attrib = new HTuple(), hv_R5_Row = new HTuple(); HTuple hv_R5_Column = new HTuple(), hv_R5_Radius = new HTuple(); HTuple hv_R5_StartPhi = new HTuple(), hv_R5_EndPhi = new HTuple(); HTuple hv_R5_PointOrder = new HTuple(), hv_R5_MinDist = new HTuple(); HTuple hv_R5_MaxDist = new HTuple(), hv_R5_AvgDist = new HTuple(); HTuple hv_R5_SigmaDist = new HTuple(); // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_R5_Circle); HOperatorSet.GenEmptyObj(out ho_R5_ROI_Image); HOperatorSet.GenEmptyObj(out ho_R5_Region); HOperatorSet.GenEmptyObj(out ho_R5_ImageReduced); HOperatorSet.GenEmptyObj(out ho_R5_Edges); HOperatorSet.GenEmptyObj(out ho_R5_ContoursSplit); HOperatorSet.GenEmptyObj(out ho_R5_SingleSegment); HOperatorSet.GenEmptyObj(out ho_R5_ContEllipse); //Measure: SDMS_R5 //Author: John Hsieh //Date: 2012 // dev_update_off(...); only in hdevelop HOperatorSet.SetSystem("border_shape_models", "false"); //****Message Args hv_msgOffsetY = 100; hv_msgOffsetX = 100; //****Model Args //STD 中心點 hv_STD_Row = 772; hv_STD_Col = 1003; //目前圖形 中心點 hv_Img_Row = hv_AllModelRow.Clone(); hv_Img_Col = hv_AllModelColumn.Clone(); //目前圖形 Rotate Angle hv_Img_Rotate_Angle = hv_AllModelAngle.Clone(); //目前圖形偏移量 hv_OffsetRow = hv_Img_Row - hv_STD_Row; hv_OffsetCol = hv_Img_Col - hv_STD_Col; //****Display if (HDevWindowStack.IsOpen()) { HOperatorSet.ClearWindow(HDevWindowStack.GetActive()); } if (HDevWindowStack.IsOpen()) { HOperatorSet.DispObj(ho_Image, HDevWindowStack.GetActive()); } //*****R5 hv_R5_R = 29; //STD R5_ 位置 hv_STD_R5_Row = 1281; hv_STD_R5_Col = 1388; //STD 向量 STD_R5_ hv_STD_R5_V_Row = hv_STD_R5_Row - hv_STD_Row; hv_STD_R5_V_Col = hv_STD_R5_Col - hv_STD_Col; //R5_X, R5_Y 分量 hv_R5_X = (hv_STD_R5_V_Col * (hv_Img_Rotate_Angle.TupleCos())) + (hv_STD_R5_V_Row * (hv_Img_Rotate_Angle.TupleSin() )); hv_R5_Y = (hv_STD_R5_V_Row * (hv_Img_Rotate_Angle.TupleCos())) - (hv_STD_R5_V_Col * (hv_Img_Rotate_Angle.TupleSin() )); //目前圖形 R5 位置 hv_R5_Pos_Row = (hv_STD_Row + hv_R5_Y) + hv_OffsetRow; hv_R5_Pos_Col = (hv_STD_Col + hv_R5_X) + hv_OffsetCol; //** 開始計算 ho_R5_Circle.Dispose(); HOperatorSet.GenCircle(out ho_R5_Circle, hv_R5_Pos_Row, hv_R5_Pos_Col, hv_R5_R); ho_R5_ROI_Image.Dispose(); HOperatorSet.ReduceDomain(ho_Image, ho_R5_Circle, out ho_R5_ROI_Image); ho_R5_Region.Dispose(); HOperatorSet.FastThreshold(ho_R5_ROI_Image, out ho_R5_Region, 100, 255, 15); ho_R5_ImageReduced.Dispose(); HOperatorSet.ReduceDomain(ho_R5_ROI_Image, ho_R5_Region, out ho_R5_ImageReduced ); //stop () //sobel_fast 具有較寬的選擇範圍,搭配 alpha 參數 (alpha 越大, 容錯範圍大) hv_alpha = 0.9; hv_R5_low = 20; hv_R5_high = 60; ho_R5_Edges.Dispose(); HOperatorSet.EdgesSubPix(ho_R5_ImageReduced, out ho_R5_Edges, "sobel_fast", hv_alpha, hv_R5_low, hv_R5_high); //stop () //*所有的數值越小,表示容錯範圍大,反之亦然 ho_R5_ContoursSplit.Dispose(); HOperatorSet.SegmentContoursXld(ho_R5_Edges, out ho_R5_ContoursSplit, "lines_circles", 17, 4, 2); //Display the results //=========================================================== HOperatorSet.CountObj(ho_R5_ContoursSplit, out hv_R5_NumSegments); hv_NumCircles = 0; hv_Num_Circle_Point = 0; hv_R5 = 999; for (hv_i = 1; hv_i.Continue(hv_R5_NumSegments, 1); hv_i = hv_i.TupleAdd(1)) { ho_R5_SingleSegment.Dispose(); HOperatorSet.SelectObj(ho_R5_ContoursSplit, out ho_R5_SingleSegment, hv_i); HOperatorSet.GetContourGlobalAttribXld(ho_R5_SingleSegment, "cont_approx", out hv_Attrib); if ((int)(new HTuple(hv_Attrib.TupleEqual(1))) != 0) { HOperatorSet.FitCircleContourXld(ho_R5_SingleSegment, "atukey", -1, 2, hv_Num_Circle_Point, 5, 2, out hv_R5_Row, out hv_R5_Column, out hv_R5_Radius, out hv_R5_StartPhi, out hv_R5_EndPhi, out hv_R5_PointOrder); ho_R5_ContEllipse.Dispose(); HOperatorSet.GenEllipseContourXld(out ho_R5_ContEllipse, hv_R5_Row, hv_R5_Column, 0, hv_R5_Radius, hv_R5_Radius, 0, (new HTuple(360)).TupleRad(), "positive", 1.0); if (HDevWindowStack.IsOpen()) { HOperatorSet.DispObj(ho_R5_ContEllipse, HDevWindowStack.GetActive()); } HOperatorSet.DistEllipseContourXld(ho_R5_SingleSegment, "algebraic", -1, 0, hv_R5_Row, hv_R5_Column, 0, hv_R5_Radius, hv_R5_Radius, out hv_R5_MinDist, out hv_R5_MaxDist, out hv_R5_AvgDist, out hv_R5_SigmaDist); hv_NumCircles = hv_NumCircles + 1; if ((int)(new HTuple(hv_R5.TupleGreater(hv_R5_Radius))) != 0) { hv_R5 = hv_R5_Radius.Clone(); mResult = new CircleResult() { Row = new HTuple(hv_R5_Row), Col = new HTuple(hv_R5_Column), Radius = new HTuple(hv_R5_Radius), StartPhi = new HTuple(hv_R5_StartPhi), EndPhi = new HTuple(hv_R5_EndPhi), PointOrder = new HTuple(hv_R5_PointOrder), }; //HOperatorSet.SetTposition(hv_WindowHandle, (hv_R5_Pos_Row - hv_msgOffsetY) - 50, // hv_R5_Pos_Col - hv_msgOffsetX); //HOperatorSet.WriteString(hv_WindowHandle, "R5"); } } } ho_R5_Circle.Dispose(); ho_R5_ROI_Image.Dispose(); ho_R5_Region.Dispose(); ho_R5_ImageReduced.Dispose(); ho_R5_Edges.Dispose(); ho_R5_ContoursSplit.Dispose(); ho_R5_SingleSegment.Dispose(); ho_R5_ContEllipse.Dispose(); return(mResult); }
public void GetContempPic() { Image = engine.GetGlobalIconicVarObject("ContempPic"); }
// Procedures // Local procedures public void EnhanceEdgeArea4(HObject ho_InputImage, out HObject ho_EnhancedImage, out HObject ho_EnhancedEdge, HTuple hv_MeanMaskWidth, HTuple hv_MeanMaskHeight, HTuple hv_FirstMinGray, HTuple hv_FirstMaxGray, HTuple hv_SortOrder, HTuple hv_EmpMaskWidth, HTuple hv_EmpMaskHeight, HTuple hv_EmpMaskFactor, HTuple hv_LastMinGray, HTuple hv_LastMaxGray) { // Local iconic variables HObject ho_Domain, ho_ImageMean, ho_Regions; HObject ho_ConnectedRegions1, ho_SelectedRegions2 = null; HObject ho_SortedRegions = null, ho_ObjectSelected = null, ho_RegionFillUp; HObject ho_ImageReduced, ho_ImageScaleMax, ho_ImageMean2; HObject ho_ImageEmphasize, ho_Regions2, ho_ConnectedRegions; HObject ho_SelectedRegions = null, ho_RegionDifference; // Local control variables HTuple hv_Width = null, hv_Height = null; // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_EnhancedImage); HOperatorSet.GenEmptyObj(out ho_EnhancedEdge); HOperatorSet.GenEmptyObj(out ho_Domain); HOperatorSet.GenEmptyObj(out ho_ImageMean); HOperatorSet.GenEmptyObj(out ho_Regions); HOperatorSet.GenEmptyObj(out ho_ConnectedRegions1); HOperatorSet.GenEmptyObj(out ho_SelectedRegions2); HOperatorSet.GenEmptyObj(out ho_SortedRegions); HOperatorSet.GenEmptyObj(out ho_ObjectSelected); HOperatorSet.GenEmptyObj(out ho_RegionFillUp); HOperatorSet.GenEmptyObj(out ho_ImageReduced); HOperatorSet.GenEmptyObj(out ho_ImageScaleMax); HOperatorSet.GenEmptyObj(out ho_ImageMean2); HOperatorSet.GenEmptyObj(out ho_ImageEmphasize); HOperatorSet.GenEmptyObj(out ho_Regions2); HOperatorSet.GenEmptyObj(out ho_ConnectedRegions); HOperatorSet.GenEmptyObj(out ho_SelectedRegions); HOperatorSet.GenEmptyObj(out ho_RegionDifference); ho_Domain.Dispose(); HOperatorSet.GetDomain(ho_InputImage, out ho_Domain); HOperatorSet.RegionFeatures(ho_Domain, "width", out hv_Width); HOperatorSet.RegionFeatures(ho_Domain, "height", out hv_Height); ho_ImageMean.Dispose(); HOperatorSet.MeanImage(ho_InputImage, out ho_ImageMean, hv_MeanMaskWidth, hv_MeanMaskHeight); ho_Regions.Dispose(); HOperatorSet.Threshold(ho_ImageMean, out ho_Regions, hv_FirstMinGray, hv_FirstMaxGray); ho_ConnectedRegions1.Dispose(); HOperatorSet.Connection(ho_Regions, out ho_ConnectedRegions1); if ((int)(new HTuple(hv_MeanMaskWidth.TupleGreater(hv_MeanMaskHeight))) != 0) { ho_SelectedRegions2.Dispose(); HOperatorSet.SelectShape(ho_ConnectedRegions1, out ho_SelectedRegions2, "width", "and", hv_Width * 0.9, hv_Width); ho_SortedRegions.Dispose(); HOperatorSet.SortRegion(ho_SelectedRegions2, out ho_SortedRegions, "upper_left", hv_SortOrder, "row"); ho_ObjectSelected.Dispose(); HOperatorSet.SelectObj(ho_SortedRegions, out ho_ObjectSelected, 1); } else { ho_SelectedRegions2.Dispose(); HOperatorSet.SelectShape(ho_ConnectedRegions1, out ho_SelectedRegions2, "height", "and", hv_Height * 0.9, hv_Height); ho_SortedRegions.Dispose(); HOperatorSet.SortRegion(ho_SelectedRegions2, out ho_SortedRegions, "upper_left", hv_SortOrder, "column"); ho_ObjectSelected.Dispose(); HOperatorSet.SelectObj(ho_SortedRegions, out ho_ObjectSelected, 1); } ho_RegionFillUp.Dispose(); HOperatorSet.FillUp(ho_ObjectSelected, out ho_RegionFillUp); ho_ImageReduced.Dispose(); HOperatorSet.ReduceDomain(ho_ImageMean, ho_RegionFillUp, out ho_ImageReduced); ho_ImageScaleMax.Dispose(); HOperatorSet.ScaleImageMax(ho_ImageReduced, out ho_ImageScaleMax); ho_ImageMean2.Dispose(); HOperatorSet.MeanImage(ho_ImageScaleMax, out ho_ImageMean2, hv_MeanMaskWidth, hv_MeanMaskHeight); ho_ImageEmphasize.Dispose(); HOperatorSet.Emphasize(ho_ImageMean2, out ho_ImageEmphasize, hv_EmpMaskWidth, hv_EmpMaskHeight, hv_EmpMaskFactor); ho_Regions2.Dispose(); HOperatorSet.Threshold(ho_ImageEmphasize, out ho_Regions2, hv_LastMinGray, hv_LastMaxGray); ho_ConnectedRegions.Dispose(); HOperatorSet.Connection(ho_Regions2, out ho_ConnectedRegions); if ((int)(new HTuple(hv_MeanMaskWidth.TupleGreater(hv_MeanMaskHeight))) != 0) { ho_SelectedRegions.Dispose(); HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions, "width", "and", hv_Width * 0.1, hv_Width); } else { ho_SelectedRegions.Dispose(); HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions, "height", "and", hv_Height * 0.1, hv_Height); } ho_EnhancedEdge.Dispose(); HOperatorSet.MoveRegion(ho_SelectedRegions, out ho_EnhancedEdge, 0, 0); ho_EnhancedImage.Dispose(); HOperatorSet.ChangeDomain(ho_ImageEmphasize, ho_Domain, out ho_EnhancedImage); ho_RegionDifference.Dispose(); HOperatorSet.Difference(ho_Domain, ho_SelectedRegions, out ho_RegionDifference ); HOperatorSet.OverpaintRegion(ho_EnhancedImage, ho_RegionDifference, 255, "fill"); ho_Domain.Dispose(); ho_ImageMean.Dispose(); ho_Regions.Dispose(); ho_ConnectedRegions1.Dispose(); ho_SelectedRegions2.Dispose(); ho_SortedRegions.Dispose(); ho_ObjectSelected.Dispose(); ho_RegionFillUp.Dispose(); ho_ImageReduced.Dispose(); ho_ImageScaleMax.Dispose(); ho_ImageMean2.Dispose(); ho_ImageEmphasize.Dispose(); ho_Regions2.Dispose(); ho_ConnectedRegions.Dispose(); ho_SelectedRegions.Dispose(); ho_RegionDifference.Dispose(); return; }
/// <summary> /// 预处理图像用于训练或测试 /// </summary> public void PreprocessImage(string hv_Pretrained_DlClassifierName, HObject ho_Image, out HObject ho_ImagePreprocessed) { HTuple hv_DLClassifierHandle = new HTuple(); HOperatorSet.ReadDlClassifier(hv_Pretrained_DlClassifierName, out hv_DLClassifierHandle); preprocess_dl_classifier_images(ho_Image, out ho_ImagePreprocessed, new HTuple(), new HTuple(), hv_DLClassifierHandle); }
/// <summary> /// 模板匹配通用函数,仅匹配 /// </summary> /// <param name="ho_image"></param> /// <param name="ho_roi"></param> /// <param name="ho_show_contour"></param> /// <param name="ho_update_show_contour"></param> /// <param name="hv_model_type"></param> /// <param name="hv_model_id"></param> /// <param name="hv_angle_start"></param> /// <param name="hv_angle_extent"></param> /// <param name="hv_score_thresh"></param> /// <param name="hv_match_num"></param> /// <param name="hv_def_row"></param> /// <param name="hv_def_col"></param> /// <param name="hv_found_row"></param> /// <param name="hv_found_col"></param> /// <param name="hv_found_angle"></param> /// <param name="hv_found_score"></param> /// <param name="hv_update_def_row"></param> /// <param name="hv_update_def_col"></param> /// <param name="hv_model_H_new"></param> /// <param name="hv_iFlag"></param> public static void find_model(HObject ho_image, HObject ho_roi, HObject ho_show_contour, out HObject ho_update_show_contour, HTuple hv_model_type, HTuple hv_model_id, HTuple hv_angle_start, HTuple hv_angle_extent, HTuple hv_score_thresh, HTuple hv_match_num, HTuple hv_def_row, HTuple hv_def_col, out HTuple hv_found_row, out HTuple hv_found_col, out HTuple hv_found_angle, out HTuple hv_found_score, out HTuple hv_update_def_row, out HTuple hv_update_def_col, out HTuple hv_model_H_new, out HTuple hv_iFlag) { // Stack for temporary objects HObject[] OTemp = new HObject[20]; // Local iconic variables HObject ho_complement_region, ho_paint_image; HObject ho_reduced_image, ho_affine_show_contour = null; // Local control variables HTuple hv_inv_model_row = new HTuple(), hv_inv_model_col = new HTuple(); HTuple hv_ncc_numlevs = new HTuple(), hv_angle_step = new HTuple(); HTuple hv_ncc_metric = new HTuple(), hv_local_row = new HTuple(); HTuple hv_local_col = new HTuple(), hv_local_angle = new HTuple(); HTuple hv_local_score = new HTuple(), hv_shape_numlevs = new HTuple(); HTuple hv_shape_scale_min = new HTuple(), hv_shape_scale_max = new HTuple(); HTuple hv_shape_scale_step = new HTuple(), hv_shape_metric = new HTuple(); HTuple hv_shape_min_contrast = new HTuple(), hv_Greatereq = null; HTuple hv_GreaterInd = null, hv_model_row = new HTuple(); HTuple hv_model_col = new HTuple(), hv_def_row_ind = new HTuple(); HTuple hv_def_col_ind = new HTuple(), hv_i = new HTuple(); HTuple hv_model_H_any = new HTuple(), hv__update_def_row = new HTuple(); HTuple hv__update_def_col = new HTuple(), hv_update_model_row = new HTuple(); HTuple hv_update_model_col = new HTuple(); HTuple hv_angle_extent_COPY_INP_TMP = hv_angle_extent.Clone(); HTuple hv_angle_start_COPY_INP_TMP = hv_angle_start.Clone(); // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_update_show_contour); HOperatorSet.GenEmptyObj(out ho_complement_region); HOperatorSet.GenEmptyObj(out ho_paint_image); HOperatorSet.GenEmptyObj(out ho_reduced_image); HOperatorSet.GenEmptyObj(out ho_affine_show_contour); hv_update_def_row = new HTuple(); hv_update_def_col = new HTuple(); hv_found_row = new HTuple(); hv_found_col = new HTuple(); hv_found_angle = new HTuple(); hv_found_score = new HTuple(); hv_model_H_new = new HTuple(); hv_iFlag = 0; ho_update_show_contour.Dispose(); HOperatorSet.GenEmptyObj(out ho_update_show_contour); HTuple channel; HOperatorSet.CountChannels(ho_image, out channel); if (channel.I != 1) { HOperatorSet.Rgb1ToGray(ho_image, out ho_image); } ho_complement_region.Dispose(); HOperatorSet.Complement(ho_roi, out ho_complement_region); ho_paint_image.Dispose(); HOperatorSet.PaintRegion(ho_complement_region, ho_image, out ho_paint_image, 255, "fill"); ho_reduced_image.Dispose(); HOperatorSet.ReduceDomain(ho_paint_image, ho_roi, out ho_reduced_image); //******NCC/bin Ncc if ((int)(new HTuple(hv_model_type.TupleEqual(0))) != 0) { HOperatorSet.GetNccModelOrigin(hv_model_id, out hv_inv_model_row, out hv_inv_model_col); if ((int)((new HTuple(hv_angle_start_COPY_INP_TMP.TupleEqual(-1))).TupleOr( new HTuple(hv_angle_extent_COPY_INP_TMP.TupleEqual(-1)))) != 0) { HOperatorSet.GetNccModelParams(hv_model_id, out hv_ncc_numlevs, out hv_angle_start_COPY_INP_TMP, out hv_angle_extent_COPY_INP_TMP, out hv_angle_step, out hv_ncc_metric); } else { hv_angle_start_COPY_INP_TMP = hv_angle_start_COPY_INP_TMP.TupleRad(); hv_angle_extent_COPY_INP_TMP = hv_angle_extent_COPY_INP_TMP.TupleRad(); } HOperatorSet.FindNccModel(ho_reduced_image, hv_model_id, hv_angle_start_COPY_INP_TMP, hv_angle_extent_COPY_INP_TMP, 0.5, hv_match_num, 0.5, "true", 0, out hv_local_row, out hv_local_col, out hv_local_angle, out hv_local_score); //******Shape/Shape Xld } else { HOperatorSet.GetShapeModelOrigin(hv_model_id, out hv_inv_model_row, out hv_inv_model_col); if ((int)((new HTuple(hv_angle_start_COPY_INP_TMP.TupleEqual(-1))).TupleOr( new HTuple(hv_angle_extent_COPY_INP_TMP.TupleEqual(-1)))) != 0) { HOperatorSet.GetShapeModelParams(hv_model_id, out hv_shape_numlevs, out hv_angle_start_COPY_INP_TMP, out hv_angle_extent_COPY_INP_TMP, out hv_angle_step, out hv_shape_scale_min, out hv_shape_scale_max, out hv_shape_scale_step, out hv_shape_metric, out hv_shape_min_contrast); } else { hv_angle_start_COPY_INP_TMP = hv_angle_start_COPY_INP_TMP.TupleRad(); hv_angle_extent_COPY_INP_TMP = hv_angle_extent_COPY_INP_TMP.TupleRad(); } HOperatorSet.FindShapeModel(ho_reduced_image, hv_model_id, hv_angle_start_COPY_INP_TMP, hv_angle_extent_COPY_INP_TMP, 0.5, hv_match_num, 0.5, "least_squares", 0, 0.9, out hv_local_row, out hv_local_col, out hv_local_angle, out hv_local_score); } if ((int)(new HTuple((new HTuple(hv_local_score.TupleLength())).TupleLess(1))) != 0) { hv_iFlag = -2; ho_complement_region.Dispose(); ho_paint_image.Dispose(); ho_reduced_image.Dispose(); ho_affine_show_contour.Dispose(); return; } HOperatorSet.TupleGreaterEqualElem(hv_local_score, hv_score_thresh, out hv_Greatereq); HOperatorSet.TupleFind(hv_Greatereq, 1, out hv_GreaterInd); if ((int)(new HTuple(hv_GreaterInd.TupleEqual(-1))) != 0) { hv_iFlag = -2; ho_complement_region.Dispose(); ho_paint_image.Dispose(); ho_reduced_image.Dispose(); ho_affine_show_contour.Dispose(); return; } else { //***获取模板中心坐标 hv_model_row = -hv_inv_model_row; hv_model_col = -hv_inv_model_col; HOperatorSet.TupleFind(hv_def_row, -1, out hv_def_row_ind); HOperatorSet.TupleFind(hv_def_col, -1, out hv_def_col_ind); for (hv_i = 0; (int)hv_i <= (int)((new HTuple(hv_GreaterInd.TupleLength())) - 1); hv_i = (int)hv_i + 1) { HOperatorSet.VectorAngleToRigid(0, 0, 0, hv_local_row.TupleSelect(hv_GreaterInd.TupleSelect( hv_i)), hv_local_col.TupleSelect(hv_GreaterInd.TupleSelect(hv_i)), hv_local_angle.TupleSelect( hv_GreaterInd.TupleSelect(hv_i)), out hv_model_H_any); ho_affine_show_contour.Dispose(); HOperatorSet.AffineTransContourXld(ho_show_contour, out ho_affine_show_contour, hv_model_H_any); if ((int)((new HTuple(hv_def_row_ind.TupleEqual(-1))).TupleAnd(new HTuple(hv_def_col_ind.TupleEqual( -1)))) != 0) { HOperatorSet.AffineTransPoint2d(hv_model_H_any, hv_def_row, hv_def_col, out hv__update_def_row, out hv__update_def_col); } else { hv__update_def_row = new HTuple(); hv__update_def_col = new HTuple(); } HOperatorSet.ConcatObj(ho_update_show_contour, ho_affine_show_contour, out OTemp[0] ); ho_update_show_contour.Dispose(); ho_update_show_contour = OTemp[0]; //*****更新实际的模板坐标 HOperatorSet.AffineTransPoint2d(hv_model_H_any, hv_model_row, hv_model_col, out hv_update_model_row, out hv_update_model_col); hv_found_row = hv_found_row.TupleConcat(hv_update_model_row); hv_found_col = hv_found_col.TupleConcat(hv_update_model_col); hv_found_angle = hv_found_angle.TupleConcat(((hv_local_angle.TupleSelect( hv_GreaterInd.TupleSelect(hv_i)))).TupleDeg()); hv_found_score = hv_found_score.TupleConcat(hv_local_score.TupleSelect(hv_GreaterInd.TupleSelect( hv_i))); hv_update_def_row = hv_update_def_row.TupleConcat(hv__update_def_row); hv_update_def_col = hv_update_def_col.TupleConcat(hv__update_def_col); hv_model_H_new = hv_model_H_new.TupleConcat(hv_model_H_any); } } ho_complement_region.Dispose(); ho_paint_image.Dispose(); ho_reduced_image.Dispose(); ho_affine_show_contour.Dispose(); return; }
private void action() { // Local iconic variables HObject ho_Circle, ho_Region, ho_ImageReduced, ho_ConnectedRegions, ho_RegionDilation, ho_RegionErosion, ho_RegionDilation1; HObject ho_SelectedRegions, ho_RegionIntersection = null; HObject ho_RegionFillUp = null, ho_RegionTrans = null, ho_Circle1 = null; // Local control variables HTuple hv_ir = null, hv_yy = null, hv_Distance = null, hv_Sigma = null, hv_Roundness = null, hv_Sides = null; HTuple hv_Number = null, hv_Row1 = new HTuple(), hv_Column1 = new HTuple(); HTuple hv_Radius1 = new HTuple(), hv_Circularity = new HTuple(); // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_Circle); HOperatorSet.GenEmptyObj(out ho_ImageReduced); HOperatorSet.GenEmptyObj(out ho_Region); HOperatorSet.GenEmptyObj(out ho_RegionErosion); HOperatorSet.GenEmptyObj(out ho_RegionDilation); HOperatorSet.GenEmptyObj(out ho_RegionDilation1); HOperatorSet.GenEmptyObj(out ho_ConnectedRegions); HOperatorSet.GenEmptyObj(out ho_SelectedRegions); HOperatorSet.GenEmptyObj(out ho_RegionIntersection); HOperatorSet.GenEmptyObj(out ho_RegionFillUp); HOperatorSet.GenEmptyObj(out ho_RegionTrans); HOperatorSet.GenEmptyObj(out ho_Circle1); HOperatorSet.Union1(algorithm.Region, out RegionToDisp); try { ho_Circle.Dispose(); HOperatorSet.GenCircle(out ho_Circle, DCenterRow, DCenterColumn, DRadius); ho_ImageReduced.Dispose(); HOperatorSet.ReduceDomain(Image, ho_Circle, out ho_ImageReduced); ho_Region.Dispose(); HOperatorSet.Threshold(ho_ImageReduced, out ho_Region, Dthv, 255); ho_ConnectedRegions.Dispose(); HOperatorSet.Connection(ho_Region, out ho_ConnectedRegions); ho_SelectedRegions.Dispose(); HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions, "area", "and", mjxx, mjsx); hv_ir = -1; hv_yy = -1; HOperatorSet.CountObj(ho_SelectedRegions, out hv_Number); if ((int)(new HTuple(hv_Number.TupleEqual(1))) != 0) { //ho_RegionIntersection.Dispose(); //HOperatorSet.Intersection(ho_Circle, ho_SelectedRegions, out ho_RegionIntersection // ); ho_RegionFillUp.Dispose(); HOperatorSet.FillUp(ho_SelectedRegions, out ho_RegionFillUp); ho_RegionTrans.Dispose(); HOperatorSet.ShapeTrans(ho_RegionFillUp, out ho_RegionTrans, "inner_circle"); HOperatorSet.SmallestCircle(ho_RegionTrans, out hv_Row1, out hv_Column1, out hv_Radius1); ho_RegionErosion.Dispose(); ho_RegionDilation.Dispose(); ho_RegionDilation1.Dispose(); HOperatorSet.Circularity(ho_RegionFillUp, out hv_Circularity); HOperatorSet.DilationCircle(ho_RegionFillUp, out ho_RegionDilation1, 15); HOperatorSet.ErosionCircle(ho_RegionDilation1, out ho_RegionErosion, 40); HOperatorSet.DilationCircle(ho_RegionErosion, out ho_RegionDilation, 25); HOperatorSet.Roundness(ho_RegionDilation, out hv_Distance, out hv_Sigma, out hv_Roundness, out hv_Sides); //shape_trans (RegionFillUp, RegionTrans1, 'outer_circle') //* smallest_circle (RegionTrans1, Row, Column, Radius) //* gen_region_line (RegionLines, Row, Column, Row1, Column1) //* distance_pp (Row1, Column1, Row, Column, Distance1) //* m := Radius-Radius1 //* n := Distance1 ho_Circle1.Dispose(); HOperatorSet.GenCircle(out ho_Circle1, hv_Row1, hv_Column1, hv_Radius1); if (hv_Radius1 * 2 * pixeldist >= this.mj && hv_Radius1 * 2 * pixeldist <= this.cd) { hv_ir = hv_Radius1 * 2 * pixeldist; } else { hv_ir = -1; } if (hv_Roundness >= this.y1 && hv_Roundness <= this.y2) { hv_yy = hv_Roundness; } else { hv_yy = -1; } } HOperatorSet.Union1(ho_Circle1, out RegionToDisp); HTuple hv_result = GetHv_result(); hv_result = hv_result.TupleConcat("内圆直径"); hv_result = hv_result.TupleConcat(hv_ir); hv_result = hv_result.TupleConcat("圆度"); hv_result = hv_result.TupleConcat(hv_yy); result = hv_result.Clone(); ho_Circle.Dispose(); ho_ImageReduced.Dispose(); ho_Region.Dispose(); ho_ConnectedRegions.Dispose(); ho_SelectedRegions.Dispose(); ho_RegionIntersection.Dispose(); ho_RegionFillUp.Dispose(); ho_RegionTrans.Dispose(); ho_Circle1.Dispose(); ho_RegionErosion.Dispose(); ho_RegionDilation.Dispose(); ho_RegionDilation1.Dispose(); algorithm.Region.Dispose(); } catch { HTuple hv_result = GetHv_result(); hv_result = hv_result.TupleConcat("内圆直径"); hv_result = hv_result.TupleConcat(-1); hv_result = hv_result.TupleConcat("圆度"); hv_result = hv_result.TupleConcat(-1); result = hv_result.Clone(); ho_Circle.Dispose(); ho_ImageReduced.Dispose(); ho_Region.Dispose(); ho_ConnectedRegions.Dispose(); ho_SelectedRegions.Dispose(); ho_RegionIntersection.Dispose(); ho_RegionFillUp.Dispose(); ho_RegionTrans.Dispose(); ho_Circle1.Dispose(); ho_RegionErosion.Dispose(); ho_RegionDilation.Dispose(); ho_RegionDilation1.Dispose(); algorithm.Region.Dispose(); } finally { ho_Circle.Dispose(); ho_ImageReduced.Dispose(); ho_Region.Dispose(); ho_ConnectedRegions.Dispose(); ho_SelectedRegions.Dispose(); ho_RegionIntersection.Dispose(); ho_RegionFillUp.Dispose(); ho_RegionTrans.Dispose(); ho_Circle1.Dispose(); ho_RegionErosion.Dispose(); ho_RegionDilation.Dispose(); ho_RegionDilation1.Dispose(); algorithm.Region.Dispose(); } }
/********************************************************************/ /* GRAPHICSSTACK */ /********************************************************************/ /// <summary> /// Adds an iconic object to the graphics stack similar to the way /// it is defined for the HDevelop graphics stack. /// </summary> /// <param name="obj">Iconic object</param> public void addIconicVar(HObject obj) { HObjectEntry entry; if (obj == null) return; if (obj is HImage) { double r, c; int h, w, area; string s; area = ((HImage)obj).GetDomain().AreaCenter(out r, out c); ((HImage)obj).GetImagePointer1(out s, out w, out h); if (area == (w * h)) { clearList(); // MODIFIED if ((h != heightImagePart) || (w != widthImagePart)) { heightImagePart = h; widthImagePart = w; resetImagePart(widthImagePart, heightImagePart); } }//if }//if entry = new HObjectEntry(obj, mGC.copyContextList()); HObjList.Add(entry); if (HObjList.Count > MAXNUMOBJLIST) HObjList.RemoveAt(1); }
/*******************************************************************/ private void mouseMoved(object sender, HalconDotNet.HMouseEventArgs e) { double motionX, motionY; double posX, posY; double zoomZone; //if (viewPort.) int count = HObjList.Count; foreach (var item in HObjList) //实时显示图片的灰度 灰度显示 { HObjectEntry objNow = (HObjectEntry)item; if (objNow.HObj is HImage) { try{ HObject myImg = new HObject(); if (!objNow.HObj.IsInitialized()) { break; } //HOperatorSet.CopyObj(objNow.HObj, out myImg, 1, -1); HTuple Gray = new HTuple(); HTuple Wid, Hei; HOperatorSet.GetImageSize(objNow.HObj, out Wid, out Hei); if (0 < e.Y && e.Y < Hei && 0 < e.X && e.X < Wid) { repaint(viewPort.HalconWindow); HOperatorSet.GetGrayval(objNow.HObj, e.Y, e.X, out Gray); double scale = (ImgRow2 - ImgRow1) / Hei.D; //HOperatorSet.SetTposition(viewPort.HalconWindow, ImgRow2 - 400 * scale, ImgCol2 - 400 * scale); HOperatorSet.SetTposition(viewPort.HalconWindow, e.Y + 20 * scale, e.X + 50 * scale); HOperatorSet.SetColor(viewPort.HalconWindow, "red"); HOperatorSet.WriteString(viewPort.HalconWindow, "R:" + ((int)e.Y).ToString() + " " + "C:" + ((int)e.X).ToString() + " " + ((int)Gray[0].D).ToString()); } //myImg.Dispose(); break; } catch { break; } } } if (!mousePressed) { return; } if (roiManager != null && (roiManager.activeROIidx != -1) && (dispROI == MODE_INCLUDE_ROI)) { roiManager.mouseMoveAction(e.X, e.Y); } else if (stateView == MODE_VIEW_MOVE) //平移视图 { motionX = ((e.X - startX)); motionY = ((e.Y - startY)); if (((int)motionX != 0) || ((int)motionY != 0)) { moveImage(motionX, motionY); startX = e.X - motionX; startY = e.Y - motionY; } } else if (stateView == MODE_VIEW_ZOOMWINDOW) //缩放视图 { HSystem.SetSystem("flush_graphic", "false"); ZoomWindow.ClearWindow(); posX = ((e.X - ImgCol1) / (ImgCol2 - ImgCol1)) * viewPort.Width; posY = ((e.Y - ImgRow1) / (ImgRow2 - ImgRow1)) * viewPort.Height; zoomZone = (zoomWndSize / 2) * zoomWndFactor * zoomAddOn; ZoomWindow.SetWindowExtents((int)posY - (zoomWndSize / 2), (int)posX - (zoomWndSize / 2), zoomWndSize, zoomWndSize); ZoomWindow.SetPart((int)(e.Y - zoomZone), (int)(e.X - zoomZone), (int)(e.Y + zoomZone), (int)(e.X + zoomZone)); repaint(ZoomWindow); HSystem.SetSystem("flush_graphic", "true"); ZoomWindow.DispLine(-100.0, -100.0, -100.0, -100.0); } }
public void Initialize(HImage image, HTuple modelRow, HTuple modelColumn, HTuple modelAngle) { ho_Image = image; hv_AllModelRow = new HTuple(modelRow); hv_AllModelColumn = new HTuple(modelColumn); hv_AllModelAngle = new HTuple(modelAngle); cAssistant = new MeasureAssistant(new ROIController()); }
/// <summary> /// The object will be pushed to the graphic stack of image /// display. The objects on the graphic stack will not be /// displayed automatically. To display the objects on the /// graphic stack, please call method Refresh. /// </summary> /// <param name="obj"> HALCON iconic object </param> public void AddObjectToGraphicStack(HObject obj) { lock (locker) { if (obj != null) { HObject copyObj = obj.CopyObj(1,-1); hWndControl.addIconicVarKeepSettings(obj); } } }
public void Object2minipicture(HObject obj) { HObject obj_temp; HOperatorSet.ZoomImageSize(obj, out obj_temp, 100, 100, "constant"); Bitmap = HObject_Bitmap.HObject2Bitmap(obj_temp); }
/// <summary> /// Determines whether the calibration image is overexposed /// </summary> public void eval_caltab_overexposure(HObject ho_Image, HObject ho_Caltab, out HTuple hv_OverexposureScore) { // Local iconic variables HObject ho_ImageReduced, ho_Region; // Local control variables HTuple hv_AreaCaltab, hv_Row, hv_Column, hv_AreaOverExp; HTuple hv_Thresh, hv_Ratio; // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_ImageReduced); HOperatorSet.GenEmptyObj(out ho_Region); //returns a measure of the amount of saturation of the plate hv_OverexposureScore = 0.0; HOperatorSet.AreaCenter(ho_Caltab, out hv_AreaCaltab, out hv_Row, out hv_Column); if ((int)((new HTuple(hv_AreaCaltab.TupleEqual(0))).TupleOr(new HTuple(hv_AreaCaltab.TupleEqual( new HTuple())))) != 0) { ho_ImageReduced.Dispose(); ho_Region.Dispose(); return; } ho_ImageReduced.Dispose(); HOperatorSet.ReduceDomain(ho_Image, ho_Caltab, out ho_ImageReduced); ho_Region.Dispose(); HOperatorSet.Threshold(ho_ImageReduced, out ho_Region, 255, 255); HOperatorSet.AreaCenter(ho_Region, out hv_AreaOverExp, out hv_Row, out hv_Column); hv_Thresh = 0.15; hv_Ratio = (hv_AreaOverExp.TupleReal()) / hv_AreaCaltab; if ((int)(new HTuple(hv_Ratio.TupleLess(hv_Thresh))) != 0) { hv_OverexposureScore = (((new HTuple(1.0)).TupleConcat(1 - (hv_Ratio / hv_Thresh)))).TupleMin() ; } ho_ImageReduced.Dispose(); ho_Region.Dispose(); return; }
/// <summary> /// NCC模板匹配-Roi-HObject /// </summary> /// <param name="img"></param> /// <param name="Roi"></param> /// <param name="ModelID"></param> /// <param name="MaxReturns"></param> /// <param name="MinScore"></param> /// <param name="MinAngle"></param> /// <param name="MaxAngle"></param> /// <param name="MinScal"></param> /// <param name="MaxScal"></param> /// <param name="matchresults"></param> /// <returns></returns> public static bool FindNccTemplate(VisionImage img, Roi Roi, HTuple ModelID, int MaxReturns, double MinScore, double MinAngle, double MaxAngle, double MinScal, double MaxScal, ref Variable.CamReturn camreturn)//, double MaxOverlap, double Greediness) { img.Type = ImageType.U8; HObject Himage = null, HRoi = null; HObject imgreduced = null; HTuple FindRow, FindColumn, FindAngle, FindScore; try { img.BorderWidth = 0; HOperatorSet.GenImage1(out Himage, "byte", img.Width, img.Height, img.StartPtr); //HOperatorSet.WriteImage(Himage, "bmp", 0, "D:\\1.bmp"); HOperatorSet.GenRectangle1(out HRoi, ((RectangleContour)Roi[0].Shape).Top, ((RectangleContour)Roi[0].Shape).Left, ((RectangleContour)Roi[0].Shape).Top + ((RectangleContour)Roi[0].Shape).Height, ((RectangleContour)Roi[0].Shape).Left + ((RectangleContour)Roi[0].Shape).Width); HOperatorSet.ReduceDomain(Himage, HRoi, out imgreduced);//image_rectified HOperatorSet.FindNccModel(imgreduced, ModelID, (new HTuple(MinAngle)).TupleRad(), (new HTuple(MaxAngle)).TupleRad(), MinScore, MaxReturns, 0.5, "true", 0, out FindRow, out FindColumn, out FindAngle, out FindScore); if (FindRow.Length == 0) { camreturn.X = 0; camreturn.Y = 0; camreturn.Angle = 0; camreturn.IsOK = false; Himage.Dispose(); HRoi.Dispose(); imgreduced.Dispose(); return(false); } else { camreturn.X = float.Parse(FindColumn[0].D.ToString()); camreturn.Y = float.Parse(FindRow[0].D.ToString()); camreturn.Angle = FindAngle[0].D; camreturn.IsOK = true; Himage.Dispose(); HRoi.Dispose(); imgreduced.Dispose(); return(true); } } catch (Exception a) { //PutInLog("玻璃板错误:" + a.Message); camreturn.X = 0; camreturn.Y = 0; camreturn.Angle = 0; camreturn.IsOK = false; //HOperatorSet.ClearObj(Himage); //HOperatorSet.ClearObj(HRoi); //HOperatorSet.ClearObj(imgreduced); if (Himage != null) { Himage.Dispose(); } if (HRoi != null) { HRoi.Dispose(); } if (imgreduced != null) { imgreduced.Dispose(); } return(false); } }
///<summary> ///图像预处理函数 ///</summary> public void ProcessImage(HObject ho_Image, HTuple hv_CenterRow, HTuple hv_CenterCol, HTuple hv_Phi, HTuple hv_Length1, HTuple hv_Length2, out HObject ho_Image1) { try { ImageProcessing.ImageCrop(ho_Image, hv_CenterRow, hv_CenterCol, hv_Phi, hv_Length1, hv_Length2, out HObject ho_Rectangle2, out HObject ho_ImagePart); ImageProcessing.ImageSharpening(ho_ImagePart, hv_MaskWidth, hv_MaskHeight, hv_MaskType, hv_Radius, hv_MaskSize, hv_FilterMask, hv_MultImage_Mult, hv_AddImage_Mult, hv_ScaleImage_Mult, hv_ScaleImage_Add, out HObject ho_ImageResult); ImageProcessing.ImageStitching(ho_ImageResult, ho_Image, ho_Rectangle2, hv_Phi, hv_Length1, hv_Length2, hv_CenterRow, hv_CenterCol, out ho_Image1); ProcessImageflag = true; } catch (Exception) { ho_Image1 = new HObject(); ProcessImageflag = false; } }
//Circle**************************************************************************************** /// <summary> /// 找圆-使用ROI-RectangleRegion /// </summary> /// <param name="img">图片</param> /// <param name="rectRoi">ROI</param> /// <param name="MinRadius">最小半径</param> /// <param name="MaxRadius">最大半径</param> /// <param name="Center">中心点</param> /// <param name="Radius">半径</param> /// <returns></returns> public static bool DetectCircle(VisionImage img, Roi rectRoi, double MinRadius, double MaxRadius, out PointContour Center, out double Radius) { //************************************************************************************************* Center = new PointContour(); Radius = 0; HObject ho_Image = new HObject(); HObject ho_ImageROI = new HObject(); HObject Roi = new HObject(); HObject hCircles = new HObject(); HObject countour = new HObject(); img.BorderWidth = 0; try { HOperatorSet.GenImage1(out ho_Image, "byte", img.Width, img.Height, img.StartPtr); RectangleContour rect = (RectangleContour)rectRoi[0].Shape; HOperatorSet.GenRectangle1(out Roi, rect.Top, rect.Left, rect.Top + rect.Height, rect.Left + rect.Width); HOperatorSet.ReduceDomain(ho_Image, Roi, out ho_ImageROI); //获取图像区域 形态学处理后 HOperatorSet.EdgesSubPix(ho_ImageROI, out ho_ImageROI, "canny", 1.5, 50, 75); HOperatorSet.SegmentContoursXld(ho_ImageROI, out ho_ImageROI, "lines_circles", 5, 4, 2); HOperatorSet.SelectShapeXld(ho_ImageROI, out ho_ImageROI, "outer_radius", "and", MinRadius, MaxRadius); HOperatorSet.SelectShapeXld(ho_ImageROI, out ho_ImageROI, "circularity", "and", 0.4, 1); HTuple colY, colX, rad, startPhi, endPhi, pointOrder; HOperatorSet.FitCircleContourXld(ho_ImageROI, "ahuber", -1, 2, 0, 3, 2, out colY, out colX, out rad, out startPhi, out endPhi, out pointOrder); if (colY.Length > 0) { Radius = rad[0]; int minIndex = 0; for (int i = 1; i < colY.Length; i++) { // 输出在范围之内最小的半径 和 圆心 if (rad[i] < Radius) { minIndex = i; Radius = rad[i]; } } Center.X = (float)(colX[minIndex].D); Center.Y = (float)(colY[minIndex].D); ho_Image?.Dispose(); Roi?.Dispose(); ho_ImageROI?.Dispose(); hCircles?.Dispose(); countour?.Dispose(); } else { throw new HalconException("没有扑抓的有效椭圆,请检查半径参数"); } } catch (HalconException ex) { ho_Image?.Dispose(); Roi?.Dispose(); ho_ImageROI?.Dispose(); hCircles?.Dispose(); countour?.Dispose(); return(false); } return(true); }
/// <summary> /// Auxiliary method for display purposes. Returns the coordinate system /// described by the parameters <c>hv_CamParam</c> and <c>hv_Pose</c> /// as an iconic object. /// </summary> public void get_3d_coord_system(HObject ho_ImageReference, out HObject ho_CoordSystemRegion, HTuple hv_CamParam, HTuple hv_Pose, HTuple hv_CoordAxesLength) { // Local iconic variables HObject ho_CoordSystemImage; // Local control variables HTuple hv_Width, hv_Height, hv_OldBG, hv_WindowHandle; // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_CoordSystemRegion); HOperatorSet.GenEmptyObj(out ho_CoordSystemImage); HOperatorSet.GetImageSize(ho_ImageReference, out hv_Width, out hv_Height); HOperatorSet.GetWindowAttr("background_color", out hv_OldBG); HOperatorSet.SetWindowAttr("background_color", "black"); HOperatorSet.OpenWindow(0, 0, hv_Width, hv_Height, 0, "buffer", "", out hv_WindowHandle); HOperatorSet.SetWindowAttr("background_color", hv_OldBG); HOperatorSet.SetColor(hv_WindowHandle, "white"); HOperatorSet.SetPart(hv_WindowHandle, 0, 0, hv_Height - 1, hv_Width - 1); disp_3d_coord_system(hv_WindowHandle, hv_CamParam, hv_Pose, hv_CoordAxesLength); ho_CoordSystemImage.Dispose(); HOperatorSet.DumpWindowImage(out ho_CoordSystemImage, hv_WindowHandle); HOperatorSet.CloseWindow(hv_WindowHandle); ho_CoordSystemRegion.Dispose(); HOperatorSet.Threshold(ho_CoordSystemImage, out ho_CoordSystemRegion, 255, 255); ho_CoordSystemImage.Dispose(); return; }
public bool RunThresholdTest(HWndCtrl hWndCtrl, HObject imagein, out HObject hregion) { hregion = new HObject(); return(false); }
/// <summary> /// Evaluates the sharpness of the calibration plate in the calibration /// image. /// </summary> public void eval_caltab_focus(HObject ho_Image, HObject ho_Marks, HTuple hv_Contrast, out HTuple hv_FocusScore) { // Local iconic variables HObject ho_Region, ho_RegionUnion, ho_ImageReduced; HObject ho_DerivGauss; // Local control variables HTuple hv_Number, hv_MeanGradient, hv_Deviation; HTuple hv_MinScore, hv_RawResult; // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_Region); HOperatorSet.GenEmptyObj(out ho_RegionUnion); HOperatorSet.GenEmptyObj(out ho_ImageReduced); HOperatorSet.GenEmptyObj(out ho_DerivGauss); hv_FocusScore = 0.0; if ((int)(new HTuple(hv_Contrast.TupleEqual(0))) != 0) { ho_Region.Dispose(); ho_RegionUnion.Dispose(); ho_ImageReduced.Dispose(); ho_DerivGauss.Dispose(); return; } HOperatorSet.CountObj(ho_Marks, out hv_Number); if ((int)(new HTuple(hv_Number.TupleLess(3))) != 0) { ho_Region.Dispose(); ho_RegionUnion.Dispose(); ho_ImageReduced.Dispose(); ho_DerivGauss.Dispose(); return; } ho_Region.Dispose(); HOperatorSet.GenRegionContourXld(ho_Marks, out ho_Region, "margin"); ho_RegionUnion.Dispose(); HOperatorSet.Union1(ho_Region, out ho_RegionUnion); ho_ImageReduced.Dispose(); HOperatorSet.ReduceDomain(ho_Image, ho_RegionUnion, out ho_ImageReduced); ho_DerivGauss.Dispose(); HOperatorSet.DerivateGauss(ho_ImageReduced, out ho_DerivGauss, 0.7, "gradient"); HOperatorSet.Intensity(ho_Region, ho_DerivGauss, out hv_MeanGradient, out hv_Deviation); hv_MinScore = 0.25; //Normalize the Gradient with the contrast hv_RawResult = hv_MeanGradient / hv_Contrast; hv_FocusScore = (((hv_RawResult * 4.5)).TupleSort())[(new HTuple((new HTuple(hv_RawResult.TupleLength() )) / 20.0)).TupleRound()]; hv_FocusScore = ((((((((hv_FocusScore - hv_MinScore)).TupleConcat(0.0))).TupleMax() )).TupleConcat(1.0))).TupleMin(); ho_Region.Dispose(); ho_RegionUnion.Dispose(); ho_ImageReduced.Dispose(); ho_DerivGauss.Dispose(); return; }
/// <summary> /// 尝试将现有队列中的Fov结果合并为Die结果,并输出 /// (已经被计算合并过的FovResult将不再参与计算) /// </summary> /// <returns></returns> public InspectionData[] DisChargeDieResults() { if (null == _fovResults) { return(null); } List <InspectionData> ret = new List <InspectionData>(); bool isSmallDie = _recipe.DieRowInFov * _recipe.DieColInFov > 0; //一个Fov中是否含有多个Die if (isSmallDie) //小Die { for (int i = 0; i < _fovResults.Length; i++) { DlafFovDetectResult fovResult = _fovResults[i]; if (null == fovResult) //fov检测结果还没有输入 { continue; } if (_fovCounteds[i]) //fov检测结果已经被统计过 { continue; } for (int j = 0; j < fovResult.DetectDiesRows.Length; j++) { int dieRow = _recipe.DieRowInFov * fovResult.ICRow + fovResult.DetectDiesRows[j]; //料片中的die行列值 int dieCol = _recipe.DieColInFov * fovResult.ICCol + fovResult.DetectDiesCols[j]; InspectionData inspData = new InspectionData(); inspData.RecipeID = _recipeID; inspData.LotID = _lotID; inspData.FrameID = _pieceID; inspData.FovNames = _recipe.FovNames(); inspData.TaskNamesInFovs = new string[inspData.FovNames.Length][]; for (int h = 0; h < inspData.FovNames.Length; h++) { inspData.TaskNamesInFovs[h] = _recipe.TaskNames(inspData.FovNames[h]); } inspData.Code2D = null; inspData.ColumnIndex = dieCol; inspData.RowIndex = dieRow; if (null == fovResult.DetectDiesImages) //可能无图,(作为工站/界面交互数据) { inspData.Image = null; } else { inspData.Image = fovResult.DetectDiesImages[j].Clone(); } if (!fovResult.IsDetectSuccess) //图象检测失败 { inspData.InspectionResult = InspectionResults.NG; } else //图象检测成功 { //金线区域 inspData.Wire = null; if (null != fovResult.WireRegion) { HObject wireRegion = fovResult.WireRegion; //fovResult.DetectIterms["WireRegions"]; string wrieTaskName = fovResult.WireRegionTaskName; //fovResult.DetectItemTaskNames["WireRegions"]; int taskIdx = 0; for (int h = 0; h < inspData.TaskNamesInFovs[0].Length; h++) { if (inspData.TaskNamesInFovs[0][h] == wrieTaskName) { taskIdx = h; break; } } HObject emptyRegion; HOperatorSet.GenEmptyRegion(out emptyRegion); HObject hoConcatReg; if (taskIdx == 0) { hoConcatReg = wireRegion.Clone(); for (int h = 1; h < inspData.TaskNamesInFovs[0].Length; h++) { HOperatorSet.ConcatObj(hoConcatReg, emptyRegion, out hoConcatReg); } } else { HOperatorSet.GenEmptyRegion(out hoConcatReg); for (int h = 1; h < inspData.TaskNamesInFovs[0].Length; h++) { if (taskIdx == h) { HOperatorSet.ConcatObj(hoConcatReg, wireRegion.Clone(), out hoConcatReg); } else { HOperatorSet.ConcatObj(hoConcatReg, emptyRegion, out hoConcatReg); } } } inspData.Wire = hoConcatReg; } inspData.Region = null; //保存所有出错的Region , 一维长度和序号 if (fovResult.DiesErrorRegions != null && fovResult.DiesErrorRegions[j] != null && fovResult.DiesErrorRegions[j].Length > 0) { HObject ho = fovResult.DiesErrorRegions[j][0].Clone(); for (int h = 1; h < fovResult.DiesErrorRegions[j].Length; h++) { HOperatorSet.ConcatObj(ho, fovResult.DiesErrorRegions[j][h], out ho); } inspData.Region = ho; } int[] errorCodes = fovResult.DiesErrorCodes[j]; if (errorCodes.Length == 1 && errorCodes[0] == 0) //检测合格 { inspData.InspectionResult = InspectionResults.OK; inspData.List_DefectData = null; } else { inspData.InspectionResult = InspectionResults.NG; inspData.List_DefectData = new List <DefectData>(); for (int h = 0; h < fovResult.DiesErrorCodes.Length; h++) { DefectData dd = new DefectData(); dd.DefectTypeIndex = errorCodes[h]; dd.ErrorDetail = fovResult.DiesErrorDetails[j][h]; dd.ImageIndex = _ImgIndex(fovResult.FovName, fovResult.DiesErrorTaskNames[j][h]); inspData.List_DefectData.Add(dd); } } inspData.SuccessRegion = null; //所有检测成功区域 inspData.SuccessRegionTypes = null; inspData.SuccessRegionImageIndex = null; if (null != fovResult.DetectIterms && fovResult.DetectIterms.Count > 0) //存在除了金线之外的其他检测项 { List <HObject> itemRegs = new List <HObject>(); List <string> itemTyps = new List <string>(); List <int> itemImgIdx = new List <int>(); foreach (string itemName in fovResult.DetectIterms.Keys) { itemRegs.Add(fovResult.DetectIterms[itemName]); itemTyps.Add(itemName); string tskName = fovResult.DetectItemTaskNames[itemName]; for (int k = 0; k < fovResult.TaskNames[0].Length; k++) { if (tskName == fovResult.TaskNames[k]) { itemImgIdx.Add(k); break; } } } if (itemRegs.Count() == 1) { inspData.SuccessRegion = itemRegs[0]; } else { HObject hoReg = itemRegs[0].Clone(); for (int h = 1; h < itemRegs.Count(); h++) { HOperatorSet.ConcatObj(hoReg, itemRegs[h], out hoReg); } inspData.SuccessRegion = hoReg; } inspData.SuccessRegionTypes = itemTyps.ToArray(); inspData.SuccessRegionImageIndex = itemImgIdx.ToArray(); } if (null == inspData.List_DefectData) { inspData.List_DefectData = new List <DefectData>(); } ret.Add(inspData); } _fovCounteds[i] = true; } } } else //大Die,一颗Die包含多个Fov { int fovCountInDie = _recipe.FovCount; for (int i = 0; i < _fovResults.Length; i += fovCountInDie) { bool isFovsCan2Die = true; //多个Fov是否能集成为一个Die for (int j = 0; j < fovCountInDie; j++) { if (null == _fovResults[i + j] || _fovCounteds[i]) { isFovsCan2Die = false; break; } } if (!isFovsCan2Die) { continue; } InspectionData inspData = new InspectionData(); inspData.RecipeID = _recipeID; inspData.LotID = _lotID; inspData.FrameID = _pieceID; inspData.FovNames = _recipe.FovNames(); inspData.TaskNamesInFovs = new string[inspData.FovNames.Length][]; for (int h = 0; h < inspData.FovNames.Length; h++) { inspData.TaskNamesInFovs[h] = _recipe.TaskNames(inspData.FovNames[h]); } inspData.Code2D = null; inspData.ColumnIndex = _fovResults[i].ICCol; inspData.RowIndex = _fovResults[i].ICRow; HObject hoImg = null; ////将Die所属的所有多通道的图平铺成一维数组 HObject hoWire = null; HObject hoErrorRegions = null; bool isDieOK = true; //整颗die的检测结果是否OK List <DefectData> lstDefectData = new List <DefectData>(); HObject hoSuccessRegion = null; List <string> lstSuccessRegionTypes = new List <string>(); List <int> lstSuccessImgIndex = new List <int>(); for (int j = i; j < i + fovCountInDie; j++) //将多个Fov合为一个Die { DlafFovDetectResult fovRet = _fovResults[j]; HObject hoTaskImgs = fovRet.DetectDiesImages[0]; //每个Fov中只有一个Die(的一部分) if (null == hoImg) //第一个 { hoImg = hoTaskImgs.Clone(); } else { for (int k = 0; k < hoTaskImgs.CountObj(); k++) { HOperatorSet.ConcatObj(hoImg, hoTaskImgs.CopyObj(k + 1, 1), out hoImg); } } HObject hoRegion = fovRet.WireRegion;//将所有Fov中的WireRegion平铺成一维数组 if (null == hoRegion) { HOperatorSet.GenEmptyRegion(out hoRegion); } if (null == hoWire) { hoWire = hoRegion.Clone(); for (int k = 1; k < fovRet.TaskNames.Length; k++) { HOperatorSet.ConcatObj(hoWire, hoRegion.Clone(), out hoWire); } } else { for (int k = 0; k < fovRet.TaskNames.Length; k++) { HOperatorSet.ConcatObj(hoWire, hoRegion.Clone(), out hoWire); } } if (!fovRet.IsDetectSuccess)//视觉检测失败 { } else { ///错误区域 if (fovRet.DiesErrorCodes[0].Length != 1 || fovRet.DiesErrorCodes[0][0] == 0) { isDieOK = false; DefectData df = new DefectData(); df.DefectTypeIndex = fovRet.DiesErrorCodes[0][0]; df.ErrorDetail = fovRet.DiesErrorDetails[0][0]; df.ImageIndex = _ImgIndex(fovRet.FovName, fovRet.DiesErrorTaskNames[0][0]); lstDefectData.Add(df); if (null == hoErrorRegions) { hoErrorRegions = fovRet.DiesErrorRegions[0][0].Clone(); } else { HOperatorSet.ConcatObj(hoErrorRegions, fovRet.DiesErrorRegions[0][0], out hoErrorRegions); } for (int k = 1; k < fovRet.DiesErrorCodes[0].Length; k++) { df = new DefectData(); df.DefectTypeIndex = fovRet.DiesErrorCodes[0][k]; df.ErrorDetail = fovRet.DiesErrorDetails[0][k]; df.ImageIndex = _ImgIndex(fovRet.FovName, fovRet.DiesErrorTaskNames[0][k]); lstDefectData.Add(df); HOperatorSet.ConcatObj(hoErrorRegions, fovRet.DiesErrorRegions[0][k], out hoErrorRegions); } } /*public HObject*/ if (fovRet.DetectIterms != null && fovRet.DetectIterms.Count > 0) { foreach (KeyValuePair <string, HObject> kv in fovRet.DetectIterms) { if (null == hoSuccessRegion) { hoSuccessRegion = kv.Value.Clone(); } else { HOperatorSet.ConcatObj(hoSuccessRegion, kv.Value, out hoSuccessRegion); } lstSuccessRegionTypes.Add(kv.Key); lstSuccessImgIndex.Add(_ImgIndex(fovRet.FovName, kv.Key)); } } } _fovCounteds[j] = true; } inspData.Image = hoImg; inspData.Wire = hoWire; inspData.Region = hoErrorRegions; if (isDieOK) { inspData.InspectionResult = InspectionResults.OK; inspData.List_DefectData = null; } else { inspData.InspectionResult = InspectionResults.NG; inspData.List_DefectData = lstDefectData; } if (null != hoSuccessRegion) { inspData.SuccessRegion = hoSuccessRegion; //所有检测成功区域 inspData.SuccessRegionTypes = lstSuccessRegionTypes.ToArray(); inspData.SuccessRegionImageIndex = lstSuccessImgIndex.ToArray(); } if (null == inspData.List_DefectData) { inspData.List_DefectData = new List <DefectData>(); } ret.Add(inspData); } } if (ret.Count() == 0) { return(null); } return(ret.ToArray()); }
private void action() { // Stack for temporary objects HObject[] OTemp = new HObject[20]; // Local iconic variables HObject ho_Rectangle, ho_ImageReduced; HObject ho_Region, ho_ConnectedRegions2, ho_SelectedRegions1; HObject ho_RegionUnion, ho_Rectangle2, ho_ImageReduced2; HObject ho_RegionLines, ho_RegionUnion1, ho_RegionUnion2; HObject ho_RegionUnion3, ho_Region1, ho_ConnectedRegions; HObject ho_RegionFillUp, ho_SelectedRegions, ho_SortedRegions; HObject ho_ObjectSelected1, ho_ObjectSelected = null, ho_Rectangle1 = null; HObject ho_ImageReduced1 = null, ho_Region2 = null, ho_ConnectedRegions3 = null; HObject ho_SelectedRegions2 = null, ho_Circle1 = null, ho_Circle2 = null; HObject ho_Circle3 = null, ho_Circle4 = null, ho_RegionUnionc1 = null; HObject ho_RegionUnionc2 = null, ho_RegionUnionc3 = null, ho_ConnectedRegionsc = null; HObject ho_SortedRegions1 = null, ho_ContoursL = null, ho_RegionLinesL = null; HObject ho_RegionLinesL1 = null, ho_RegionUnionL = null, ho_ConnectedRegionsL = null; HObject ho_SelectedRegionsL = null, ho_RegionFillUpL = null; HObject ho_ContoursSplitL = null, ho_SelectedContoursL = null; HObject ho_UnionContoursL = null, ho_RegionL = null, ho_RegionDifferenceL = null; HObject ho_ContoursR = null, ho_RegionLinesR = null, ho_RegionLinesR1 = null; HObject ho_RegionUnionR = null, ho_ConnectedRegionsR = null; HObject ho_SelectedRegionsR = null, ho_RegionFillUpR = null; HObject ho_ContoursSplitR = null, ho_SelectedContoursR = null; HObject ho_UnionContoursR = null, ho_RegionR = null, ho_RegionDifferenceR = null; HObject ho_ConnectedRegions1; // Local control variables HTuple hv_Width = null, hv_Height = null, hv_Row11 = null; HTuple hv_Column11 = null, hv_Row21 = null, hv_Column21 = null; HTuple hv_Row12 = null, hv_Column12 = null, hv_Row22 = null; HTuple hv_Column22 = null, hv_hi = null, hv_Number = null; HTuple hv_h = null, hv_w = null, hv_w1 = null, hv_Row4 = null; HTuple hv_Column4 = null, hv_Phi1 = null, hv_Length11 = null; HTuple hv_Length21 = null, hv_i = null, hv_Row5 = new HTuple(); HTuple hv_Column5 = new HTuple(), hv_Phi2 = new HTuple(); HTuple hv_Length12 = new HTuple(), hv_Length22 = new HTuple(); HTuple hv_Length1 = new HTuple(), hv_Row = new HTuple(); HTuple hv_Column = new HTuple(), hv_Phi = new HTuple(); HTuple hv_Length2 = new HTuple(), hv_Cos = new HTuple(); HTuple hv_Sin = new HTuple(), hv_RT_X = new HTuple(), hv_RT_Y = new HTuple(); HTuple hv_AX = new HTuple(), hv_AY = new HTuple(), hv_RB_X = new HTuple(); HTuple hv_RB_Y = new HTuple(), hv_BX = new HTuple(), hv_BY = new HTuple(); HTuple hv_LB_X = new HTuple(), hv_LB_Y = new HTuple(); HTuple hv_CX = new HTuple(), hv_CY = new HTuple(), hv_LT_X = new HTuple(); HTuple hv_LT_Y = new HTuple(), hv_DX = new HTuple(), hv_DY = new HTuple(); HTuple hv_Area = new HTuple(), hv_Row1 = new HTuple(); HTuple hv_Column1 = new HTuple(), hv_Distance = new HTuple(); HTuple hv_Distance1 = new HTuple(), hv_shapeParam = new HTuple(); HTuple hv_MetrologyHandleL = new HTuple(), hv_Index = new HTuple(); HTuple hv_RowL = new HTuple(), hv_ColumnL = new HTuple(); HTuple hv_l = new HTuple(), hv_NumberL = new HTuple(); HTuple hv_MetrologyHandleR = new HTuple(), hv_RowR = new HTuple(); HTuple hv_ColumnR = new HTuple(), hv_r = new HTuple(); HTuple hv_NumberR = new HTuple(), hv_AreaL = new HTuple(); HTuple hv_AreaR = new HTuple(), hv_Area1 = null, hv_Row2 = null; HTuple hv_Column2 = null, hv_Area2 = null, hv_Row3 = null; HTuple hv_Column3 = null, hv_hm = null, hv_wm = null, hv_w1m = null; HTuple hv_Row13 = null, hv_Column13 = null, hv_Row23 = null; HTuple hv_Column23 = null, hv_zh = null; // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_Rectangle); HOperatorSet.GenEmptyObj(out ho_ImageReduced); HOperatorSet.GenEmptyObj(out ho_Region); HOperatorSet.GenEmptyObj(out ho_ConnectedRegions2); HOperatorSet.GenEmptyObj(out ho_SelectedRegions1); HOperatorSet.GenEmptyObj(out ho_RegionUnion); HOperatorSet.GenEmptyObj(out ho_Rectangle2); HOperatorSet.GenEmptyObj(out ho_ImageReduced2); HOperatorSet.GenEmptyObj(out ho_RegionLines); HOperatorSet.GenEmptyObj(out ho_RegionUnion1); HOperatorSet.GenEmptyObj(out ho_RegionUnion2); HOperatorSet.GenEmptyObj(out ho_RegionUnion3); HOperatorSet.GenEmptyObj(out ho_Region1); HOperatorSet.GenEmptyObj(out ho_ConnectedRegions); HOperatorSet.GenEmptyObj(out ho_RegionFillUp); HOperatorSet.GenEmptyObj(out ho_SelectedRegions); HOperatorSet.GenEmptyObj(out ho_SortedRegions); HOperatorSet.GenEmptyObj(out ho_ObjectSelected1); HOperatorSet.GenEmptyObj(out ho_ObjectSelected); HOperatorSet.GenEmptyObj(out ho_Rectangle1); HOperatorSet.GenEmptyObj(out ho_ImageReduced1); HOperatorSet.GenEmptyObj(out ho_Region2); HOperatorSet.GenEmptyObj(out ho_ConnectedRegions3); HOperatorSet.GenEmptyObj(out ho_SelectedRegions2); HOperatorSet.GenEmptyObj(out ho_Circle1); HOperatorSet.GenEmptyObj(out ho_Circle2); HOperatorSet.GenEmptyObj(out ho_Circle3); HOperatorSet.GenEmptyObj(out ho_Circle4); HOperatorSet.GenEmptyObj(out ho_RegionUnionc1); HOperatorSet.GenEmptyObj(out ho_RegionUnionc2); HOperatorSet.GenEmptyObj(out ho_RegionUnionc3); HOperatorSet.GenEmptyObj(out ho_ConnectedRegionsc); HOperatorSet.GenEmptyObj(out ho_SortedRegions1); HOperatorSet.GenEmptyObj(out ho_ContoursL); HOperatorSet.GenEmptyObj(out ho_RegionLinesL); HOperatorSet.GenEmptyObj(out ho_RegionLinesL1); HOperatorSet.GenEmptyObj(out ho_RegionUnionL); HOperatorSet.GenEmptyObj(out ho_ConnectedRegionsL); HOperatorSet.GenEmptyObj(out ho_SelectedRegionsL); HOperatorSet.GenEmptyObj(out ho_RegionFillUpL); HOperatorSet.GenEmptyObj(out ho_ContoursSplitL); HOperatorSet.GenEmptyObj(out ho_SelectedContoursL); HOperatorSet.GenEmptyObj(out ho_UnionContoursL); HOperatorSet.GenEmptyObj(out ho_RegionL); HOperatorSet.GenEmptyObj(out ho_RegionDifferenceL); HOperatorSet.GenEmptyObj(out ho_ContoursR); HOperatorSet.GenEmptyObj(out ho_RegionLinesR); HOperatorSet.GenEmptyObj(out ho_RegionLinesR1); HOperatorSet.GenEmptyObj(out ho_RegionUnionR); HOperatorSet.GenEmptyObj(out ho_ConnectedRegionsR); HOperatorSet.GenEmptyObj(out ho_SelectedRegionsR); HOperatorSet.GenEmptyObj(out ho_RegionFillUpR); HOperatorSet.GenEmptyObj(out ho_ContoursSplitR); HOperatorSet.GenEmptyObj(out ho_SelectedContoursR); HOperatorSet.GenEmptyObj(out ho_UnionContoursR); HOperatorSet.GenEmptyObj(out ho_RegionR); HOperatorSet.GenEmptyObj(out ho_RegionDifferenceR); HOperatorSet.GenEmptyObj(out ho_ConnectedRegions1); HOperatorSet.Union1(algorithm.Region, out RegionToDisp); try { HOperatorSet.GetImageSize(Image, out hv_Width, out hv_Height); ho_Rectangle.Dispose(); HOperatorSet.GenRectangle1(out ho_Rectangle, DRow1m, DCol1m, DRow2m, DCol2m); ho_ImageReduced.Dispose(); HOperatorSet.ReduceDomain(Image, ho_Rectangle, out ho_ImageReduced); ho_Region.Dispose(); HOperatorSet.Threshold(ho_ImageReduced, out ho_Region, 250, 255); ho_ConnectedRegions2.Dispose(); HOperatorSet.Connection(ho_Region, out ho_ConnectedRegions2); ho_SelectedRegions1.Dispose(); HOperatorSet.SelectShape(ho_ConnectedRegions2, out ho_SelectedRegions1, "height", "and", 220, 99999); ho_RegionUnion.Dispose(); HOperatorSet.Union1(ho_SelectedRegions1, out ho_RegionUnion); HOperatorSet.SmallestRectangle1(ho_RegionUnion, out hv_Row12, out hv_Column12, out hv_Row22, out hv_Column22); ho_Rectangle2.Dispose(); HOperatorSet.GenRectangle1(out ho_Rectangle2, hv_Row12, hv_Column12, hv_Row22, hv_Column22); ho_ImageReduced2.Dispose(); HOperatorSet.ReduceDomain(ho_ImageReduced, ho_Rectangle2, out ho_ImageReduced2 ); ho_RegionLines.Dispose(); HOperatorSet.GenRegionLine(out ho_RegionLines, (hv_Row12 + hv_Row22) / 2, hv_Column12, ((hv_Row12 + hv_Row22) / 2) + 1, hv_Column12); ho_RegionUnion1.Dispose(); HOperatorSet.Union1(ho_RegionLines, out ho_RegionUnion1); ho_RegionUnion2.Dispose(); HOperatorSet.Union1(ho_RegionLines, out ho_RegionUnion2); ho_RegionUnion3.Dispose(); HOperatorSet.Union1(ho_RegionLines, out ho_RegionUnion3); ho_Region1.Dispose(); HOperatorSet.Threshold(ho_ImageReduced2, out ho_Region1, 128, 255); ho_ConnectedRegions.Dispose(); HOperatorSet.Connection(ho_Region1, out ho_ConnectedRegions); ho_RegionFillUp.Dispose(); HOperatorSet.FillUp(ho_ConnectedRegions, out ho_RegionFillUp); hv_hi = hv_Row22 - hv_Row12; ho_SelectedRegions.Dispose(); HOperatorSet.SelectShape(ho_RegionFillUp, out ho_SelectedRegions, (new HTuple("area")).TupleConcat( "height"), "and", (new HTuple(500)).TupleConcat(hv_hi * 0.4), (new HTuple(99999000)).TupleConcat( hv_hi + 2)); ho_SortedRegions.Dispose(); HOperatorSet.SortRegion(ho_SelectedRegions, out ho_SortedRegions, "upper_left", "true", "column"); HOperatorSet.CountObj(ho_SortedRegions, out hv_Number); // stop(); only in hdevelop hv_h = new HTuple(); hv_w = new HTuple(); //w1 := [] ho_ObjectSelected1.Dispose(); HOperatorSet.SelectObj(ho_SortedRegions, out ho_ObjectSelected1, 1); HOperatorSet.SmallestRectangle2(ho_ObjectSelected1, out hv_Row4, out hv_Column4, out hv_Phi1, out hv_Length11, out hv_Length21); hv_w1 = hv_Length21 * 2; HTuple end_val51 = hv_Number - 1; HTuple step_val51 = 1; for (hv_i = 2; hv_i.Continue(end_val51, step_val51); hv_i = hv_i.TupleAdd(step_val51)) { ho_ObjectSelected.Dispose(); HOperatorSet.SelectObj(ho_SortedRegions, out ho_ObjectSelected, hv_i); HOperatorSet.SmallestRectangle2(ho_ObjectSelected, out hv_Row5, out hv_Column5, out hv_Phi2, out hv_Length12, out hv_Length22); //if (Length1>(Row22-Row12)*0.25) ho_Rectangle1.Dispose(); HOperatorSet.GenRectangle2(out ho_Rectangle1, hv_Row5, hv_Column5, hv_Phi2, hv_Length12 * 0.85, hv_Length22); ho_ImageReduced1.Dispose(); HOperatorSet.ReduceDomain(ho_ImageReduced, ho_Rectangle1, out ho_ImageReduced1 ); ho_Region2.Dispose(); HOperatorSet.Threshold(ho_ImageReduced1, out ho_Region2, 128, 255); ho_ConnectedRegions3.Dispose(); HOperatorSet.Connection(ho_Region2, out ho_ConnectedRegions3); ho_SelectedRegions2.Dispose(); HOperatorSet.SelectShapeStd(ho_ConnectedRegions3, out ho_SelectedRegions2, "max_area", 70); HOperatorSet.SmallestRectangle2(ho_SelectedRegions2, out hv_Row, out hv_Column, out hv_Phi, out hv_Length1, out hv_Length2); //*矩形4个角点 HOperatorSet.TupleCos(hv_Phi, out hv_Cos); HOperatorSet.TupleSin(hv_Phi, out hv_Sin); //*dev_set_color('green') hv_RT_X = ((-hv_Length1) * hv_Cos) - (hv_Length2 * hv_Sin); hv_RT_Y = ((-hv_Length1) * hv_Sin) + (hv_Length2 * hv_Cos); ho_Circle1.Dispose(); HOperatorSet.GenCircle(out ho_Circle1, hv_Row - hv_RT_Y, hv_Column + hv_RT_X, 0.5); //*最小矩形的顶点A hv_AX = ((-hv_Length1) * hv_Cos) - (hv_Length2 * hv_Sin); hv_AY = ((-hv_Length1) * hv_Sin) + (hv_Length2 * hv_Cos); //*dev_set_color('red') hv_RB_X = (hv_Length1 * hv_Cos) - (hv_Length2 * hv_Sin); hv_RB_Y = (hv_Length1 * hv_Sin) + (hv_Length2 * hv_Cos); ho_Circle2.Dispose(); HOperatorSet.GenCircle(out ho_Circle2, hv_Row - hv_RB_Y, hv_Column + hv_RB_X, 0.5); //*最小矩形的顶点B hv_BX = (hv_Length1 * hv_Cos) - (hv_Length2 * hv_Sin); hv_BY = (hv_Length1 * hv_Sin) + (hv_Length2 * hv_Cos); //*dev_set_color('yellow') hv_LB_X = (hv_Length1 * hv_Cos) + (hv_Length2 * hv_Sin); hv_LB_Y = (hv_Length1 * hv_Sin) - (hv_Length2 * hv_Cos); ho_Circle3.Dispose(); HOperatorSet.GenCircle(out ho_Circle3, hv_Row - hv_LB_Y, hv_Column + hv_LB_X, 0.5); //*最小矩形的顶点C hv_CX = (hv_Length1 * hv_Cos) + (hv_Length2 * hv_Sin); hv_CY = (hv_Length1 * hv_Sin) - (hv_Length2 * hv_Cos); //*dev_set_color('pink') hv_LT_X = ((-hv_Length1) * hv_Cos) + (hv_Length2 * hv_Sin); hv_LT_Y = ((-hv_Length1) * hv_Sin) - (hv_Length2 * hv_Cos); ho_Circle4.Dispose(); HOperatorSet.GenCircle(out ho_Circle4, hv_Row - hv_LT_Y, hv_Column + hv_LT_X, 0.5); //*最小矩形的顶点D hv_DX = ((-hv_Length1) * hv_Cos) + (hv_Length2 * hv_Sin); hv_DY = ((-hv_Length1) * hv_Sin) - (hv_Length2 * hv_Cos); //stop () ho_RegionUnionc1.Dispose(); HOperatorSet.Union2(ho_Circle1, ho_Circle2, out ho_RegionUnionc1); ho_RegionUnionc2.Dispose(); HOperatorSet.Union2(ho_RegionUnionc1, ho_Circle3, out ho_RegionUnionc2); ho_RegionUnionc3.Dispose(); HOperatorSet.Union2(ho_RegionUnionc2, ho_Circle4, out ho_RegionUnionc3); ho_ConnectedRegionsc.Dispose(); HOperatorSet.Connection(ho_RegionUnionc3, out ho_ConnectedRegionsc); //count_obj (RegionUnionc3, Number1) ho_SortedRegions1.Dispose(); HOperatorSet.SortRegion(ho_ConnectedRegionsc, out ho_SortedRegions1, "upper_left", "true", "row"); HOperatorSet.AreaCenter(ho_SortedRegions1, out hv_Area, out hv_Row1, out hv_Column1); HOperatorSet.DistancePp(hv_Row1.TupleSelect(0), hv_Column1.TupleSelect( 0), hv_Row1.TupleSelect(1), hv_Column1.TupleSelect(1), out hv_Distance); HOperatorSet.DistancePl(hv_Row1.TupleSelect(0), hv_Column1.TupleSelect( 0), hv_Row1.TupleSelect(2), hv_Column1.TupleSelect(2), hv_Row1.TupleSelect( 3), hv_Column1.TupleSelect(3), out hv_Distance1); //if (i>1) hv_h = hv_h.TupleConcat((hv_Distance1 * 4) / 3); //endif hv_w = hv_w.TupleConcat(hv_Distance); //gen_region_line (RegionLines2, (Row1[0]+Row1[1])/2, (Column1[0]+Column1[1])/2, (Row1[2]+Row1[3])/2, (Column1[2]+Column1[3])/2) hv_shapeParam = new HTuple(); hv_shapeParam = hv_shapeParam.TupleConcat(((hv_Row1.TupleSelect( 0)) + (hv_Row1.TupleSelect(1))) / 2); hv_shapeParam = hv_shapeParam.TupleConcat(((hv_Column1.TupleSelect( 0)) + (hv_Column1.TupleSelect(1))) / 2); hv_shapeParam = hv_shapeParam.TupleConcat(((hv_Row1.TupleSelect( 2)) + (hv_Row1.TupleSelect(3))) / 2); hv_shapeParam = hv_shapeParam.TupleConcat(((hv_Column1.TupleSelect( 2)) + (hv_Column1.TupleSelect(3))) / 2); //shapeParam := [Row12,(Column22+Column12)/2,Row22,(Column22+Column12)/2] //找左侧点 HOperatorSet.CreateMetrologyModel(out hv_MetrologyHandleL); HOperatorSet.SetMetrologyModelImageSize(hv_MetrologyHandleL, hv_Width, hv_Height); HOperatorSet.AddMetrologyObjectGeneric(hv_MetrologyHandleL, "line", hv_shapeParam, (hv_Distance / 2) + 0.5, 1, 1, 60, new HTuple(), new HTuple(), out hv_Index); //设置参数 HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandleL, "all", "measure_transition", "negative"); HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandleL, "all", "num_measures", 150); HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandleL, "all", "num_instances", 1); HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandleL, "all", "measure_select", "last"); //开始找边缘 HOperatorSet.ApplyMetrologyModel(ho_ImageReduced1, hv_MetrologyHandleL); ho_ContoursL.Dispose(); HOperatorSet.GetMetrologyObjectMeasures(out ho_ContoursL, hv_MetrologyHandleL, "all", "all", out hv_RowL, out hv_ColumnL); if (HDevWindowStack.IsOpen()) { //dev_set_color ('red') } //disp_cross (3600, RowL, ColumnL, 6, Phi) //左侧点,用一Row,只取最左边点 //gen_cross_contour_xld (CrossL, RowL, ColumnL, 6, 0) ///释放测量句柄 HOperatorSet.ClearMetrologyModel(hv_MetrologyHandleL); //gen_region_line (RegionLines, Row11, Column11, Row11+1, Column11) //union1 (RegionLines, RegionUnion1) for (hv_l = 0; (int)hv_l <= (int)((new HTuple(hv_RowL.TupleLength())) - 2); hv_l = (int)hv_l + 1) { ho_RegionLinesL.Dispose(); HOperatorSet.GenRegionLine(out ho_RegionLinesL, hv_RowL.TupleSelect(hv_l), hv_ColumnL.TupleSelect(hv_l), hv_RowL.TupleSelect(hv_l + 1), hv_ColumnL.TupleSelect( hv_l + 1)); { HObject ExpTmpOutVar_0; HOperatorSet.Union2(ho_RegionUnion1, ho_RegionLinesL, out ExpTmpOutVar_0 ); ho_RegionUnion1.Dispose(); ho_RegionUnion1 = ExpTmpOutVar_0; } } ho_RegionLinesL1.Dispose(); HOperatorSet.GenRegionLine(out ho_RegionLinesL1, hv_RowL.TupleSelect(0), hv_ColumnL.TupleSelect(0), hv_RowL.TupleSelect((new HTuple(hv_RowL.TupleLength() )) - 1), hv_ColumnL.TupleSelect((new HTuple(hv_RowL.TupleLength())) - 1)); ho_RegionUnionL.Dispose(); HOperatorSet.Union2(ho_RegionUnion1, ho_RegionLinesL1, out ho_RegionUnionL ); ho_ConnectedRegionsL.Dispose(); HOperatorSet.Connection(ho_RegionUnionL, out ho_ConnectedRegionsL); ho_SelectedRegionsL.Dispose(); HOperatorSet.SelectShapeStd(ho_ConnectedRegionsL, out ho_SelectedRegionsL, "max_area", 70); ho_RegionFillUpL.Dispose(); HOperatorSet.FillUp(ho_SelectedRegionsL, out ho_RegionFillUpL); ho_ContoursL.Dispose(); HOperatorSet.GenContourRegionXld(ho_RegionFillUpL, out ho_ContoursL, "border"); ho_ContoursSplitL.Dispose(); HOperatorSet.SegmentContoursXld(ho_ContoursL, out ho_ContoursSplitL, "lines_circles", 5, 8, 3.5); ho_SelectedContoursL.Dispose(); HOperatorSet.SelectContoursXld(ho_ContoursSplitL, out ho_SelectedContoursL, "contour_length", 70, 2000, -0.5, 0.5); //*** ho_UnionContoursL.Dispose(); HOperatorSet.UnionAdjacentContoursXld(ho_SelectedContoursL, out ho_UnionContoursL, 10, 1, "attr_keep"); ho_RegionL.Dispose(); HOperatorSet.GenRegionContourXld(ho_UnionContoursL, out ho_RegionL, "filled"); ho_RegionDifferenceL.Dispose(); HOperatorSet.Difference(ho_RegionFillUpL, ho_RegionL, out ho_RegionDifferenceL ); HOperatorSet.CountObj(ho_RegionDifferenceL, out hv_NumberL); //* //找右侧点 HOperatorSet.CreateMetrologyModel(out hv_MetrologyHandleR); HOperatorSet.SetMetrologyModelImageSize(hv_MetrologyHandleR, hv_Width, hv_Height); HOperatorSet.AddMetrologyObjectGeneric(hv_MetrologyHandleR, "line", hv_shapeParam, (hv_Distance / 2) + 0.5, 1, 1, 60, new HTuple(), new HTuple(), out hv_Index); //设置参数 HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandleR, "all", "measure_transition", "positive"); HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandleR, "all", "num_measures", 100); HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandleR, "all", "num_instances", 1); HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandleR, "all", "measure_select", "first"); //开始找边缘 HOperatorSet.ApplyMetrologyModel(ho_ImageReduced1, hv_MetrologyHandleR); ho_ContoursR.Dispose(); HOperatorSet.GetMetrologyObjectMeasures(out ho_ContoursR, hv_MetrologyHandleR, "all", "all", out hv_RowR, out hv_ColumnR); //disp_obj (Image, 3600) if (HDevWindowStack.IsOpen()) { //dev_set_color ('red') } //disp_cross (3600, RowR, ColumnR, 6, Phi) //*右侧点,用一Row,只取最右边点 //gen_cross_contour_xld (CrossR, RowR, ColumnR, 6, 0) ///释放测量句柄 HOperatorSet.ClearMetrologyModel(hv_MetrologyHandleR); //close_measure (MeasureHandle1) //stop () //gen_region_line (RegionLines, Row11, Column11, Row11+1, Column11) //union1 (RegionLines, RegionUnion1) for (hv_r = 0; (int)hv_r <= (int)((new HTuple(hv_RowR.TupleLength())) - 2); hv_r = (int)hv_r + 1) { ho_RegionLinesR.Dispose(); HOperatorSet.GenRegionLine(out ho_RegionLinesR, hv_RowR.TupleSelect(hv_r), hv_ColumnR.TupleSelect(hv_r), hv_RowR.TupleSelect(hv_r + 1), hv_ColumnR.TupleSelect( hv_r + 1)); { HObject ExpTmpOutVar_0; HOperatorSet.Union2(ho_RegionUnion2, ho_RegionLinesR, out ExpTmpOutVar_0 ); ho_RegionUnion2.Dispose(); ho_RegionUnion2 = ExpTmpOutVar_0; } } ho_RegionLinesR1.Dispose(); HOperatorSet.GenRegionLine(out ho_RegionLinesR1, hv_RowR.TupleSelect(0), hv_ColumnR.TupleSelect(0), hv_RowR.TupleSelect((new HTuple(hv_RowR.TupleLength() )) - 1), hv_ColumnR.TupleSelect((new HTuple(hv_RowR.TupleLength())) - 1)); ho_RegionUnionR.Dispose(); HOperatorSet.Union2(ho_RegionUnion2, ho_RegionLinesR1, out ho_RegionUnionR ); ho_ConnectedRegionsR.Dispose(); HOperatorSet.Connection(ho_RegionUnionR, out ho_ConnectedRegionsR); ho_SelectedRegionsR.Dispose(); HOperatorSet.SelectShapeStd(ho_ConnectedRegionsR, out ho_SelectedRegionsR, "max_area", 70); ho_RegionFillUpR.Dispose(); HOperatorSet.FillUp(ho_SelectedRegionsR, out ho_RegionFillUpR); ho_ContoursR.Dispose(); HOperatorSet.GenContourRegionXld(ho_RegionFillUpR, out ho_ContoursR, "border"); ho_ContoursSplitR.Dispose(); HOperatorSet.SegmentContoursXld(ho_ContoursR, out ho_ContoursSplitR, "lines_circles", 5, 8, 3.5); ho_SelectedContoursR.Dispose(); HOperatorSet.SelectContoursXld(ho_ContoursSplitR, out ho_SelectedContoursR, "contour_length", 70, 2000, -0.5, 0.5); ho_UnionContoursR.Dispose(); HOperatorSet.UnionAdjacentContoursXld(ho_SelectedContoursR, out ho_UnionContoursR, 10, 1, "attr_keep"); ho_RegionR.Dispose(); HOperatorSet.GenRegionContourXld(ho_UnionContoursR, out ho_RegionR, "filled"); ho_RegionDifferenceR.Dispose(); HOperatorSet.Difference(ho_RegionFillUpR, ho_RegionR, out ho_RegionDifferenceR ); HOperatorSet.CountObj(ho_RegionDifferenceR, out hv_NumberR); //stop () if ((int)(new HTuple(hv_NumberL.TupleGreater(0))) != 0) { HOperatorSet.AreaCenter(ho_RegionDifferenceL, out hv_AreaL, out hv_RowL, out hv_ColumnL); { HObject ExpTmpOutVar_0; HOperatorSet.Union2(ho_RegionUnion3, ho_RegionDifferenceL, out ExpTmpOutVar_0 ); ho_RegionUnion3.Dispose(); ho_RegionUnion3 = ExpTmpOutVar_0; } } if ((int)(new HTuple(hv_NumberR.TupleGreater(0))) != 0) { HOperatorSet.AreaCenter(ho_RegionDifferenceR, out hv_AreaR, out hv_RowR, out hv_ColumnR); { HObject ExpTmpOutVar_0; HOperatorSet.Union2(ho_RegionUnion3, ho_RegionDifferenceR, out ExpTmpOutVar_0 ); ho_RegionUnion3.Dispose(); ho_RegionUnion3 = ExpTmpOutVar_0; } } //union2 (RegionDifferenceL, RegionDifferenceR, RegionUnionLR) //union2 (RegionUnion3, RegionUnionLR, RegionUnion3) // stop(); only in hdevelop //endif } HOperatorSet.AreaCenter(ho_RegionUnion3, out hv_Area1, out hv_Row2, out hv_Column2); ho_ConnectedRegions1.Dispose(); HOperatorSet.Connection(ho_RegionUnion3, out ho_ConnectedRegions1); HOperatorSet.AreaCenter(ho_ConnectedRegions1, out hv_Area2, out hv_Row3, out hv_Column3); //tuple_concat (w1, w, Concat) hv_hm = (hv_h.TupleMin()) / (hv_h.TupleMean()); hv_wm = (hv_w.TupleMax()) / (hv_w.TupleMean()); hv_w1m = hv_w1 / (hv_w.TupleMean()); ho_ObjectSelected.Dispose(); HOperatorSet.SelectObj(ho_SortedRegions, out ho_ObjectSelected, hv_Number); HOperatorSet.SmallestRectangle1(ho_ObjectSelected, out hv_Row13, out hv_Column13, out hv_Row23, out hv_Column23); hv_zh = hv_Column23 - hv_Column13; HOperatorSet.Union1(ho_ConnectedRegions1, out RegionToDisp); HTuple hv_result = GetHv_result(); hv_result = hv_result.TupleConcat("最短比值"); hv_result = hv_result.TupleConcat(hv_hm.D); hv_result = hv_result.TupleConcat("最宽比值"); hv_result = hv_result.TupleConcat(hv_wm.D); hv_result = hv_result.TupleConcat("第一条宽度比值"); hv_result = hv_result.TupleConcat(hv_w1m.D); hv_result = hv_result.TupleConcat("缺陷总面积"); hv_result = hv_result.TupleConcat(hv_Area1.D); hv_result = hv_result.TupleConcat("最大缺陷面积"); hv_result = hv_result.TupleConcat(hv_Area2.D); hv_result = hv_result.TupleConcat("宽度"); hv_result = hv_result.TupleConcat(hv_zh.D); result = hv_result.Clone(); ho_Rectangle.Dispose(); ho_ImageReduced.Dispose(); ho_Region.Dispose(); ho_ConnectedRegions2.Dispose(); ho_SelectedRegions1.Dispose(); ho_RegionUnion.Dispose(); ho_Rectangle2.Dispose(); ho_ImageReduced2.Dispose(); ho_RegionLines.Dispose(); ho_RegionUnion1.Dispose(); ho_RegionUnion2.Dispose(); ho_RegionUnion3.Dispose(); ho_Region1.Dispose(); ho_ConnectedRegions.Dispose(); ho_RegionFillUp.Dispose(); ho_SelectedRegions.Dispose(); ho_SortedRegions.Dispose(); ho_ObjectSelected1.Dispose(); ho_ObjectSelected.Dispose(); ho_Rectangle1.Dispose(); ho_ImageReduced1.Dispose(); ho_Region2.Dispose(); ho_ConnectedRegions3.Dispose(); ho_SelectedRegions2.Dispose(); ho_Circle1.Dispose(); ho_Circle2.Dispose(); ho_Circle3.Dispose(); ho_Circle4.Dispose(); ho_RegionUnionc1.Dispose(); ho_RegionUnionc2.Dispose(); ho_RegionUnionc3.Dispose(); ho_ConnectedRegionsc.Dispose(); ho_SortedRegions1.Dispose(); ho_ContoursL.Dispose(); ho_RegionLinesL.Dispose(); ho_RegionLinesL1.Dispose(); ho_RegionUnionL.Dispose(); ho_ConnectedRegionsL.Dispose(); ho_SelectedRegionsL.Dispose(); ho_RegionFillUpL.Dispose(); ho_ContoursSplitL.Dispose(); ho_SelectedContoursL.Dispose(); ho_UnionContoursL.Dispose(); ho_RegionL.Dispose(); ho_RegionDifferenceL.Dispose(); ho_ContoursR.Dispose(); ho_RegionLinesR.Dispose(); ho_RegionLinesR1.Dispose(); ho_RegionUnionR.Dispose(); ho_ConnectedRegionsR.Dispose(); ho_SelectedRegionsR.Dispose(); ho_RegionFillUpR.Dispose(); ho_ContoursSplitR.Dispose(); ho_SelectedContoursR.Dispose(); ho_UnionContoursR.Dispose(); ho_RegionR.Dispose(); ho_RegionDifferenceR.Dispose(); ho_ConnectedRegions1.Dispose(); algorithm.Region.Dispose(); } catch { HTuple hv_result = GetHv_result(); hv_result = hv_result.TupleConcat("最短比值"); hv_result = hv_result.TupleConcat(0); hv_result = hv_result.TupleConcat("最宽比值"); hv_result = hv_result.TupleConcat(0); hv_result = hv_result.TupleConcat("第一条宽度比值"); hv_result = hv_result.TupleConcat(0); hv_result = hv_result.TupleConcat("缺陷总面积"); hv_result = hv_result.TupleConcat(999999); hv_result = hv_result.TupleConcat("最大缺陷面积"); hv_result = hv_result.TupleConcat(999999); hv_result = hv_result.TupleConcat("宽度"); hv_result = hv_result.TupleConcat(999999); result = hv_result.Clone(); ho_Rectangle.Dispose(); ho_ImageReduced.Dispose(); ho_Region.Dispose(); ho_ConnectedRegions2.Dispose(); ho_SelectedRegions1.Dispose(); ho_RegionUnion.Dispose(); ho_Rectangle2.Dispose(); ho_ImageReduced2.Dispose(); ho_RegionLines.Dispose(); ho_RegionUnion1.Dispose(); ho_RegionUnion2.Dispose(); ho_RegionUnion3.Dispose(); ho_Region1.Dispose(); ho_ConnectedRegions.Dispose(); ho_RegionFillUp.Dispose(); ho_SelectedRegions.Dispose(); ho_SortedRegions.Dispose(); ho_ObjectSelected1.Dispose(); ho_ObjectSelected.Dispose(); ho_Rectangle1.Dispose(); ho_ImageReduced1.Dispose(); ho_Region2.Dispose(); ho_ConnectedRegions3.Dispose(); ho_SelectedRegions2.Dispose(); ho_Circle1.Dispose(); ho_Circle2.Dispose(); ho_Circle3.Dispose(); ho_Circle4.Dispose(); ho_RegionUnionc1.Dispose(); ho_RegionUnionc2.Dispose(); ho_RegionUnionc3.Dispose(); ho_ConnectedRegionsc.Dispose(); ho_SortedRegions1.Dispose(); ho_ContoursL.Dispose(); ho_RegionLinesL.Dispose(); ho_RegionLinesL1.Dispose(); ho_RegionUnionL.Dispose(); ho_ConnectedRegionsL.Dispose(); ho_SelectedRegionsL.Dispose(); ho_RegionFillUpL.Dispose(); ho_ContoursSplitL.Dispose(); ho_SelectedContoursL.Dispose(); ho_UnionContoursL.Dispose(); ho_RegionL.Dispose(); ho_RegionDifferenceL.Dispose(); ho_ContoursR.Dispose(); ho_RegionLinesR.Dispose(); ho_RegionLinesR1.Dispose(); ho_RegionUnionR.Dispose(); ho_ConnectedRegionsR.Dispose(); ho_SelectedRegionsR.Dispose(); ho_RegionFillUpR.Dispose(); ho_ContoursSplitR.Dispose(); ho_SelectedContoursR.Dispose(); ho_UnionContoursR.Dispose(); ho_RegionR.Dispose(); ho_RegionDifferenceR.Dispose(); ho_ConnectedRegions1.Dispose(); algorithm.Region.Dispose(); } finally { ho_Rectangle.Dispose(); ho_ImageReduced.Dispose(); ho_Region.Dispose(); ho_ConnectedRegions2.Dispose(); ho_SelectedRegions1.Dispose(); ho_RegionUnion.Dispose(); ho_Rectangle2.Dispose(); ho_ImageReduced2.Dispose(); ho_RegionLines.Dispose(); ho_RegionUnion1.Dispose(); ho_RegionUnion2.Dispose(); ho_RegionUnion3.Dispose(); ho_Region1.Dispose(); ho_ConnectedRegions.Dispose(); ho_RegionFillUp.Dispose(); ho_SelectedRegions.Dispose(); ho_SortedRegions.Dispose(); ho_ObjectSelected1.Dispose(); ho_ObjectSelected.Dispose(); ho_Rectangle1.Dispose(); ho_ImageReduced1.Dispose(); ho_Region2.Dispose(); ho_ConnectedRegions3.Dispose(); ho_SelectedRegions2.Dispose(); ho_Circle1.Dispose(); ho_Circle2.Dispose(); ho_Circle3.Dispose(); ho_Circle4.Dispose(); ho_RegionUnionc1.Dispose(); ho_RegionUnionc2.Dispose(); ho_RegionUnionc3.Dispose(); ho_ConnectedRegionsc.Dispose(); ho_SortedRegions1.Dispose(); ho_ContoursL.Dispose(); ho_RegionLinesL.Dispose(); ho_RegionLinesL1.Dispose(); ho_RegionUnionL.Dispose(); ho_ConnectedRegionsL.Dispose(); ho_SelectedRegionsL.Dispose(); ho_RegionFillUpL.Dispose(); ho_ContoursSplitL.Dispose(); ho_SelectedContoursL.Dispose(); ho_UnionContoursL.Dispose(); ho_RegionL.Dispose(); ho_RegionDifferenceL.Dispose(); ho_ContoursR.Dispose(); ho_RegionLinesR.Dispose(); ho_RegionLinesR1.Dispose(); ho_RegionUnionR.Dispose(); ho_ConnectedRegionsR.Dispose(); ho_SelectedRegionsR.Dispose(); ho_RegionFillUpR.Dispose(); ho_ContoursSplitR.Dispose(); ho_SelectedContoursR.Dispose(); ho_UnionContoursR.Dispose(); ho_RegionR.Dispose(); ho_RegionDifferenceR.Dispose(); ho_ConnectedRegions1.Dispose(); algorithm.Region.Dispose(); } }
private void addToStack(string Name, HObject obj, bool addToPL, string col, string lw, string dm) { if(addToPL) procList.Add(Name, obj); viewControl.addIconicVar(obj); IconiclistBox.Items.Add(Name); addGraphicsStackDisplay(Name, col, lw, dm); }
private void train_classifier(HTuple hv_DLClassifierHandle, HTuple hv_FileName, HTuple hv_NumEpochs, HTuple hv_TrainingImages, HTuple hv_TrainingLabels, HTuple hv_ValidationImages, HTuple hv_ValidationLabels, HTuple hv_LearningRateStepEveryNthEpoch, HTuple hv_LearningRateStepRatio, HTuple hv_PlotEveryNthEpoch, HTuple hv_WindowHandle) { // Stack for temporary objects HObject[] OTemp = new HObject[20]; // Local iconic variables HObject ho_BatchImages = null; // Local control variables HTuple hv_TrainingErrors = new HTuple(), hv_ValidationErrors = new HTuple(); HTuple hv_LearningRates = new HTuple(), hv_Epochs = new HTuple(); HTuple hv_LossByIteration = new HTuple(), hv_BatchSize = new HTuple(); HTuple hv_MinValidationError = new HTuple(), hv_NumBatchesInEpoch = new HTuple(); HTuple hv_NumTotalIterations = new HTuple(), hv_PlottedIterations = new HTuple(); HTuple hv_TrainSequence = new HTuple(), hv_SelectPercentageTrainingImages = new HTuple(); HTuple hv_TrainingImagesSelected = new HTuple(), hv_TrainingLabelsSelected = new HTuple(); HTuple hv_Epoch = new HTuple(), hv_Iteration = new HTuple(); HTuple hv_BatchStart = new HTuple(), hv_BatchEnd = new HTuple(); HTuple hv_BatchIndices = new HTuple(), hv_BatchImageFiles = new HTuple(); HTuple hv_BatchLabels = new HTuple(), hv_GenParamName = new HTuple(); HTuple hv_GenParamValue = new HTuple(), hv_DLClassifierTrainResultHandle = new HTuple(); HTuple hv_Loss = new HTuple(), hv_CurrentIteration = new HTuple(); HTuple hv_TrainingDLClassifierResultIDs = new HTuple(); HTuple hv_ValidationDLClassifierResultIDs = new HTuple(); HTuple hv_TrainingTop1Error = new HTuple(), hv_ValidationTop1Error = new HTuple(); HTuple hv_LearningRate = new HTuple(); HTupleVector hvec_TrainingPredictedLabels = new HTupleVector(1); HTupleVector hvec_TrainingConfidences = new HTupleVector(1); HTupleVector hvec_ValidationPredictedLabels = new HTupleVector(1); HTupleVector hvec_ValidationConfidences = new HTupleVector(1); // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_BatchImages); try { //For the plot during training, //we need to concatenate some intermediate results. hv_TrainingErrors.Dispose(); hv_TrainingErrors = new HTuple(); hv_ValidationErrors.Dispose(); hv_ValidationErrors = new HTuple(); hv_LearningRates.Dispose(); hv_LearningRates = new HTuple(); hv_Epochs.Dispose(); hv_Epochs = new HTuple(); hv_LossByIteration.Dispose(); hv_LossByIteration = new HTuple(); hv_BatchSize.Dispose(); HOperatorSet.GetDlClassifierParam(hv_DLClassifierHandle, "batch_size", out hv_BatchSize); hv_MinValidationError.Dispose(); hv_MinValidationError = 1; // //Create a tuple that includes all the iterations //where the plot should be computed (including the last ieration). hv_NumBatchesInEpoch.Dispose(); using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_NumBatchesInEpoch = (((((new HTuple(hv_TrainingImages.TupleLength() )) / (hv_BatchSize.TupleReal()))).TupleFloor())).TupleInt(); } hv_NumTotalIterations.Dispose(); using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_NumTotalIterations = (hv_NumBatchesInEpoch * hv_NumEpochs) - 1; } hv_PlottedIterations.Dispose(); using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_PlottedIterations = ((((hv_NumBatchesInEpoch * HTuple.TupleGenSequence( 0, hv_NumEpochs - 1, hv_PlotEveryNthEpoch))).TupleConcat(hv_NumTotalIterations))).TupleRound() ; } // //TrainSequence is used for easier indexing of the training data. using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_TrainSequence.Dispose(); HOperatorSet.TupleGenSequence(0, (new HTuple(hv_TrainingImages.TupleLength() )) - 1, 1, out hv_TrainSequence); } // //Select a subset of the training data set //in order to obtain a fast approximation //of the training error during training (plotting). hv_SelectPercentageTrainingImages.Dispose(); hv_SelectPercentageTrainingImages = 100; hv_TrainingImagesSelected.Dispose(); hv_TrainingLabelsSelected.Dispose(); select_percentage_dl_classifier_data(hv_TrainingImages, hv_TrainingLabels, hv_SelectPercentageTrainingImages, out hv_TrainingImagesSelected, out hv_TrainingLabelsSelected); // HTuple end_val25 = hv_NumEpochs - 1; HTuple step_val25 = 1; #region for (hv_Epoch = 0; hv_Epoch.Continue(end_val25, step_val25); hv_Epoch = hv_Epoch.TupleAdd(step_val25)) { //In order to get randomness in each epoch, //the training set is shuffled every epoch. { HTuple ExpTmpOutVar_0; tuple_shuffle(hv_TrainSequence, out ExpTmpOutVar_0); hv_TrainSequence.Dispose(); hv_TrainSequence = ExpTmpOutVar_0; } HTuple end_val29 = hv_NumBatchesInEpoch - 1; HTuple step_val29 = 1; for (hv_Iteration = 0; hv_Iteration.Continue(end_val29, step_val29); hv_Iteration = hv_Iteration.TupleAdd(step_val29)) { //Select a batch from the training data set. hv_BatchStart.Dispose(); using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_BatchStart = hv_Iteration * hv_BatchSize; } hv_BatchEnd.Dispose(); using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_BatchEnd = hv_BatchStart + (hv_BatchSize - 1); } hv_BatchIndices.Dispose(); using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_BatchIndices = hv_TrainSequence.TupleSelectRange( hv_BatchStart, hv_BatchEnd); } hv_BatchImageFiles.Dispose(); using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_BatchImageFiles = hv_TrainingImages.TupleSelect( hv_BatchIndices); } hv_BatchLabels.Dispose(); using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_BatchLabels = hv_TrainingLabels.TupleSelect( hv_BatchIndices); } // //Read the image of the current batch. ho_BatchImages.Dispose(); HOperatorSet.ReadImage(out ho_BatchImages, hv_BatchImageFiles); //Augment the images to get a better variety of training images. hv_GenParamName.Dispose(); hv_GenParamName = "mirror"; hv_GenParamValue.Dispose(); hv_GenParamValue = "rc"; { HObject ExpTmpOutVar_0; augment_images(ho_BatchImages, out ExpTmpOutVar_0, hv_GenParamName, hv_GenParamValue); ho_BatchImages.Dispose(); ho_BatchImages = ExpTmpOutVar_0; } // //Train the network with these images and ground truth labels. hv_DLClassifierTrainResultHandle.Dispose(); HOperatorSet.TrainDlClassifierBatch(ho_BatchImages, hv_DLClassifierHandle, hv_BatchLabels, out hv_DLClassifierTrainResultHandle); //You can access the current value of the loss function, //which should decrease during the training. hv_Loss.Dispose(); HOperatorSet.GetDlClassifierTrainResult(hv_DLClassifierTrainResultHandle, "loss", out hv_Loss); //Store the loss in a tuple . using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_LossByIteration = hv_LossByIteration.TupleConcat( hv_Loss); hv_LossByIteration.Dispose(); hv_LossByIteration = ExpTmpLocalVar_LossByIteration; } } // //In regular intervals, we want to evaluate //how well our classifier performs. hv_CurrentIteration.Dispose(); using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_CurrentIteration = ((hv_Iteration + (hv_NumBatchesInEpoch * hv_Epoch))).TupleInt() ; } if ((int)(((hv_CurrentIteration.TupleEqualElem(hv_PlottedIterations))).TupleSum() ) != 0) { //Plot the progress regularly. //Evaluate the current classifier on the training and validation set. hv_TrainingDLClassifierResultIDs.Dispose(); hvec_TrainingPredictedLabels.Dispose(); hvec_TrainingConfidences.Dispose(); apply_dl_classifier_batchwise(hv_TrainingImagesSelected, hv_DLClassifierHandle, out hv_TrainingDLClassifierResultIDs, out hvec_TrainingPredictedLabels, out hvec_TrainingConfidences); hv_ValidationDLClassifierResultIDs.Dispose(); hvec_ValidationPredictedLabels.Dispose(); hvec_ValidationConfidences.Dispose(); apply_dl_classifier_batchwise(hv_ValidationImages, hv_DLClassifierHandle, out hv_ValidationDLClassifierResultIDs, out hvec_ValidationPredictedLabels, out hvec_ValidationConfidences); //Evaluate the top-1 error on each dataset. hv_TrainingTop1Error.Dispose(); evaluate_dl_classifier(hv_TrainingLabelsSelected, hv_DLClassifierHandle, hv_TrainingDLClassifierResultIDs, "top1_error", "global", out hv_TrainingTop1Error); hv_ValidationTop1Error.Dispose(); evaluate_dl_classifier(hv_ValidationLabels, hv_DLClassifierHandle, hv_ValidationDLClassifierResultIDs, "top1_error", "global", out hv_ValidationTop1Error); //Concatenate the values for the plot. hv_LearningRate.Dispose(); HOperatorSet.GetDlClassifierParam(hv_DLClassifierHandle, "learning_rate", out hv_LearningRate); using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_TrainingErrors = hv_TrainingErrors.TupleConcat( hv_TrainingTop1Error); hv_TrainingErrors.Dispose(); hv_TrainingErrors = ExpTmpLocalVar_TrainingErrors; } } using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_ValidationErrors = hv_ValidationErrors.TupleConcat( hv_ValidationTop1Error); hv_ValidationErrors.Dispose(); hv_ValidationErrors = ExpTmpLocalVar_ValidationErrors; } } using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_LearningRates = hv_LearningRates.TupleConcat( hv_LearningRate); hv_LearningRates.Dispose(); hv_LearningRates = ExpTmpLocalVar_LearningRates; } } using (HDevDisposeHelper dh = new HDevDisposeHelper()) { { HTuple ExpTmpLocalVar_Epochs = hv_Epochs.TupleConcat( (hv_PlottedIterations.TupleSelect(new HTuple(hv_Epochs.TupleLength() ))) / (hv_NumBatchesInEpoch.TupleReal())); hv_Epochs.Dispose(); hv_Epochs = ExpTmpLocalVar_Epochs; } } //Plot validation and error against the epochs in order to //observe the progress of the training. plot_dl_classifier_training_progress(hv_TrainingErrors, hv_ValidationErrors, hv_LearningRates, hv_Epochs, hv_NumEpochs, hv_WindowHandle); //如果上面绘制坐标系到窗体过程报错,搞不定的话就用下面这句代替,直接显示训练数据到窗体 //disp_training_progress_datas(hv_TrainingErrors, hv_ValidationErrors, hv_LearningRates, hv_Epochs, hv_NumEpochs, hv_WindowHandle); if ((int)(new HTuple(hv_ValidationTop1Error.TupleLessEqual(hv_MinValidationError))) != 0) { HOperatorSet.WriteDlClassifier(hv_DLClassifierHandle, hv_FileName); hv_MinValidationError.Dispose(); hv_MinValidationError = new HTuple(hv_ValidationTop1Error); } } } //Reduce the learning rate every nth epoch. if ((int)(new HTuple((((hv_Epoch + 1) % hv_LearningRateStepEveryNthEpoch)).TupleEqual( 0))) != 0) { using (HDevDisposeHelper dh = new HDevDisposeHelper()) { HOperatorSet.SetDlClassifierParam(hv_DLClassifierHandle, "learning_rate", hv_LearningRate * hv_LearningRateStepRatio); } hv_LearningRate.Dispose(); HOperatorSet.GetDlClassifierParam(hv_DLClassifierHandle, "learning_rate", out hv_LearningRate); } } #endregion // stop(...); only in hdevelop ho_BatchImages.Dispose(); hv_TrainingErrors.Dispose(); hv_ValidationErrors.Dispose(); hv_LearningRates.Dispose(); hv_Epochs.Dispose(); hv_LossByIteration.Dispose(); hv_BatchSize.Dispose(); hv_MinValidationError.Dispose(); hv_NumBatchesInEpoch.Dispose(); hv_NumTotalIterations.Dispose(); hv_PlottedIterations.Dispose(); hv_TrainSequence.Dispose(); hv_SelectPercentageTrainingImages.Dispose(); hv_TrainingImagesSelected.Dispose(); hv_TrainingLabelsSelected.Dispose(); hv_Epoch.Dispose(); hv_Iteration.Dispose(); hv_BatchStart.Dispose(); hv_BatchEnd.Dispose(); hv_BatchIndices.Dispose(); hv_BatchImageFiles.Dispose(); hv_BatchLabels.Dispose(); hv_GenParamName.Dispose(); hv_GenParamValue.Dispose(); hv_DLClassifierTrainResultHandle.Dispose(); hv_Loss.Dispose(); hv_CurrentIteration.Dispose(); hv_TrainingDLClassifierResultIDs.Dispose(); hv_ValidationDLClassifierResultIDs.Dispose(); hv_TrainingTop1Error.Dispose(); hv_ValidationTop1Error.Dispose(); hv_LearningRate.Dispose(); hvec_TrainingPredictedLabels.Dispose(); hvec_TrainingConfidences.Dispose(); hvec_ValidationPredictedLabels.Dispose(); hvec_ValidationConfidences.Dispose(); return; } catch (HalconException HDevExpDefaultException) { ho_BatchImages.Dispose(); hv_TrainingErrors.Dispose(); hv_ValidationErrors.Dispose(); hv_LearningRates.Dispose(); hv_Epochs.Dispose(); hv_LossByIteration.Dispose(); hv_BatchSize.Dispose(); hv_MinValidationError.Dispose(); hv_NumBatchesInEpoch.Dispose(); hv_NumTotalIterations.Dispose(); hv_PlottedIterations.Dispose(); hv_TrainSequence.Dispose(); hv_SelectPercentageTrainingImages.Dispose(); hv_TrainingImagesSelected.Dispose(); hv_TrainingLabelsSelected.Dispose(); hv_Epoch.Dispose(); hv_Iteration.Dispose(); hv_BatchStart.Dispose(); hv_BatchEnd.Dispose(); hv_BatchIndices.Dispose(); hv_BatchImageFiles.Dispose(); hv_BatchLabels.Dispose(); hv_GenParamName.Dispose(); hv_GenParamValue.Dispose(); hv_DLClassifierTrainResultHandle.Dispose(); hv_Loss.Dispose(); hv_CurrentIteration.Dispose(); hv_TrainingDLClassifierResultIDs.Dispose(); hv_ValidationDLClassifierResultIDs.Dispose(); hv_TrainingTop1Error.Dispose(); hv_ValidationTop1Error.Dispose(); hv_LearningRate.Dispose(); hvec_TrainingPredictedLabels.Dispose(); hvec_TrainingConfidences.Dispose(); hvec_ValidationPredictedLabels.Dispose(); hvec_ValidationConfidences.Dispose(); throw HDevExpDefaultException; } }
/// <summary>Constructor</summary> /// <param name="obj"> /// HALCON object that is linked to the graphical context gc. /// </param> /// <param name="gc"> /// Hashlist of graphical states that are applied before the object /// is displayed. /// </param> public HObjectEntry(HObject obj, Hashtable gc) { gContext = gc; HObj = obj; }
private void action() { int log = 0; // Local iconic variables HObject ho_Image, ho_MarkContours = null; // Local control variables HTuple hv_AllCalibImageFiles = null, hv_ImageFiles = null; HTuple hv_Width = null, hv_Height = null, hv_CalibDataID = null; HTuple hv_CalPlateDescr = null, hv_StartParam = null, hv_Index = null; HTuple hv_StartPose = new HTuple(), hv_Error = null, hv_CameraParametersCalibrated = null; HTuple hv_ParLabels = null; // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_Image); HOperatorSet.GenEmptyObj(out ho_MarkContours); //This example shows how to perform the basic calibration of a single //camera with multiple images of a calibration object. //Initialize visualization list_image_files(ImagePath, "default", new HTuple(), out hv_AllCalibImageFiles); HOperatorSet.TupleRegexpSelect(hv_AllCalibImageFiles, "calib_single_camera", out hv_ImageFiles); ho_Image.Dispose(); HOperatorSet.ReadImage(out ho_Image, hv_ImageFiles); HOperatorSet.GetImageSize(ho_Image, out hv_Width, out hv_Height); // //Create the 3d object models that visualize the current configuration //of camera and calibration plate. This may take a moment. // //Part I // //Create and setup the calibration model // //First, create the calibration data structure HOperatorSet.CreateCalibData("calibration_object", 1, 1, out hv_CalibDataID); //Specify the used calibration plane using the name of the //description file hv_CalPlateDescr = "calplate_" + txtCalibtate.Text + "mm.cpd"; try { HOperatorSet.SetCalibDataCalibObject(hv_CalibDataID, 0, hv_CalPlateDescr); } catch { if (log == 0) { log = 1; } } double sx = System.Convert.ToDouble(txtSx.Text); double sy = System.Convert.ToDouble(txtSy.Text); hv_StartParam = new HTuple(); hv_StartParam[0] = System.Convert.ToDouble(txtFocus.Text); hv_StartParam[1] = System.Convert.ToDouble(txtKappa.Text); hv_StartParam[2] = sx * 1e-006; hv_StartParam[3] = sy * 1e-006; hv_StartParam[4] = System.Convert.ToDouble(txtCx.Text); hv_StartParam[5] = System.Convert.ToDouble(txtCy.Text); hv_StartParam[6] = System.Convert.ToDouble(txtIx.Text); hv_StartParam[7] = System.Convert.ToDouble(txtIy.Text); HOperatorSet.SetCalibDataCamParam(hv_CalibDataID, 0, "area_scan_division", hv_StartParam); try { for (hv_Index = 0; (int)hv_Index <= (int)((new HTuple(hv_ImageFiles.TupleLength() )) - 1); hv_Index = (int)hv_Index + 1) { try { ho_Image.Dispose(); HOperatorSet.ReadImage(out ho_Image, hv_ImageFiles.TupleSelect(hv_Index)); HOperatorSet.FindCalibObject(ho_Image, hv_CalibDataID, 0, 0, hv_Index, new HTuple(), new HTuple()); HOperatorSet.GetCalibDataObservPose(hv_CalibDataID, 0, 0, hv_Index, out hv_StartPose); ho_MarkContours.Dispose(); HOperatorSet.GetCalibDataObservContours(out ho_MarkContours, hv_CalibDataID, "marks", 0, 0, hv_Index); //图像标定成功 txtLog.Text = txtLog.Text + "图像" + hv_Index.ToString() + "处理成功" + "\r\n" + DateTime.Now + "\r\n"; } catch { if (log == 0) { txtLog.Text = txtLog.Text + "图像" + hv_Index.ToString() + "处理失败" + "\r\n" + DateTime.Now + "\r\n"; } //图像标定失败 } } HOperatorSet.CalibrateCameras(hv_CalibDataID, out hv_Error); HOperatorSet.GetCalibData(hv_CalibDataID, "camera", 0, "params", out hv_CameraParametersCalibrated); HOperatorSet.GetCalibData(hv_CalibDataID, "camera", 0, "params_labels", out hv_ParLabels); HOperatorSet.ClearCalibData(hv_CalibDataID); ho_Image.Dispose(); ho_MarkContours.Dispose(); //txtLog.Clear(); txtLog.Text = txtLog.Text + "相机内参" + hv_CameraParametersCalibrated.ToString() + "\r\n" + DateTime.Now + "\r\n"; } catch { if (log == 0) { log = 2; } } switch (log) { case 1: txtLog.Text = txtLog.Text + "相机参数错误,标定失败" + "\r\n" + DateTime.Now + "\r\n"; break; case 2: txtLog.Text = txtLog.Text + "图像质量出现问题,标定失败" + "\r\n" + DateTime.Now + "\r\n"; break; default: txtLog.Text = txtLog.Text + "标定成功" + "\r\n" + DateTime.Now + "\r\n"; break; } }
/// <summary> /// Evaluates the area covered by the calibration plate in the calibration /// image. /// </summary> public void eval_caltab_size(HObject ho_Image, HObject ho_Caltab, HObject ho_Marks, out HTuple hv_SizeScore) { // Local iconic variables HObject ho_Region = null, ho_RegionUnion = null; // Local control variables HTuple hv_Width, hv_Height, hv_Number, hv_Row1 = new HTuple(); HTuple hv_Column1 = new HTuple(), hv_Phi1 = new HTuple(), hv_Length1 = new HTuple(); HTuple hv_Length2 = new HTuple(), hv_Area = new HTuple(), hv_Row = new HTuple(); HTuple hv_Column = new HTuple(), hv_MinRatio, hv_MaxRatio; HTuple hv_Ratio; // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_Region); HOperatorSet.GenEmptyObj(out ho_RegionUnion); hv_SizeScore = 0.0; HOperatorSet.GetImageSize(ho_Image, out hv_Width, out hv_Height); HOperatorSet.CountObj(ho_Marks, out hv_Number); if ((int)(new HTuple(hv_Number.TupleGreaterEqual(4))) != 0) { //Best approach: Use the surrounding box of the marks as reference size ho_Region.Dispose(); HOperatorSet.GenRegionContourXld(ho_Marks, out ho_Region, "filled"); ho_RegionUnion.Dispose(); HOperatorSet.Union1(ho_Region, out ho_RegionUnion); HOperatorSet.SmallestRectangle2(ho_RegionUnion, out hv_Row1, out hv_Column1, out hv_Phi1, out hv_Length1, out hv_Length2); hv_Area = (hv_Length2 * hv_Length1) * 4; } else { //If no marks could be found: use the caltab as reference size HOperatorSet.AreaCenter(ho_Caltab, out hv_Area, out hv_Row, out hv_Column); if ((int)((new HTuple(hv_Area.TupleEqual(0))).TupleOr(new HTuple(hv_Area.TupleEqual( new HTuple())))) != 0) { ho_Region.Dispose(); ho_RegionUnion.Dispose(); return; } } hv_MinRatio = 0.015; hv_MaxRatio = 0.075; hv_Ratio = (hv_Area.TupleReal()) / (hv_Width * hv_Height); if ((int)(new HTuple(hv_Ratio.TupleGreater(hv_MinRatio))) != 0) { hv_SizeScore = (hv_Ratio - hv_MinRatio) / (hv_MaxRatio - hv_MinRatio); hv_SizeScore = (((new HTuple(1.0)).TupleConcat(hv_SizeScore))).TupleMin(); } ho_Region.Dispose(); ho_RegionUnion.Dispose(); return; }
private void CalibFormMain_ChangeSide(int SideId, HObject arg1, HObject arg2, HObject arg3) { if (SideId != -1) { SideID = SideId; } if (arg1 != null) { hwindow_final.HobjectToHimage(arg1); } }
/// <summary> /// Extracts the calibration plate and the marks on this plate /// for the supplied image /// </summary> public void find_caltab_edges(HObject ho_Image, out HObject ho_Caltab, out HObject ho_Marks, HTuple hv_DescriptionFileName) { // Stack for temporary objects HObject[] OTemp = new HObject[20]; // Local iconic variables HObject ho_ImageMean, ho_RegionDynThresh, ho_RegionBorder; HObject ho_RegionOpening1, ho_ConnectedRegions1, ho_SelectedRegions4; HObject ho_SelectedRegions5, ho_RegionBorder2, ho_RegionTrans; HObject ho_RegionErosion, ho_RegionBorder1, ho_RegionDilation2; HObject ho_RegionDifference1, ho_RegionOpening, ho_ConnectedRegions; HObject ho_SelectedRegions2, ho_SelectedRegions, ho_RegionFillUp; HObject ho_SelectedRegions1, ho_RegionIntersection, ho_RegionFillUp1; HObject ho_RegionDifference, ho_CaltabCandidates, ho_ObjectSelected = null; HObject ho_ConnectedMarks = null, ho_ObjectSelectedCaltab = null; HObject ho_RegionFillUpCand, ho_MarksCand, ho_RegionDilation1; HObject ho_ImageReduced, ho_DefaultEdges, ho_UnionContours; HObject ho_SelectedXLD, ho_SelectedXLD1; // Local control variables HTuple hv_Width, hv_Height, hv_EstimatedCaltabSize; HTuple hv_EstimatedMarkSize, hv_Number, hv_X, hv_Y, hv_Z; HTuple hv_NumDescrMarks, hv_Index, hv_NumberMarks = new HTuple(); HTuple hv_Anisometry = new HTuple(), hv_Bulkiness = new HTuple(); HTuple hv_StructureFactor = new HTuple(), hv_AreaMarks = new HTuple(); HTuple hv_Row = new HTuple(), hv_Column = new HTuple(), hv_Rectangularity; HTuple hv_SortedIndex, hv_IndexBest, hv_MinContrast, hv_NumberCand; HTuple hv_Area, hv_Dummy, hv_DummyS, hv_AreaMedian; // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_Caltab); HOperatorSet.GenEmptyObj(out ho_Marks); HOperatorSet.GenEmptyObj(out ho_ImageMean); HOperatorSet.GenEmptyObj(out ho_RegionDynThresh); HOperatorSet.GenEmptyObj(out ho_RegionBorder); HOperatorSet.GenEmptyObj(out ho_RegionOpening1); HOperatorSet.GenEmptyObj(out ho_ConnectedRegions1); HOperatorSet.GenEmptyObj(out ho_SelectedRegions4); HOperatorSet.GenEmptyObj(out ho_SelectedRegions5); HOperatorSet.GenEmptyObj(out ho_RegionBorder2); HOperatorSet.GenEmptyObj(out ho_RegionTrans); HOperatorSet.GenEmptyObj(out ho_RegionErosion); HOperatorSet.GenEmptyObj(out ho_RegionBorder1); HOperatorSet.GenEmptyObj(out ho_RegionDilation2); HOperatorSet.GenEmptyObj(out ho_RegionDifference1); HOperatorSet.GenEmptyObj(out ho_RegionOpening); HOperatorSet.GenEmptyObj(out ho_ConnectedRegions); HOperatorSet.GenEmptyObj(out ho_SelectedRegions2); HOperatorSet.GenEmptyObj(out ho_SelectedRegions); HOperatorSet.GenEmptyObj(out ho_RegionFillUp); HOperatorSet.GenEmptyObj(out ho_SelectedRegions1); HOperatorSet.GenEmptyObj(out ho_RegionIntersection); HOperatorSet.GenEmptyObj(out ho_RegionFillUp1); HOperatorSet.GenEmptyObj(out ho_RegionDifference); HOperatorSet.GenEmptyObj(out ho_CaltabCandidates); HOperatorSet.GenEmptyObj(out ho_ObjectSelected); HOperatorSet.GenEmptyObj(out ho_ConnectedMarks); HOperatorSet.GenEmptyObj(out ho_ObjectSelectedCaltab); HOperatorSet.GenEmptyObj(out ho_RegionFillUpCand); HOperatorSet.GenEmptyObj(out ho_MarksCand); HOperatorSet.GenEmptyObj(out ho_RegionDilation1); HOperatorSet.GenEmptyObj(out ho_ImageReduced); HOperatorSet.GenEmptyObj(out ho_DefaultEdges); HOperatorSet.GenEmptyObj(out ho_UnionContours); HOperatorSet.GenEmptyObj(out ho_SelectedXLD); HOperatorSet.GenEmptyObj(out ho_SelectedXLD1); // ho_Marks.Dispose(); HOperatorSet.GenEmptyObj(out ho_Marks); ho_Caltab.Dispose(); HOperatorSet.GenEmptyObj(out ho_Caltab); HOperatorSet.GetImageSize(ho_Image, out hv_Width, out hv_Height); hv_EstimatedCaltabSize = (((((hv_Width.TupleConcat(hv_Height))).TupleMax()) / 2.5)).TupleRound() ; hv_EstimatedMarkSize = ((hv_EstimatedCaltabSize / 12.0)).TupleRound(); ho_ImageMean.Dispose(); HOperatorSet.MeanImage(ho_Image, out ho_ImageMean, hv_EstimatedMarkSize * 3, hv_EstimatedMarkSize * 3); ho_RegionDynThresh.Dispose(); HOperatorSet.DynThreshold(ho_Image, ho_ImageMean, out ho_RegionDynThresh, 3, "light"); ho_RegionBorder.Dispose(); HOperatorSet.DynThreshold(ho_Image, ho_ImageMean, out ho_RegionBorder, 20, "dark"); ho_RegionOpening1.Dispose(); HOperatorSet.OpeningCircle(ho_RegionBorder, out ho_RegionOpening1, 1.5); ho_ConnectedRegions1.Dispose(); HOperatorSet.Connection(ho_RegionOpening1, out ho_ConnectedRegions1); ho_SelectedRegions4.Dispose(); HOperatorSet.SelectShape(ho_ConnectedRegions1, out ho_SelectedRegions4, "compactness", "and", 17, 50); ho_SelectedRegions5.Dispose(); HOperatorSet.SelectShape(ho_SelectedRegions4, out ho_SelectedRegions5, "anisometry", "and", 1, 1.4); ho_RegionBorder2.Dispose(); HOperatorSet.Boundary(ho_SelectedRegions5, out ho_RegionBorder2, "outer"); ho_SelectedRegions5.Dispose(); HOperatorSet.SelectShape(ho_RegionBorder2, out ho_SelectedRegions5, "circularity", "and", 0.006, 1); ho_RegionTrans.Dispose(); HOperatorSet.ShapeTrans(ho_SelectedRegions5, out ho_RegionTrans, "rectangle2"); ho_RegionErosion.Dispose(); HOperatorSet.ErosionCircle(ho_RegionTrans, out ho_RegionErosion, (hv_Width / 640.0) * 5.5); ho_RegionBorder1.Dispose(); HOperatorSet.Boundary(ho_RegionErosion, out ho_RegionBorder1, "inner"); ho_RegionDilation2.Dispose(); HOperatorSet.DilationCircle(ho_RegionBorder1, out ho_RegionDilation2, 3.5); ho_RegionDifference1.Dispose(); HOperatorSet.Difference(ho_RegionDynThresh, ho_RegionDilation2, out ho_RegionDifference1 ); ho_RegionOpening.Dispose(); HOperatorSet.OpeningCircle(ho_RegionDifference1, out ho_RegionOpening, (hv_Width / 640) * 1.5); ho_ConnectedRegions.Dispose(); HOperatorSet.Connection(ho_RegionOpening, out ho_ConnectedRegions); ho_SelectedRegions2.Dispose(); HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions2, "area", "and", (hv_EstimatedCaltabSize.TuplePow(2)) / 10, (hv_EstimatedCaltabSize.TuplePow( 2)) * 5); ho_SelectedRegions.Dispose(); HOperatorSet.SelectShape(ho_SelectedRegions2, out ho_SelectedRegions, "compactness", "and", 1.4, 10); ho_RegionFillUp.Dispose(); HOperatorSet.FillUp(ho_SelectedRegions, out ho_RegionFillUp); ho_SelectedRegions1.Dispose(); HOperatorSet.SelectShape(ho_RegionFillUp, out ho_SelectedRegions1, "rectangularity", "and", 0.6, 1); ho_RegionIntersection.Dispose(); HOperatorSet.Intersection(ho_SelectedRegions1, ho_RegionDynThresh, out ho_RegionIntersection ); ho_RegionFillUp1.Dispose(); HOperatorSet.FillUp(ho_RegionIntersection, out ho_RegionFillUp1); ho_RegionDifference.Dispose(); HOperatorSet.Difference(ho_RegionFillUp1, ho_RegionIntersection, out ho_RegionDifference ); HOperatorSet.CountObj(ho_RegionDifference, out hv_Number); ho_CaltabCandidates.Dispose(); HOperatorSet.GenEmptyObj(out ho_CaltabCandidates); HOperatorSet.CaltabPoints(hv_DescriptionFileName, out hv_X, out hv_Y, out hv_Z); hv_NumDescrMarks = new HTuple(hv_X.TupleLength()); for (hv_Index = 1; hv_Index.Continue(hv_Number, 1); hv_Index = hv_Index.TupleAdd(1)) { ho_ObjectSelected.Dispose(); HOperatorSet.SelectObj(ho_RegionDifference, out ho_ObjectSelected, hv_Index); ho_ConnectedMarks.Dispose(); HOperatorSet.Connection(ho_ObjectSelected, out ho_ConnectedMarks); HOperatorSet.CountObj(ho_ConnectedMarks, out hv_NumberMarks); HOperatorSet.Eccentricity(ho_ConnectedMarks, out hv_Anisometry, out hv_Bulkiness, out hv_StructureFactor); HOperatorSet.AreaCenter(ho_ConnectedMarks, out hv_AreaMarks, out hv_Row, out hv_Column); ho_ObjectSelectedCaltab.Dispose(); HOperatorSet.SelectObj(ho_RegionIntersection, out ho_ObjectSelectedCaltab, hv_Index); if ((int)((new HTuple((new HTuple((new HTuple(hv_NumberMarks.TupleGreaterEqual( 10))).TupleAnd(new HTuple(hv_NumberMarks.TupleLess(hv_NumDescrMarks + 20))))).TupleAnd( new HTuple(((((hv_Anisometry.TupleSort())).TupleSelect((new HTuple(hv_Anisometry.TupleLength() )) / 2))).TupleLess(2))))).TupleAnd(new HTuple((new HTuple(hv_AreaMarks.TupleMean() )).TupleGreater(20)))) != 0) { HOperatorSet.ConcatObj(ho_CaltabCandidates, ho_ObjectSelectedCaltab, out OTemp[0] ); ho_CaltabCandidates.Dispose(); ho_CaltabCandidates = OTemp[0]; } } ho_RegionFillUpCand.Dispose(); HOperatorSet.FillUp(ho_CaltabCandidates, out ho_RegionFillUpCand); HOperatorSet.Rectangularity(ho_RegionFillUpCand, out hv_Rectangularity); if ((int)(new HTuple((new HTuple(hv_Rectangularity.TupleLength())).TupleEqual( 0))) != 0) { ho_ImageMean.Dispose(); ho_RegionDynThresh.Dispose(); ho_RegionBorder.Dispose(); ho_RegionOpening1.Dispose(); ho_ConnectedRegions1.Dispose(); ho_SelectedRegions4.Dispose(); ho_SelectedRegions5.Dispose(); ho_RegionBorder2.Dispose(); ho_RegionTrans.Dispose(); ho_RegionErosion.Dispose(); ho_RegionBorder1.Dispose(); ho_RegionDilation2.Dispose(); ho_RegionDifference1.Dispose(); ho_RegionOpening.Dispose(); ho_ConnectedRegions.Dispose(); ho_SelectedRegions2.Dispose(); ho_SelectedRegions.Dispose(); ho_RegionFillUp.Dispose(); ho_SelectedRegions1.Dispose(); ho_RegionIntersection.Dispose(); ho_RegionFillUp1.Dispose(); ho_RegionDifference.Dispose(); ho_CaltabCandidates.Dispose(); ho_ObjectSelected.Dispose(); ho_ConnectedMarks.Dispose(); ho_ObjectSelectedCaltab.Dispose(); ho_RegionFillUpCand.Dispose(); ho_MarksCand.Dispose(); ho_RegionDilation1.Dispose(); ho_ImageReduced.Dispose(); ho_DefaultEdges.Dispose(); ho_UnionContours.Dispose(); ho_SelectedXLD.Dispose(); ho_SelectedXLD1.Dispose(); return; } hv_SortedIndex = hv_Rectangularity.TupleSortIndex(); hv_IndexBest = (((hv_SortedIndex.TupleInverse())).TupleSelect(0)) + 1; ho_Caltab.Dispose(); HOperatorSet.SelectObj(ho_RegionFillUpCand, out ho_Caltab, hv_IndexBest); ho_RegionFillUp.Dispose(); HOperatorSet.FillUp(ho_Caltab, out ho_RegionFillUp); ho_MarksCand.Dispose(); HOperatorSet.Difference(ho_RegionFillUp, ho_RegionDynThresh, out ho_MarksCand ); ho_RegionBorder.Dispose(); HOperatorSet.Boundary(ho_MarksCand, out ho_RegionBorder, "inner"); ho_RegionDilation1.Dispose(); HOperatorSet.DilationCircle(ho_RegionBorder, out ho_RegionDilation1, 9.5); ho_ImageReduced.Dispose(); HOperatorSet.ReduceDomain(ho_Image, ho_RegionDilation1, out ho_ImageReduced); hv_MinContrast = 10; ho_DefaultEdges.Dispose(); HOperatorSet.EdgesSubPix(ho_ImageReduced, out ho_DefaultEdges, "canny", 2, hv_MinContrast / 2, hv_MinContrast); HOperatorSet.CountObj(ho_DefaultEdges, out hv_NumberCand); if ((int)(new HTuple(hv_NumberCand.TupleLess(10))) != 0) { ho_ImageMean.Dispose(); ho_RegionDynThresh.Dispose(); ho_RegionBorder.Dispose(); ho_RegionOpening1.Dispose(); ho_ConnectedRegions1.Dispose(); ho_SelectedRegions4.Dispose(); ho_SelectedRegions5.Dispose(); ho_RegionBorder2.Dispose(); ho_RegionTrans.Dispose(); ho_RegionErosion.Dispose(); ho_RegionBorder1.Dispose(); ho_RegionDilation2.Dispose(); ho_RegionDifference1.Dispose(); ho_RegionOpening.Dispose(); ho_ConnectedRegions.Dispose(); ho_SelectedRegions2.Dispose(); ho_SelectedRegions.Dispose(); ho_RegionFillUp.Dispose(); ho_SelectedRegions1.Dispose(); ho_RegionIntersection.Dispose(); ho_RegionFillUp1.Dispose(); ho_RegionDifference.Dispose(); ho_CaltabCandidates.Dispose(); ho_ObjectSelected.Dispose(); ho_ConnectedMarks.Dispose(); ho_ObjectSelectedCaltab.Dispose(); ho_RegionFillUpCand.Dispose(); ho_MarksCand.Dispose(); ho_RegionDilation1.Dispose(); ho_ImageReduced.Dispose(); ho_DefaultEdges.Dispose(); ho_UnionContours.Dispose(); ho_SelectedXLD.Dispose(); ho_SelectedXLD1.Dispose(); return; } ho_UnionContours.Dispose(); HOperatorSet.UnionCocircularContoursXld(ho_DefaultEdges, out ho_UnionContours, 0.5, 0.1, 0.2, 30, 10, 10, "true", 1); ho_SelectedXLD.Dispose(); HOperatorSet.SelectShapeXld(ho_UnionContours, out ho_SelectedXLD, "area", "and", 30, 10000); ho_SelectedXLD1.Dispose(); HOperatorSet.SelectShapeXld(ho_SelectedXLD, out ho_SelectedXLD1, "circularity", "and", 0.4, 1); ho_MarksCand.Dispose(); HOperatorSet.SelectShapeXld(ho_SelectedXLD1, out ho_MarksCand, "compactness", "and", 1, 1.5); HOperatorSet.AreaCenterXld(ho_MarksCand, out hv_Area, out hv_Dummy, out hv_Dummy, out hv_DummyS); HOperatorSet.CountObj(ho_MarksCand, out hv_Number); if ((int)(new HTuple(hv_Number.TupleLess(4))) != 0) { ho_ImageMean.Dispose(); ho_RegionDynThresh.Dispose(); ho_RegionBorder.Dispose(); ho_RegionOpening1.Dispose(); ho_ConnectedRegions1.Dispose(); ho_SelectedRegions4.Dispose(); ho_SelectedRegions5.Dispose(); ho_RegionBorder2.Dispose(); ho_RegionTrans.Dispose(); ho_RegionErosion.Dispose(); ho_RegionBorder1.Dispose(); ho_RegionDilation2.Dispose(); ho_RegionDifference1.Dispose(); ho_RegionOpening.Dispose(); ho_ConnectedRegions.Dispose(); ho_SelectedRegions2.Dispose(); ho_SelectedRegions.Dispose(); ho_RegionFillUp.Dispose(); ho_SelectedRegions1.Dispose(); ho_RegionIntersection.Dispose(); ho_RegionFillUp1.Dispose(); ho_RegionDifference.Dispose(); ho_CaltabCandidates.Dispose(); ho_ObjectSelected.Dispose(); ho_ConnectedMarks.Dispose(); ho_ObjectSelectedCaltab.Dispose(); ho_RegionFillUpCand.Dispose(); ho_MarksCand.Dispose(); ho_RegionDilation1.Dispose(); ho_ImageReduced.Dispose(); ho_DefaultEdges.Dispose(); ho_UnionContours.Dispose(); ho_SelectedXLD.Dispose(); ho_SelectedXLD1.Dispose(); return; } hv_AreaMedian = ((hv_Area.TupleSort())).TupleSelect(hv_Number / 2); ho_Marks.Dispose(); HOperatorSet.SelectShapeXld(ho_MarksCand, out ho_Marks, "area", "and", hv_AreaMedian - (hv_AreaMedian * 0.5), hv_AreaMedian + (hv_AreaMedian * 0.5)); ho_ImageMean.Dispose(); ho_RegionDynThresh.Dispose(); ho_RegionBorder.Dispose(); ho_RegionOpening1.Dispose(); ho_ConnectedRegions1.Dispose(); ho_SelectedRegions4.Dispose(); ho_SelectedRegions5.Dispose(); ho_RegionBorder2.Dispose(); ho_RegionTrans.Dispose(); ho_RegionErosion.Dispose(); ho_RegionBorder1.Dispose(); ho_RegionDilation2.Dispose(); ho_RegionDifference1.Dispose(); ho_RegionOpening.Dispose(); ho_ConnectedRegions.Dispose(); ho_SelectedRegions2.Dispose(); ho_SelectedRegions.Dispose(); ho_RegionFillUp.Dispose(); ho_SelectedRegions1.Dispose(); ho_RegionIntersection.Dispose(); ho_RegionFillUp1.Dispose(); ho_RegionDifference.Dispose(); ho_CaltabCandidates.Dispose(); ho_ObjectSelected.Dispose(); ho_ConnectedMarks.Dispose(); ho_ObjectSelectedCaltab.Dispose(); ho_RegionFillUpCand.Dispose(); ho_MarksCand.Dispose(); ho_RegionDilation1.Dispose(); ho_ImageReduced.Dispose(); ho_DefaultEdges.Dispose(); ho_UnionContours.Dispose(); ho_SelectedXLD.Dispose(); ho_SelectedXLD1.Dispose(); return; }
private void simpleButton1_Click(object sender, EventArgs e) { try { if (MessageBox.Show("是否标定Side" + (SideID + 1).ToString(), "Warning", MessageBoxButtons.YesNo) == DialogResult.No) { return; } HTuple row, col; string ok = RunIntersection(out row, out col); if (ok != "OK") { label_result.Text = ok; label_result.BackColor = Color.Red; return; } StringBuilder PixStr = new StringBuilder(); dataGridView1.Rows.Clear(); dataGridView1.AllowUserToAddRows = false; if (MyGlobal.globalPointSet_Left.imgRotateArr[SideID] == 180) { row = row.TupleInverse(); col = col.TupleInverse(); } for (int i = 0; i < row.Length; i++) { dataGridView1.Rows.Add(); dataGridView1.Rows[i].Cells[0].Value = i + 1; dataGridView1.Rows[i].Cells[1].Value = Math.Round(col[i].D, 3); dataGridView1.Rows[i].Cells[2].Value = Math.Round(row[i].D, 3); hwindow_final.viewWindow.dispMessage("P" + (i + 1).ToString(), "green", row[i].D, col[i].D); string data = Math.Round(row[i].D, 3).ToString() + "," + Math.Round(col[i].D, 3).ToString() + "\r\n"; PixStr.Append(data); } HObject cross = new HObject(); HOperatorSet.GenCrossContourXld(out cross, row, col, 15, 0.5); hwindow_final.viewWindow.displayHobject(cross, "red", false, 3); //计算标定 if (row.Length < 3) { MessageBox.Show(string.Format("当前标定像素点数{0}太少", row.Length)); return; } if (AxisX == null || AxisX.Length == 0) { return; } ParamPath.ToolType = MyGlobal.ToolType_Calib; ParamPath.ParaName = MyGlobal.FindPointType_FitLineSet + "_" + "Side" + (SideID + 1).ToString(); ParamPath.IsRight = isRight; if (File.Exists(ParamPath.Path_CalibPix)) { File.Delete(ParamPath.Path_CalibPix); } ParamPath.WriteTxt(ParamPath.Path_CalibPix, PixStr.ToString()); HOperatorSet.VectorToHomMat2d(row, col, AxisX, AxisY, out HomMat2Dxy); string Deviation = ""; RunCalibDeviation(row, col, out Deviation); label_Score.Text = Deviation; HOperatorSet.WriteTuple(HomMat2Dxy, ParamPath.Path_tup); label_result.Text = "OK"; label_result.BackColor = Color.Green; } catch (Exception ex) { MessageBox.Show("标定失败" + ex.Message); } }
/// <summary> /// Generate a contour in form of an arrow. /// </summary> private void gen_arrow_cont(out HObject ho_Arrow, HTuple hv_Row1, HTuple hv_Column1, HTuple hv_Row2, HTuple hv_Column2) { // Local iconic variables HObject ho_Cross1, ho_Cross2, ho_CrossP1, ho_CrossP2; // Local control variables HTuple hv_Length, hv_Angle, hv_MinArrowLength; HTuple hv_DRow, hv_DCol, hv_ArrowLength, hv_Phi, hv_P1R; HTuple hv_P1C, hv_P2R, hv_P2C; // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_Arrow); HOperatorSet.GenEmptyObj(out ho_Cross1); HOperatorSet.GenEmptyObj(out ho_Cross2); HOperatorSet.GenEmptyObj(out ho_CrossP1); HOperatorSet.GenEmptyObj(out ho_CrossP2); //Generate a contour in form of a arrow hv_Length = 7; hv_Angle = 40; hv_MinArrowLength = 2; hv_DRow = hv_Row2 - hv_Row1; hv_DCol = hv_Column2 - hv_Column1; hv_ArrowLength = (((hv_DRow * hv_DRow) + (hv_DCol * hv_DCol))).TupleSqrt(); if ((int)(new HTuple(hv_ArrowLength.TupleLess(hv_MinArrowLength))) != 0) { hv_Length = 0; } HOperatorSet.TupleAtan2(hv_DRow, -hv_DCol, out hv_Phi); hv_P1R = hv_Row2 - (hv_Length * (((hv_Phi - (hv_Angle.TupleRad()))).TupleSin())); hv_P1C = hv_Column2 + (hv_Length * (((hv_Phi - (hv_Angle.TupleRad()))).TupleCos())); hv_P2R = hv_Row2 - (hv_Length * (((hv_Phi + (hv_Angle.TupleRad()))).TupleSin())); hv_P2C = hv_Column2 + (hv_Length * (((hv_Phi + (hv_Angle.TupleRad()))).TupleCos())); ho_Cross1.Dispose(); HOperatorSet.GenCrossContourXld(out ho_Cross1, hv_Row1, hv_Column1, 6, 0.785398); ho_Cross2.Dispose(); HOperatorSet.GenCrossContourXld(out ho_Cross2, hv_Row2, hv_Column2, 6, 0.785398); ho_CrossP1.Dispose(); HOperatorSet.GenCrossContourXld(out ho_CrossP1, hv_P1R, hv_P1C, 6, 0.785398); ho_CrossP2.Dispose(); HOperatorSet.GenCrossContourXld(out ho_CrossP2, hv_P2R, hv_P2C, 6, 0.785398); ho_Arrow.Dispose(); HOperatorSet.GenContourPolygonXld(out ho_Arrow, ((((((hv_Row1.TupleConcat(hv_Row2))).TupleConcat( hv_P1R))).TupleConcat(hv_Row2))).TupleConcat(hv_P2R), ((((((hv_Column1.TupleConcat( hv_Column2))).TupleConcat(hv_P1C))).TupleConcat(hv_Column2))).TupleConcat( hv_P2C)); ho_Cross1.Dispose(); ho_Cross2.Dispose(); ho_CrossP1.Dispose(); ho_CrossP2.Dispose(); return; }
/// <summary> /// 执行 /// </summary> /// <param name="image">图像</param> /// <param name="outputs">输出结果</param> /// <returns>执行结果</returns> public void Execute(object image, out ItemCollection outputs) { HObject hImage = image as HObject; outputs = new ItemCollection(); stopwatch.Restart(); HObject ho_Image20190904144527, ho_GrayImage; HObject ho_Regions, ho_ConnectedRegions, ho_SelectedRegions; HObject ho_ContCircle; // Local control variables HTuple hv_Number = new HTuple(); HTuple hv_Row = null, hv_Column = null, hv_Radius = null; // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_Image20190904144527); HOperatorSet.GenEmptyObj(out ho_GrayImage); HOperatorSet.GenEmptyObj(out ho_Regions); HOperatorSet.GenEmptyObj(out ho_ConnectedRegions); HOperatorSet.GenEmptyObj(out ho_SelectedRegions); HOperatorSet.GenEmptyObj(out ho_ContCircle); try { HTuple width, height; HOperatorSet.GetImageSize(hImage, out width, out height); //若未初始化,则进行初始化 if (!isInit) { isInit = true; } if (runningWindow == null) { try { runningWindow = (RunningWindow as HSmartWindowControlWPF).HalconWindow; } catch (Exception) { } } if (configWindow == null) { try { configWindow = (ConfigWindow as HSmartWindowControlWPF).HalconWindow; } catch (Exception) { } } if (runningWindow != null) { SetWindowPart(runningWindow, width, height); HOperatorSet.ClearWindow(runningWindow); HOperatorSet.DispObj(hImage, runningWindow); } if (configWindow != null) { SetWindowPart(configWindow, width, height); HOperatorSet.ClearWindow(configWindow); HOperatorSet.DispObj(hImage, configWindow); } //执行主任务 //转灰度图 ho_GrayImage.Dispose(); HOperatorSet.Rgb1ToGray(hImage, out ho_GrayImage); //阈值分割 ho_Regions.Dispose(); HOperatorSet.Threshold(ho_GrayImage, out ho_Regions, new HTuple(Inputs["MinThreshold"].Value), new HTuple(Inputs["MaxThreshold"].Value)); //提取有效区域 ho_ConnectedRegions.Dispose(); HOperatorSet.Connection(ho_Regions, out ho_ConnectedRegions); ho_SelectedRegions.Dispose(); HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegions, "area", "and", new HTuple(Inputs["BlobArea"].Value), 999999999); HOperatorSet.CountObj(ho_SelectedRegions, out hv_Number); if (hv_Number.I > 0) { //提取有效区域 HOperatorSet.SmallestCircle(ho_SelectedRegions, out hv_Row, out hv_Column, out hv_Radius); ho_ContCircle.Dispose(); HOperatorSet.GenCircleContourXld(out ho_ContCircle, hv_Row, hv_Column, hv_Radius + 20, 0, 6.28318, "positive", 1); var locations = new Location[hv_Column.Length]; for (int i = 0; i < hv_Column.Length; i++) { locations[i] = new Location(hv_Column[i].D, hv_Row[i].D, 0); } Outputs["ItemLocation"].Value = locations; //显示结果 if (runningWindow != null) { HOperatorSet.DispObj(ho_GrayImage, runningWindow); HOperatorSet.DispObj(ho_ContCircle, runningWindow); disp_message(runningWindow, (hv_Column + new HTuple(",")) + hv_Row, "image", hv_Row - 100, hv_Column + 100, "black", "true"); } if (configWindow != null) { HOperatorSet.DispObj(ho_GrayImage, configWindow); HOperatorSet.DispObj(ho_ContCircle, configWindow); disp_message(configWindow, (hv_Column + new HTuple(",")) + hv_Row, "image", hv_Row - 100, hv_Column + 100, "black", "true"); } stopwatch.Stop(); RunStatus = new RunStatus(stopwatch.Elapsed.TotalMilliseconds); } else { //没有有效的结果 Outputs["ItemLocation"].Value = new Location[0]; stopwatch.Stop(); RunStatus = new RunStatus(stopwatch.Elapsed.TotalMilliseconds, EResult.Warning, "没找到有效目标"); } outputs = new ItemCollection(Outputs); } catch (Exception ex) { stopwatch.Stop(); RunStatus = new RunStatus(stopwatch.Elapsed.TotalMilliseconds, EResult.Error, ex.Message, ex); throw; } finally { hImage.Dispose(); ho_GrayImage.Dispose(); ho_Regions.Dispose(); ho_ConnectedRegions.Dispose(); ho_SelectedRegions.Dispose(); ho_ContCircle.Dispose(); } }
private HObject extractEdges(HObject imageReduced) { HObject edges, contoursSplit; HOperatorSet.GenEmptyObj(out edges); HOperatorSet.GenEmptyObj(out contoursSplit); //Edgesubpix try { if (mMeasAssist.UseEdgeSubpix) { var alpha = mMeasAssist.EdgesAlpha; var grayHigh = mMeasAssist.EdgesGrayHigh; HOperatorSet.EdgesSubPix(imageReduced, out edges, _filter, alpha, _low, grayHigh); } else { HOperatorSet.ThresholdSubPix(imageReduced, out edges, mMeasAssist.SubpixThreadhold); } HOperatorSet.SegmentContoursXld(edges, out contoursSplit, _mode, _smoothCont, _maxLineDist1, _maxLineDist2); } catch (HOperatorException ex) { Hanbo.Log.LogManager.Error(ex); } return contoursSplit; }
private FitLineResult fitline(HObject contoursSplit) { FitLineResult result = new FitLineResult() { Col1 = new HTuple(), Row1 = new HTuple(), Col2 = new HTuple(), Row2 = new HTuple(), }; //fitLine HTuple number, rowBegin, colBegin, rowEnd, colEnd, nr, nc, dist; HObject objectSelected; HOperatorSet.GenEmptyObj(out objectSelected); HTuple distance, preDistance = 0.0; var fitlineContourAlgorithm = (mMeasAssist != null) ? new HTuple(mMeasAssist.FitLineAlgorithm) : _algorithm; HOperatorSet.CountObj(contoursSplit, out number); for (HTuple hv_i = 1; hv_i.Continue(number, 1); hv_i = hv_i.TupleAdd(1)) { HOperatorSet.SelectObj(contoursSplit, out objectSelected, hv_i); HOperatorSet.FitLineContourXld(objectSelected , fitlineContourAlgorithm, _maxNumPoints, _clippingEndPoints, _iterations, _clippingFactor, out rowBegin, out colBegin, out rowEnd, out colEnd, out nr, out nc, out dist); HOperatorSet.DistancePp(rowBegin, colBegin, rowEnd, colEnd, out distance); if (distance > preDistance) { preDistance = new HTuple(distance); //Answer result = new FitLineResult() { Row1 = new HTuple(rowBegin), Col1 = new HTuple(colBegin), Row2 = new HTuple(rowEnd), Col2 = new HTuple(colEnd), }; } } return result; }
public StationStep StepGoSnap(VisionControl visionControl, bool bmanual = false) { StationStep step = StationStep.Step_Stop; //拍照识别是否有料,计算偏差(6月后做) ParamSetMgr.GetInstance().SetBoolParam("启动点胶", true); //开始点胶(优先实现画轨迹) //获取当前夹取位置是A工位还是B工位 int StationIndex = TableData.GetInstance().GetSocketNum(1, 0.5) - 1; PathHelper.Disp_ID = StationIndex; string stationAAName = StationIndex == 0 ? "A" : "B"; ParamSetMgr.GetInstance().SetBoolParam($"{stationAAName}工位点胶", true); double CenterX = ParamSetMgr.GetInstance().GetDoubleParam("产品点胶X轴半径"); double CenterY = ParamSetMgr.GetInstance().GetDoubleParam("产品点胶Y轴半径"); double DelZ = ParamSetMgr.GetInstance().GetDoubleParam("点胶Z轴上升高度偏差"); int DispDelay = ParamSetMgr.GetInstance().GetIntParam("出胶延迟"); double DispRunAngle = ParamSetMgr.GetInstance().GetDoubleParam("画胶角度"); double DispEndAngle = ParamSetMgr.GetInstance().GetDoubleParam("收胶角度"); bool DispEnable = ParamSetMgr.GetInstance().GetBoolParam("屏蔽点胶"); bool DispPhoto = ParamSetMgr.GetInstance().GetBoolParam("点胶相机拍照定位"); double SafeZ = GetStationPointDic()[$"安全位置"].pointZ; double X = 0; double Y = 0; double DispPhotoX = GetStationPointDic()[$"{stationAAName}工位拍照位"].pointX; double DispPhotoY = GetStationPointDic()[$"{stationAAName}工位拍照位"].pointY; double DispPhotoZ = GetStationPointDic()[$"{stationAAName}工位拍照位"].pointZ; double DispPosX = GetStationPointDic()[$"{stationAAName}工位点胶位"].pointX; double DispPosY = GetStationPointDic()[$"{stationAAName}工位点胶位"].pointY; double DispPosZ = GetStationPointDic()[$"{stationAAName}工位点胶位"].pointZ; double x1 = GetStationPointDic()["安全位置"].pointX; CameraBase cam = null; if (!ParamSetMgr.GetInstance().GetBoolParam("屏蔽上相机")) { cam = CameraMgr.GetInstance().GetCamera("Top"); cam.BindWindow(visionControl); Task.Run(() => { cam.StopGrap(); cam.SetTriggerMode(CameraModeType.Software); cam.SetGain(ParamSetMgr.GetInstance().GetIntParam("点胶相机增益")); cam.SetExposureTime(ParamSetMgr.GetInstance().GetIntParam("点胶相机曝光")); cam.StartGrab(); }); } IOMgr.GetInstace().WriteIoBit($"相机光源", true); retry_uplens: IOMgr.GetInstace().WriteIoBit($"{stationAAName}Lens升降气缸", true); WaranResult waranResult1 = CheckIobyName($"{stationAAName}Lens上升到位", true, $"{stationAAName}Lens上升到位", bmanual); if (waranResult1 == WaranResult.Retry) { goto retry_uplens; } MoveSigleAxisPosWaitInpos(AxisZ, SafeZ, (double)SpeedType.High, 0.005, bmanual, this); MoveY(DispPhotoY, SpeedType.High); MoveMulitAxisPosWaitInpos(new int[] { AxisX, AxisZ }, new double[] { DispPhotoX, DispPhotoZ }, new double[] { (double)SpeedType.High, (double)SpeedType.High }, 0.005, bmanual, this); HObject img = null; if (!ParamSetMgr.GetInstance().GetBoolParam("屏蔽上相机")) { img = cam.GetImage(); if (img == null || !img.IsInitialized()) { img = cam.GetImage(); } else { ImageHelper.Instance.SaveImage($"{PathHelper.ImagePathDisp}{DateTime.Now.ToString("HHmmssfff")}.bmp", "bmp", img.Clone()); } } IOMgr.GetInstace().WriteIoBit($"相机光源", false); //去画胶 Task.Run(() => { if (ParamSetMgr.GetInstance().GetBoolParam("是否选择程控电源")) { double valueVoltage = ParamSetMgr.GetInstance().GetDoubleParam("程控电源电压"); OtherDevices.ckPower.SetVoltage(StationIndex + 1, valueVoltage); double valueCurrent = ParamSetMgr.GetInstance().GetDoubleParam("程控电源电流"); OtherDevices.ckPower.SetCurrent(StationIndex + 1, valueCurrent); } IOMgr.GetInstace().WriteIoBit($"{stationAAName}模组上电", true); IOMgr.GetInstace().WriteIoBit($"12V开启", ParamSetMgr.GetInstance().GetBoolParam("是否开启非程控12V")); }); if (DispEnable) { step = StationStep.Step_CheckIpos; MoveSigleAxisPosWaitInpos(AxisZ, SafeZ, (double)SpeedType.High, 0.005, bmanual, this); TableData.GetInstance().SetStationResult("A_UnLoadLoad", true); TableData.GetInstance().SetStationResult("B_UnLoadLoad", true); return(step); } if (DispPhoto) { ////MoveY(DispPhotoY, SpeedType.High); ////MoveMulitAxisPosWaitInpos(new int[] { AxisX, AxisZ }, new double[] { DispPhotoX, DispPhotoZ }, new double[] { (double)SpeedType.High, (double)SpeedType.High }, 0.005, bmanual, this); //拍照计算 +半径 double CenterdelX = 0; double CenterdelY = 0; X = CenterX + CenterdelX; Y = CenterdelY; DispPosX = DispPhotoX - X; DispPosY = DispPhotoY + CenterdelY; } else { X = CenterX; Y = 0; } // IOMgr.GetInstace().WriteIoBit("点胶机", false); bool brtnExc = true; MotionMgr.GetInstace().AddAxisToGroup("点胶群组", 2, new int[] { AxisX, AxisY }); MoveY(DispPosY, SpeedType.High); MoveMulitAxisPosWaitInpos(new int[] { AxisX, AxisZ }, new double[] { DispPosX, DispPosZ + DelZ + 10 }, new double[] { (double)SpeedType.High, (double)SpeedType.High }, 0.005, bmanual, this); // MoveMulitAxisPosWaitInpos(new int[] { AxisX }, new double[] { DispPosX }, new double[] { (double)SpeedType.High }, 0.005, bmanual, this); IOMgr.GetInstace().WriteIoBit("点胶机", false); MoveMulitAxisPosWaitInpos(new int[] { AxisZ }, new double[] { DispPosZ + DelZ }, new double[] { (double)SpeedType.High }, 0.005, bmanual, this); if (ParamSetMgr.GetInstance().GetStringParam("点胶轨迹") == "Circle") { DateTime dateTime = DateTime.Now; if (DispDelay >= 0) { IOMgr.GetInstace().WriteIoBit("点胶机", true); Thread.Sleep(DispDelay); } else { Task.Run(() => { while (true) { if ((DateTime.Now - dateTime).TotalSeconds > Math.Abs(DispDelay) / 1000.0) { IOMgr.GetInstace().WriteIoBit("点胶机", true); break; } Thread.Sleep(10); } }); } //走 brtnExc &= MotionMgr.GetInstace().ClearBufMove("点胶群组"); brtnExc &= MotionMgr.GetInstace().RestGpErr("点胶群组"); // GpState gps = MotionMgr.GetInstace().GetGpState("点胶群组"); brtnExc &= MotionMgr.GetInstace().AddBufMove("点胶群组", BufMotionType.buf_Arc2dAbsAngleCW, 1, 2, (double)SpeedType.Mid, (double)SpeedType.Mid, new double[2] { X, Y }, new double[2] { DispPosZ, 0 }); brtnExc &= MotionMgr.GetInstace().BufTrans("点胶群组");//M314没有buf运动,所以放在这里star brtnExc &= MotionMgr.GetInstace().BufStart("点胶群组"); Thread.Sleep(400); if (!WaitXY(DispPosX, DispPosY)) { IOMgr.GetInstace().WriteIoBit("点胶机", false); return(step); } IOMgr.GetInstace().WriteIoBit("点胶机", false); } else { IOMgr.GetInstace().WriteIoBit("点胶机", true); Thread.Sleep(DispDelay); MoveY(DispPosY + CenterY * 10, SpeedType.Mid); MoveMulitAxisPosWaitInpos(new int[] { AxisX }, new double[] { DispPosX + CenterX * 2 }, new double[] { (double)SpeedType.Mid }, 0.005, bmanual, this); MoveY(DispPosY - CenterY * 10, SpeedType.Mid); MoveMulitAxisPosWaitInpos(new int[] { AxisX }, new double[] { DispPosX }, new double[] { (double)SpeedType.Mid }, 0.005, bmanual, this); MoveY(DispPosY, SpeedType.Mid); IOMgr.GetInstace().WriteIoBit("点胶机", false); } IOMgr.GetInstace().WriteIoBit($"相机光源", true); MoveMulitAxisPosWaitInpos(new int[] { AxisZ }, new double[] { DispPosZ + 3 }, new double[] { (double)SpeedType.Mid }, 0.005, bmanual, this); MoveMulitAxisPosWaitInpos(new int[] { AxisZ }, new double[] { DispPosZ + 10 }, new double[] { (double)SpeedType.High }, 0.005, bmanual, this); if (!ParamSetMgr.GetInstance().GetBoolParam("屏蔽上相机")) { MoveMulitAxisPosWaitInpos(new int[] { AxisX, AxisZ }, new double[] { DispPhotoX, DispPhotoZ }, new double[] { (double)SpeedType.High, (double)SpeedType.High }, 0.005, bmanual, this); // MoveSigleAxisPosWaitInpos(AxisX, DispPhotoX, (double)SpeedType.High, 0.005, bmanual, this); MoveY(DispPhotoY, SpeedType.High); HObject img2 = cam.GetImage(); if (img2 == null || !img2.IsInitialized()) { img2 = cam.GetImage(); } else { ImageHelper.Instance.SaveImage($"{PathHelper.ImagePathDisp}{DateTime.Now.ToString("HHmmssfff")}.bmp", "bmp", img2.Clone()); } } IOMgr.GetInstace().WriteIoBit($"相机光源", false); MoveMulitAxisPosWaitInpos(new int[] { AxisZ }, new double[] { SafeZ }, new double[] { (double)SpeedType.High }, 0.005, bmanual, this); MoveSigleAxisPosWaitInpos(AxisX, x1, (double)SpeedType.High, 0.005, bmanual, this); step = StationStep.Step_CheckIpos; //if (DialogResult.OK!= MessageBox.Show("请确定点胶效果是否OK,OK按确定", "Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly)) //{ // ParamSetMgr.GetInstance().SetBoolParam("重新上料", true); // return step; //} ParamSetMgr.GetInstance().SetBoolParam("重新上料", false); SocketMgr.GetInstance().SetSocketState(SocketNumOfUnloadLoad, SocketState.Have); TableData.GetInstance().SetStationResult("A_UnLoadLoad", true); TableData.GetInstance().SetStationResult("B_UnLoadLoad", true); ParamSetMgr.GetInstance().SetBoolParam("点胶完成", true); return(step); }
/********************************************************************/ /* GRAPHICSSTACK -KEEP */ /********************************************************************/ /// <summary> /// Adds an iconic object to the graphics stack similar to the way /// it is defined for the HDevelop graphics stack. /// </summary> /// <param name="obj">Iconic object</param> public void addIconicVarKeepSettings(HObject obj) { HObjectEntry entry; if (obj == null) return; if ((obj is HImage) && (obj != null)) { double r, c; int h, w, area; string s; area = ((HImage)obj).GetDomain().AreaCenter(out r, out c); ((HImage)obj).GetImagePointer1(out s, out w, out h); if (HObjList.Count == 0) { heightImagePart = h; widthImagePart = w; //adaptSize = true; zoomWndFactor = (double)widthDisplayedImage / viewPort.Width; resetImagePart(widthImagePart, heightImagePart); } if (area == (w * h)) { clearList(); if ((h != heightImagePart) || (w != widthImagePart)) { heightImagePart = h; widthImagePart = w; if ((widthDisplayedImage != w) || (heightDisplayedImage != h)) resetImagePart(w, h); zoomWndFactor = (double)widthDisplayedImage / viewPort.Width; } }//if widthDisplayedImage = w; heightDisplayedImage = h; }//if entry = new HObjectEntry(obj, mGC.copyContextList()); HObjList.Add(entry); if (HObjList.Count > MAXNUMOBJLIST) HObjList.RemoveAt(1); }
public bool GlueCheck(HObject Image1, HObject Image2) { bool result = true; string pathImage = ParamSetMgr.GetInstance().GetStringParam("保存相机图片路径"); string path = pathImage + "\\" + DateTime.Now.ToString("yy-MM-dd") + "\\Fail\\"; HObject ModleImage = null; HTuple Number1 = null; HTuple Number2 = null; HTuple Number3 = null; HObject modelROI = null; HTuple ModelID = null; HObject ModleRoiCircle = null; HObject RoiCircle1 = null; HObject RoiCircle2 = null; HObject ModleRoiRectangle = null; HObject RoiRectangle1 = null; HObject RoiRectangle2 = null; HObject RegionDifference = null; HObject RegionDifference1 = null; HObject RegionDifference2 = null; HObject ImageReduced = null; HObject ImageReduced1 = null; HObject ImageReduced2 = null; HObject ImageSub = null; HObject RegionThreshold = null; HObject ConnectedRegions = null; HObject SelectedRegions = null; HObject RegionClosing1 = null; HObject RegionClosing2 = null; HObject Skeleton = null; HObject SelectedSkeleton = null; HObject SelectedSkeleton2 = null; HObject RegionUnion = null; try { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } //读取模板路径,模板参数 //string Modelpath = "D:\ProductFile\DF\Disp\GlueCheck\ModelImage.bmp"; //HTuple threshold = 30; //HTuple closing = 2; //HTuple modelCircleRow = 512.71; HTuple modelCircleCol = 838.492; HTuple modelCircleR = 97.1676; //HTuple RoiCircleRow = 515.131; HTuple RoiCircleCol = 635.466; HTuple RoiCircleR = 61.896; //HTuple RoiRectangleRow1 = 411.037; HTuple RoiRectangleCol1 = 542.693; HTuple RoiRectangleRow2 = 611.963; HTuple RoiRectangleCol2 = 724.206; string Modelpath = ParamSetMgr.GetInstance().GetStringParam("点胶检查路径模板").Replace("\\", "\\\\"); HTuple threshold = ParamSetMgr.GetInstance().GetIntParam("点胶检查阈值"); HTuple closing = ParamSetMgr.GetInstance().GetIntParam("点胶检查闭合像素"); HTuple modelCircleRow = ParamSetMgr.GetInstance().GetDoubleParam("点胶检查模板Row"); HTuple modelCircleCol = ParamSetMgr.GetInstance().GetDoubleParam("点胶检查模板Col"); HTuple modelCircleR = ParamSetMgr.GetInstance().GetDoubleParam("点胶检查模板R"); HTuple RoiCircleRow = ParamSetMgr.GetInstance().GetDoubleParam("点胶检查CircleRow"); HTuple RoiCircleCol = ParamSetMgr.GetInstance().GetDoubleParam("点胶检查CircleCol"); HTuple RoiCircleR = ParamSetMgr.GetInstance().GetDoubleParam("点胶检查CircleR"); HTuple RoiRectangleRow1 = ParamSetMgr.GetInstance().GetDoubleParam("点胶检查RectangleRow1"); HTuple RoiRectangleCol1 = ParamSetMgr.GetInstance().GetDoubleParam("点胶检查RectangleCol1"); HTuple RoiRectangleRow2 = ParamSetMgr.GetInstance().GetDoubleParam("点胶检查RectangleRow2"); HTuple RoiRectangleCol2 = ParamSetMgr.GetInstance().GetDoubleParam("点胶检查RectangleCol2"); HTuple Row1 = null; HTuple Column1 = null; HTuple Angle1 = null; HTuple Score1 = null; HTuple Row2 = null; HTuple Column2 = null; HTuple Angle2 = null; HTuple Score2 = null; HOperatorSet.ReadImage(out ModleImage, Modelpath); HOperatorSet.GenCircle(out modelROI, modelCircleRow, modelCircleCol, modelCircleR); HOperatorSet.GenCircle(out ModleRoiCircle, RoiCircleRow, RoiCircleCol, RoiCircleR); HOperatorSet.GenRectangle1(out ModleRoiRectangle, RoiRectangleRow1, RoiRectangleCol1, RoiRectangleRow2, RoiRectangleCol2); HOperatorSet.Difference(ModleRoiRectangle, ModleRoiCircle, out RegionDifference); HOperatorSet.ReduceDomain(Image1, modelROI, out ImageReduced); HOperatorSet.CreateNccModel(ImageReduced, 3, -0.39, 0.79, 0.1, "use_polarity", out ModelID); HOperatorSet.FindNccModel(Image1, ModelID, -0.39, 0.78, 0.8, 1, 0.5, "true", 0, out Row1, out Column1, out Angle1, out Score1); HOperatorSet.FindNccModel(Image2, ModelID, -0.39, 0.78, 0.8, 1, 0.5, "true", 0, out Row2, out Column2, out Angle2, out Score2); HOperatorSet.GenCircle(out RoiCircle1, RoiCircleRow - modelCircleRow + Row1, RoiCircleCol - modelCircleCol + Column1, RoiCircleR); HOperatorSet.GenCircle(out RoiCircle2, RoiCircleRow - modelCircleRow + Row2, RoiCircleCol - modelCircleCol + Column2, RoiCircleR); HOperatorSet.GenRectangle1(out RoiRectangle1, RoiRectangleRow1 - modelCircleRow + Row1, RoiRectangleCol1 - modelCircleCol + Column1, RoiRectangleRow2 - modelCircleRow + Row1, RoiRectangleCol2 - modelCircleCol + Column1); HOperatorSet.GenRectangle1(out RoiRectangle2, RoiRectangleRow1 - modelCircleRow + Row2, RoiRectangleCol1 - modelCircleCol + Column2, RoiRectangleRow2 - modelCircleRow + Row2, RoiRectangleCol2 - modelCircleCol + Column2); HOperatorSet.Difference(RoiRectangle1, RoiCircle1, out RegionDifference1); HOperatorSet.Difference(RoiRectangle2, RoiCircle2, out RegionDifference2); HOperatorSet.ReduceDomain(Image1, RegionDifference1, out ImageReduced1); HOperatorSet.ReduceDomain(Image2, RegionDifference2, out ImageReduced2); HOperatorSet.SubImage(ImageReduced1, ImageReduced2, out ImageSub, 1, 0); HOperatorSet.Threshold(ImageSub, out RegionThreshold, threshold, 255); HOperatorSet.ClosingCircle(RegionThreshold, out RegionClosing1, closing); HOperatorSet.Connection(RegionClosing1, out ConnectedRegions); HOperatorSet.SelectShape(ConnectedRegions, out SelectedRegions, "area", "and", 800, 99999); HOperatorSet.CountObj(SelectedRegions, out Number1); if (Number1.I < 1) { HOperatorSet.WriteImage(Image1.Clone(), "bmp", 0, $"{path}LoseGlue1_{DateTime.Now.ToString("yyMMdd_HHmmssfff")}.bmp"); HOperatorSet.WriteImage(Image2.Clone(), "bmp", 0, $"{path}LoseGlue2_{DateTime.Now.ToString("yyMMdd_HHmmssfff")}.bmp"); return(false);//无特征,漏胶 } HOperatorSet.ClosingCircle(SelectedRegions, out RegionClosing2, closing); HOperatorSet.Skeleton(RegionClosing2, out Skeleton); HOperatorSet.SelectShape(Skeleton, out SelectedSkeleton, (((new HTuple("area")).TupleConcat("holes_num")).TupleConcat("column")).TupleConcat("row"), "and", (((new HTuple(300)).TupleConcat(0)).TupleConcat(300)).TupleConcat(300), (((new HTuple(1000000)).TupleConcat(1000)).TupleConcat(1000)).TupleConcat(1000)); // HOperatorSet.Union1(SelectedSkeleton, out RegionUnion); HOperatorSet.CountObj(SelectedSkeleton, out Number2); if (Number2.I < 1) { HOperatorSet.WriteImage(Image1.Clone(), "bmp", 0, $"{path}OpenGlueNoSkeleton1_{DateTime.Now.ToString("yyMMdd_HHmmssfff")}.bmp"); HOperatorSet.WriteImage(Image2.Clone(), "bmp", 0, $"{path}OpenGlueNoSkeleton2_{DateTime.Now.ToString("yyMMdd_HHmmssfff")}.bmp"); return(false);//无特征,断胶 } else { HOperatorSet.SelectShape(SelectedSkeleton, out SelectedSkeleton2, "area_holes", "and", 10000, 99999999); HOperatorSet.CountObj(SelectedSkeleton2, out Number3); if (Number3.I != 1) { HOperatorSet.WriteImage(Image1.Clone(), "bmp", 0, $"{path}OpenGlue1AreaNum_{DateTime.Now.ToString("yyMMdd_HHmmssfff")}.bmp"); HOperatorSet.WriteImage(Image2.Clone(), "bmp", 0, $"{path}OpenGlue2AreaNum_{DateTime.Now.ToString("yyMMdd_HHmmssfff")}.bmp"); return(false);//无特征,断胶 } } } catch { if (Image1 != null) { HOperatorSet.WriteImage(Image1.Clone(), "bmp", 0, $"{path}GlueErr1_{DateTime.Now.ToString("yyMMdd_HHmmssfff")}.bmp"); } if (Image2 != null) { HOperatorSet.WriteImage(Image2.Clone(), "bmp", 0, $"{path}GlueErr2_{DateTime.Now.ToString("yyMMdd_HHmmssfff")}.bmp"); } result = false; } finally { if (ModleImage != null) { ModleImage.Dispose(); } if (modelROI != null) { modelROI.Dispose(); } if (ModleRoiCircle != null) { ModleRoiCircle.Dispose(); } if (RoiCircle1 != null) { RoiCircle1.Dispose(); } if (RoiCircle2 != null) { RoiCircle2.Dispose(); } if (ModleRoiRectangle != null) { ModleRoiRectangle.Dispose(); } if (RoiRectangle1 != null) { RoiRectangle1.Dispose(); } if (RoiRectangle2 != null) { RoiRectangle2.Dispose(); } if (RegionDifference != null) { RegionDifference.Dispose(); } if (RegionDifference1 != null) { RegionDifference1.Dispose(); } if (RegionDifference2 != null) { RegionDifference2.Dispose(); } if (ImageReduced != null) { ImageReduced.Dispose(); } if (ImageReduced1 != null) { ImageReduced1.Dispose(); } if (ImageReduced2 != null) { ImageReduced2.Dispose(); } if (ImageSub != null) { ImageSub.Dispose(); } if (RegionThreshold != null) { RegionThreshold.Dispose(); } if (ConnectedRegions != null) { ConnectedRegions.Dispose(); } if (SelectedRegions != null) { SelectedRegions.Dispose(); } if (RegionClosing1 != null) { RegionClosing1.Dispose(); } if (RegionClosing2 != null) { RegionClosing2.Dispose(); } if (Skeleton != null) { Skeleton.Dispose(); } if (SelectedSkeleton != null) { SelectedSkeleton.Dispose(); } if (RegionUnion != null) { RegionUnion.Dispose(); } if (Image1 != null) { Image1.Dispose(); } if (Image2 != null) { Image2.Dispose(); } } return(result); }
//畫方形輸入:顯示視窗 , 圖 , ROI資料-------------------------------------------------------------------- public void DrawRectangle(HTuple hwindows) { //Rectangle HObject Mod_ROI_2 = null; HObject ROI_2 = null; HOperatorSet.GenEmptyObj(out Mod_ROI_2); SettingLine(hwindows, "red", "margin", 2); HOperatorSet.DrawRectangle2Mod(hwindows, ImageHeight / 2, ImageWidth / 2, 0, 50, 50, out RowRectangle, out ColumnRectangle, out PhiRectangle, out Length1Rectangle, out Length2Rectangle); //HOperatorSet.DrawRectangle2(hwindows, // out RowRectangle, // out ColumnRectangle, // out PhiRectangle, // out Length1Rectangle, // out Length2Rectangle); HOperatorSet.GenRectangle2(out ROI_2, RowRectangle, ColumnRectangle, PhiRectangle, Length1Rectangle, Length2Rectangle); HOperatorSet.ReduceDomain(Image, ROI_2, out Mod_ROI_2); HOperatorSet.DispObj(ROI_2, hwindows); ROI = ROI_2.Clone(); Mod_ROI = Mod_ROI_2.Clone(); ROI_2.Dispose(); Mod_ROI_2.Dispose(); }
public bool CalibrationMake(SourceBuffer _sourceBuffer, ExecuteBuffer _executeBuffer, out SourceBuffer outsourcebuffer, out ExecuteBuffer outexecutebuffer, HWndCtrl hWndCtrl, out string result_info) { outsourcebuffer = _sourceBuffer; outexecutebuffer = _executeBuffer; result_info = ""; HTuple hv_PixelSize = 0.00001; HTuple hv_Message = new HTuple(), hv_Row = new HTuple(); HTuple hv_Column = new HTuple(), hv_Index = new HTuple(); HTuple hv_Error = null; HObject ho_Contours = null, ho_Cross = null, hv_outimage = null; HTuple hv_HomMat3DIdentity = null; HTuple hv_cp1Hur1 = null, hv_cam2Hcp2 = null, hv_cam2Hul2 = null; HTuple hv_PoseNewOrigin2 = null, hv_ULX = null, hv_ULY = null, hv_PoseNewOrigin = null; double[] Get_actual_pixel = new double[7]; HTuple WorldPixelx, WorldPixely; HTuple Heightx = new HTuple(), Widthx = new HTuple(); Heightx.Append(Height / 2); Heightx.Append(Height / 2); Heightx.Append(Height / 2 + 1); Widthx.Append(Width / 2); Widthx.Append(Width / 2 + 1); Widthx.Append(Width / 2); HTuple WorldLength1, WorldLength2; HTuple ScaleForSimilarPixelSize = 0; HOperatorSet.GenEmptyObj(out ho_Contours); HOperatorSet.GenEmptyObj(out ho_Cross); HOperatorSet.GenEmptyObj(out hv_outimage); if (!_executeBuffer.imageBuffer.ContainsKey(this.Input_image.SelectedItem.ToString() + ".img")) { MessageBox.Show("二值化处理: 输入图像已经不存在,请重置设置输入图像"); result_info = " 二值化处理: 输入图像已经不存在,请重置设置输入图像"; return(false); } if (_executeBuffer.imageBuffer[this.Input_image.SelectedItem.ToString() + ".img"] == null) { MessageBox.Show("二值化处理: image参数为空或者未赋值"); result_info = " 二值化处理: 输入图像已经不存在,请重置设置输入图像"; return(false); } string comboBox_imageoutname = this.Output_image.Text.ToString() + ".img"; if (_executeBuffer.imageBuffer[comboBox_imageoutname] != null) { if (_executeBuffer.imageBuffer[comboBox_imageoutname].IsInitialized()) { _executeBuffer.imageBuffer[comboBox_imageoutname].Dispose(); } } HTuple width, height; int m = _executeBuffer.imageBuffer[this.Input_image.SelectedItem.ToString() + ".img"].CountObj(); HOperatorSet.GetImageSize(_executeBuffer.imageBuffer[this.Input_image.SelectedItem.ToString() + ".img"], out width, out height); int number = Convert.ToInt32(this.textBox1.Text.ToString()); if (!this.checkBox1.Checked) { if (Get_Cal_pixel) { Get_Cal_pixel = false; } if (number == 0) { hv_StartCamPar = new HTuple(); if (this.checkBox_focalize.Checked) { hv_StartCamPar.Append(0); } else { hv_StartCamPar.Append(Convert.ToDouble(this.textbox_lens.Text.ToString()) / 100); } hv_StartCamPar.Append(0); hv_StartCamPar.Append(Convert.ToDouble(this.textBox_width.Text.ToString()) / 10000000); hv_StartCamPar.Append(Convert.ToDouble(this.textBox_height.Text.ToString()) / 10000000); hv_StartCamPar.Append(width / 2); hv_StartCamPar.Append(height / 2); hv_StartCamPar.Append(width); hv_StartCamPar.Append(height); hv_CalTabDescrFile = this.textBox_file.Text; HOperatorSet.CreateCalibData("calibration_object", 1, 1, out CalibDataID); if (this.checkBox_focalize.Checked) { HOperatorSet.SetCalibDataCamParam(CalibDataID, 0, "area_scan_telecentric_division", hv_StartCamPar); } else { HOperatorSet.SetCalibDataCamParam(CalibDataID, 0, "area_scan_division", hv_StartCamPar); } HOperatorSet.SetCalibDataCalibObject(CalibDataID, 0, hv_CalTabDescrFile); } try { HOperatorSet.FindCalibObject(_executeBuffer.imageBuffer[this.Input_image.SelectedItem.ToString() + ".img"], CalibDataID, 0, 0, number, new HTuple(), new HTuple()); HOperatorSet.GetCalibData(CalibDataID, "camera", 0, "init_params", out hv_StartCamPar); HOperatorSet.GetCalibDataObservPoints(CalibDataID, 0, 0, number, out hv_Row, out hv_Column, out hv_Index, out hv_Pose); HOperatorSet.GetCalibDataObservContours(out ho_Contours, CalibDataID, "caltab", 0, 0, number); HOperatorSet.GenCrossContourXld(out ho_Cross, hv_Row, hv_Column, 6, 0.785398); hWndCtrl.changeGraphicSettings(GraphicsContext.GC_COLOR, "orange"); hWndCtrl.addIconicVar(ho_Cross); hWndCtrl.addIconicVar(ho_Contours); hWndCtrl.repaint(); } catch { MessageBox.Show("找不到标定板"); ho_Contours.Dispose(); ho_Cross.Dispose(); return(false); } if (number == hv_NumImages - 1) { Read_file = false; HOperatorSet.CalibrateCameras(CalibDataID, out hv_Error); HOperatorSet.GetCalibData(CalibDataID, "camera", 0, "params", out hv_CamParam); HOperatorSet.GetCalibData(CalibDataID, "calib_obj_pose", (new HTuple(0)).TupleConcat(6), "pose", out hv_Pose); HOperatorSet.HomMat3dIdentity(out hv_HomMat3DIdentity); HOperatorSet.HomMat3dRotateLocal(hv_HomMat3DIdentity, ((-(hv_Pose.TupleSelect(5)))).TupleRad(), "z", out hv_cp1Hur1); HOperatorSet.PoseToHomMat3d(hv_Pose, out hv_cam2Hcp2); HOperatorSet.HomMat3dCompose(hv_cam2Hcp2, hv_cp1Hur1, out hv_cam2Hul2); HOperatorSet.HomMat3dToPose(hv_cam2Hul2, out hv_PoseNewOrigin2); HOperatorSet.ImagePointsToWorldPlane(hv_CamParam, hv_PoseNewOrigin2, 0, 0, "m", out hv_ULX, out hv_ULY); HOperatorSet.SetOriginPose(hv_PoseNewOrigin2, hv_ULX, hv_ULY, 0, out hv_PoseNewOrigin); HOperatorSet.ImagePointsToWorldPlane(hv_CamParam, hv_Pose, Heightx, Widthx, 1, out WorldPixelx, out WorldPixely); HOperatorSet.DistancePp(WorldPixely[0], WorldPixelx[0], WorldPixely[1], WorldPixelx[1], out WorldLength1); HOperatorSet.DistancePp(WorldPixely[0], WorldPixelx[0], WorldPixely[2], WorldPixelx[2], out WorldLength2); ScaleForSimilarPixelSize = (WorldLength1 + WorldLength2) / 2; HOperatorSet.GenImageToWorldPlaneMap(out ho_MapSingle1, hv_CamParam, hv_PoseNewOrigin, width, height, width, height, ScaleForSimilarPixelSize, "bilinear"); HOperatorSet.WriteObject(ho_MapSingle1, this.textBox2.Text.ToString()); Read_file = true; Get_Calibration = true; this.checkBox1.Checked = true; result_info = " 校正参数: 设置完成"; } this.textBox1.Text = (number + 1).ToString(); } if (this.checkBox1.Checked) { if (Read_file) { if (File.Exists(this.textBox2.Text)) { HOperatorSet.ReadObject(out ho_MapSingle1, this.textBox2.Text); } else { MessageBox.Show("校正文件不存在 ,请检查"); return(false); } } HOperatorSet.MapImage(_executeBuffer.imageBuffer[this.Input_image.SelectedItem.ToString() + ".img"], ho_MapSingle1, out hv_outimage); _executeBuffer.imageBuffer[comboBox_imageoutname] = hv_outimage; outexecutebuffer = _executeBuffer; result_info = " 校正: 完成"; HTuple Distance; if (!Get_Cal_pixel) { try { double all_number = 0; HOperatorSet.FindCalibObject(hv_outimage, CalibDataID, 0, 0, 0, new HTuple(), new HTuple()); HOperatorSet.GetCalibDataObservPoints(CalibDataID, 0, 0, 0, out hv_Row, out hv_Column, out hv_Index, out hv_Pose); for (int i = 0; i < 7; i++) { HOperatorSet.DistancePp(hv_Row[i * 7], hv_Column[i * 7], hv_Row[i * 7 + 6], hv_Column[i * 7 + 6], out Distance); Get_actual_pixel[i] = Distance.D; all_number = all_number + Get_actual_pixel[i]; } Pixel_number = (Convert.ToDouble(this.textBox_pixel.Text)) / (all_number / 7); Get_Cal_pixel = true; this.label_pixel.Text = Pixel_number.ToString(); Pixel_Trans = Convert.ToDouble(Pixel_number.ToString()); } catch { MessageBox.Show("请再次添加图像寻找计算像素比"); } } if (Read_file) { ho_MapSingle1.Dispose(); } } return(true); }
/// <summary> /// Composes set of HALCON iconic objects to display /// dimension of measure object /// </summary> /// <returns>Surrounding contour of measure object</returns> public HObject getMeasureRegions() { HObject val; HObject obj = new HObject(); obj.GenEmptyObj(); for (int i=0; i < mMeasureList.Count; i++) { val = ((Measurement)mMeasureList[i]).getMeasureRegion(); if (val.IsInitialized()) obj = obj.ConcatObj(val); } return obj; }
/// <summary> /// 圆心模板匹配 /// </summary> /// <param name="window"></param> /// <param name="image"></param> /// <param name="ROIFileName"></param> /// <param name="ModelFileName"></param> /// <returns></returns> public static double[] CenterMatch(Bitmap bmp, HWindow window) { try { HObject image, img_old; HOperatorSet.GenEmptyObj(out image); HOperatorSet.GenEmptyObj(out img_old); img_old.Dispose(); Bitmap2HObject.Bitmap2HObj(bmp, out img_old); HTuple htuple; HOperatorSet.CountChannels(img_old, out htuple); image.Dispose(); if (htuple == 3) { HOperatorSet.Rgb1ToGray(img_old, out image); } else { image = img_old.Clone(); } HTuple width, height; HOperatorSet.GetImageSize(image, out width, out height); HOperatorSet.SetPart(window, 0, 0, height - 1, width - 1); HOperatorSet.DispObj(image, window); HOperatorSet.SetLineWidth(window, 3); HOperatorSet.SetColor(window, "red"); double[] data = TempalteMatch.action(window, image, AppConfig.VisonPath + "\\CenterLocROI.hobj", AppConfig.VisonPath + "\\CenterModle.shm"); if (data[0] == -100 || data[1] == -100) { HOperatorSet.DispText(window, "识别失败", "window", 12, 7, "black", new HTuple(), new HTuple()); try { SetString(window, "NG", "red", 100); } catch { } return(data); } else { CenterLoc[0] = data[0]; CenterLoc[1] = data[1]; HObject ho_Cross = null; HOperatorSet.DispText(window, "X像素:" + System.Math.Round(data[0], 4) + " Y像素:" + System.Math.Round(data[1], 4) + " pixel", "window", 10, 7, "black", new HTuple(), new HTuple()); HOperatorSet.GenEmptyObj(out ho_Cross); ho_Cross.Dispose(); HOperatorSet.GenCrossContourXld(out ho_Cross, data[1], data[0], 180, 0.785398); //data[0] = (data[0] - width / 2) * 0.0096; //data[1] = -1 * ((data[1] - height / 2) * 0.0096); data[0] = (data[0] - width / 2) * Config.Instance.CameraPixelMM_X; data[1] = 1 * ((data[1] - height / 2) * Config.Instance.CameraPixelMM_Y); HOperatorSet.DispObj(ho_Cross, window); HOperatorSet.DispText(window, "X方向偏差:" + System.Math.Round(data[0], 4) + " mm", "window", 30, 7, "black", new HTuple(), new HTuple()); HOperatorSet.DispText(window, "Y方向偏差:" + System.Math.Round(data[1], 4) + " mm", "window", 50, 7, "black", new HTuple(), new HTuple()); Marking.CenterLocateTestSucceed = true; SetString(window, "OK", "green", 100); return(data); } } catch { try { SetString(window, "NG", "red", 100); } catch { } Marking.CenterLocateTestSucceed = false; return(null); } }
/// <summary>Constructor</summary> /// <param name="obj"> /// HALCON object that is linked to the graphical context gc. /// </param> /// <param name="gc"> /// Hashlist of graphical states that are applied before the object /// is displayed. /// </param> public HObjectEntry(HObject obj, Hashtable gc) { gContext = gc; HObj = obj; isRegion = false; }
private double ImageAlgorithmII(HObject ho_ResultImage) { // Local iconic variables HObject ho_ResultRegion = null; HObject ho_ResultConnectedRegions = null, ho_ResultSelectedRegions = null; HObject ho_ResultCircle = null, ho_ResultContour = null; // Local control variables HTuple hv_Width = null, hv_Height = null; HTuple hv_MetrologyHandle = null, hv_CircleRadiusTolerance = null; HTuple hv_NewRadius = null; HTuple hv_ResultArea = new HTuple(), hv_ResultRow = new HTuple(); HTuple hv_ResultColumn = new HTuple(), hv_MetrologyCircleIndice = new HTuple(); HTuple hv_CircleRadiusResult = new HTuple(); // Initialize local and output iconic variables HOperatorSet.GenEmptyObj(out ho_ResultRegion); HOperatorSet.GenEmptyObj(out ho_ResultConnectedRegions); HOperatorSet.GenEmptyObj(out ho_ResultSelectedRegions); HOperatorSet.GenEmptyObj(out ho_ResultCircle); HOperatorSet.GenEmptyObj(out ho_ResultContour); HOperatorSet.GetImageSize(ho_ResultImage, out hv_Width, out hv_Height); //创建测量模型 HOperatorSet.CreateMetrologyModel(out hv_MetrologyHandle); //设置测量对象图像大小 HOperatorSet.SetMetrologyModelImageSize(hv_MetrologyHandle, hv_Width, hv_Height); // hv_CircleRadiusTolerance = 100; //圆半径 hv_NewRadius = 324; //阈值图像 ho_ResultRegion.Dispose(); HOperatorSet.Threshold(ho_ResultImage, out ho_ResultRegion, 0, 60); //区域连通处理 ho_ResultConnectedRegions.Dispose(); HOperatorSet.Connection(ho_ResultRegion, out ho_ResultConnectedRegions); //根据面积和圆度来过滤想要的圆区域 ho_ResultSelectedRegions.Dispose(); HOperatorSet.SelectShape(ho_ResultConnectedRegions, out ho_ResultSelectedRegions, (new HTuple("area")).TupleConcat("roundness"), "and", (new HTuple(250000)).TupleConcat( 0.9), (new HTuple(320000)).TupleConcat(1)); //获取圆的中心坐标和面积 HOperatorSet.AreaCenter(ho_ResultSelectedRegions, out hv_ResultArea, out hv_ResultRow, out hv_ResultColumn); HOperatorSet.SetColor(WindowID, "green"); //设置区域的填充模式 HOperatorSet.SetDraw(WindowID, "margin"); //显示图像 HOperatorSet.DispObj(ho_ResultImage, WindowID); if (hv_ResultArea.Length != 0) { //生成圆 ho_ResultCircle.Dispose(); HOperatorSet.GenCircle(out ho_ResultCircle, hv_ResultRow, hv_ResultColumn, hv_NewRadius); //添加圆到测量模型里 HOperatorSet.AddMetrologyObjectCircleMeasure(hv_MetrologyHandle, hv_ResultRow, hv_ResultColumn, hv_NewRadius, hv_CircleRadiusTolerance, 5, 1.5, 30, (new HTuple("measure_transition")).TupleConcat( "min_score"), (new HTuple("all")).TupleConcat(0.4), out hv_MetrologyCircleIndice); //测量并拟合几何形状 HOperatorSet.ApplyMetrologyModel(ho_ResultImage, hv_MetrologyHandle); //获取测量模型里的测量轮廓 ho_ResultContour.Dispose(); HOperatorSet.GetMetrologyObjectResultContour(out ho_ResultContour, hv_MetrologyHandle, "all", "all", 1.5); //获取测量模型里的测量结果 HOperatorSet.GetMetrologyObjectResult(hv_MetrologyHandle, hv_MetrologyCircleIndice, "all", "result_type", "radius", out hv_CircleRadiusResult); //显示测量轮廓 HOperatorSet.DispObj(ho_ResultContour, WindowID); //设置文字显示位置 HOperatorSet.SetTposition(WindowID, 0, 0); //* 在窗口指定位置输出文字信息 HOperatorSet.WriteString(WindowID, "圆外径:" + hv_CircleRadiusResult); //清除测量模型 HOperatorSet.ClearMetrologyModel(hv_MetrologyHandle); ho_ResultRegion.Dispose(); ho_ResultConnectedRegions.Dispose(); ho_ResultSelectedRegions.Dispose(); ho_ResultCircle.Dispose(); ho_ResultContour.Dispose(); return(hv_CircleRadiusResult.D); } else { ho_ResultRegion.Dispose(); ho_ResultConnectedRegions.Dispose(); ho_ResultSelectedRegions.Dispose(); ho_ResultCircle.Dispose(); ho_ResultContour.Dispose(); return(0); } }