public MainWindow() { InitializeComponent(); InitializeComponent(); hdev_export = new HDevelopExport(); drawing_objects = new List <HTuple>(); }
public MainWindow() { InitializeComponent(); //Init ??? HDevelopExport hd = new HDevelopExport(); //HDevelopExportApp. }
private void SaveImage(HTuple handle, bool result) { try { Task.Run(() => { string imageName = $"{DateTime.Now:HHmmss}.tiff"; string res = result ? "OK" : "NG"; string pathSource = $@"{ProductMgr.GetInstance().ProductPath}Images\{DateTime.Now:yyyyMMdd}\{res}\Robot\Source\"; string pathWindow = $@"{ProductMgr.GetInstance().ProductPath}Images\{DateTime.Now:yyyyMMdd}\{res}\Robot\Window\"; if (!System.IO.Directory.Exists(pathSource)) { System.IO.Directory.CreateDirectory(pathSource); } if (!System.IO.Directory.Exists(pathWindow)) { System.IO.Directory.CreateDirectory(pathWindow); } string fileNameSource = $"{pathSource}{imageName}"; string fileNameWindow = $"{pathWindow}{imageName}"; HDevelopExport.WriteImage(imgSrc, fileNameSource); HDevelopExport.DumpWindow(handle, fileNameWindow); }); } catch (Exception) { } }
// Event handler koji se poziva kada zavrsi analiza slike za pick private static void PickUpdate(HDevelopExport sender, HalconEventArgs e) { App.PLC.WriteTag(PLC.STATUS.Kamere.CAM1RezultatX, e.RXcord); App.PLC.WriteTag(PLC.STATUS.Kamere.CAM1RezultatY, e.RYcord); App.PLC.WriteTag(PLC.STATUS.Kamere.CAM1RezultatAngle, e.AngleDeg); App.PLC.WriteTag(PLC.STATUS.Kamere.CAM1RezultatWorkpieceDiameter, e.WorkpieceDiameter); App.PLC.WriteTag(PLC.STATUS.Kamere.CAM1AnalizaOk, true); App.PLC.WriteTag(PLC.STATUS.Kamere.CAM1AnalizaOk, false); }
//private void PLC_Update_1_s(PLCInterface sender, PLCInterfaceEventArgs e) //{ // String msg = "SISTEM SPREMAN 1s"; // if (mwHandle != null) // { // mwHandle.tb_statusMessage.Dispatcher.BeginInvoke((Action)(() => { mwHandle.tb_statusMessage.Text = msg; })); // } //} // Event handler koji se poziva kad zavrsi analiza slike za mjerenje diametara private static void HalconUpdate(HDevelopExport sender, HalconEventArgs e) { App.PLC.WriteTag(PLC.STATUS.Kamere.CAM4Rezultat, e.PXvalue); App.PLC.WriteTag(PLC.STATUS.Kamere.CAM3Rezultat, e.CameraTemp); App.PLC.WriteTag(PLC.STATUS.Kamere.CAM4AnalizaOk, true); Thread.Sleep(100); App.PLC.WriteTag(PLC.STATUS.Kamere.CAM4AnalizaOk, false); // e.PXvalue = 0.0f; }
/// <summary> /// 更新显示控件 /// </summary> /// <param name="ctl"></param> public override void UpdateVisionControl(VisionControl ctl) { ctl.LockDisplay(); try { if (imgSrc != null && imgSrc.IsInitialized() && imgSrc.Key != IntPtr.Zero) { HTuple num = 0; HOperatorSet.CountObj(imgSrc, out num); if (num > 0)//&& m_image.IsInitialized() && m_image.Key != IntPtr.Zero) { HOperatorSet.DispObj(imgSrc, ctl.GetHalconWindow()); } // HOperatorSet.DispObj(ModelContour, ctl.GetHalconWindow()); //if (MeasureRect != null && MeasureRect.IsInitialized()) //{ // HOperatorSet.SetColor(m_visionControl.GetHalconWindow(), "red"); // HOperatorSet.DispObj(MeasureRect, ctl.GetHalconWindow()); //} if (Lines != null && Lines.IsInitialized()) { HOperatorSet.SetColor(m_visionControl.GetHalconWindow(), "blue"); HOperatorSet.DispObj(Lines, ctl.GetHalconWindow()); } if (IntraDistance != null && IntraDistance.Length > 0) { if (IntraDistance.Type == HTupleType.STRING) { HDevelopExport.disp_message(m_visionControl.GetHalconWindow(), IntraDistance, "window", 20, -1, "green", "false"); } else { var value = SideCameraCalibData.PixelToMm(IntraDistance); HDevelopExport.disp_message(m_visionControl.GetHalconWindow(), $"{value:F2}", "window", 20, -1, "green", "false"); } } } } catch (HalconException HDevExpDefaultException1) { System.Diagnostics.Debug.WriteLine(HDevExpDefaultException1.ToString()); } catch (Exception exp) { System.Diagnostics.Debug.WriteLine(exp.ToString()); } finally { ctl.UnlockDisplay(); } }
private void FindCalibObjPose(Object sender, EventArgs e) { HTuple ImgPath = "D:/Tool/Calvin/NET_Project/caltab/"; HTuple StartCamPar = new HTuple(0.012, 0, 0.0000022, 0.0000022, 2592 / 2, 1944 / 2, 2592, 1944);//(Focus, Kappa, Sx, Sy, Cx, Cy, Width, Height) HTuple CameraType = "area_scan_division"; HTuple PoseInfo = new HTuple("TransX", "TransY", "TransZ", "RotationX", "RotationY", "RotationZ", "Type"); HTuple PoseUnit = new HTuple("mm", "mm", "mm", "deg", "deg", "deg", ""); HTuple CalibDataID, objInCameraPose; HOperatorSet.SetDraw(hWindowControl.HalconWindow, "margin"); //HOperatorSet.GenCaltab(7, 7, 0.005, 0.5, ImgPath + "caltab.descr", ImgPath + "caltab.ps"); HOperatorSet.CreateCalibData("calibration_object", 1, 1, out CalibDataID); HOperatorSet.SetCalibDataCamParam(CalibDataID, 0, CameraType, StartCamPar); HOperatorSet.SetCalibDataCalibObject(CalibDataID, 0, ImgPath + "caltab.descr"); if (AcqHandle.Length > 0) { HObject Image; HOperatorSet.SetFramegrabberParam(AcqHandle, "ExposureTimeRaw", 100000); HOperatorSet.GrabImageStart(AcqHandle, -1); { HOperatorSet.GrabImageAsync(out Image, AcqHandle, -1); HGraphics.allObj["pic"] = Image; HGraphics.SetFullImagePart(Image); } } try { HOperatorSet.FindCalibObject(HGraphics.allObj["pic"], CalibDataID, 0, 0, 1, new HTuple(), new HTuple()); HOperatorSet.GetCalibDataObservPose(CalibDataID, 0, 0, 1, out objInCameraPose); HOperatorSet.SetSystem("flush_graphic", "false"); HOperatorSet.DispObj(HGraphics.allObj["pic"], hWindowControl.HalconWindow); HOperatorSet.SetColor(hWindowControl.HalconWindow, "green"); HOperatorSet.DispCaltab(hWindowControl.HalconWindow, ImgPath + "caltab.descr", StartCamPar, objInCameraPose, 1); objInCameraPose[0] = objInCameraPose[0] * 1000; objInCameraPose[1] = objInCameraPose[1] * 1000; objInCameraPose[2] = objInCameraPose[2] * 1000; HDevelopExport.disp_message(hWindowControl.HalconWindow, (PoseInfo + ": " + objInCameraPose.TupleRound() + "." + (objInCameraPose.TupleSub(objInCameraPose.TupleRound()).TupleAbs() * 1000).TupleRound() + " " + PoseUnit).TupleSelectRange(0, 5), "window", 12, 12, "green", "false"); HOperatorSet.SetSystem("flush_graphic", "true"); HOperatorSet.DispLine(hWindowControl.HalconWindow, -4, -4, -4, -4); } catch (Exception ex) { HOperatorSet.SetSystem("flush_graphic", "false"); HOperatorSet.DispObj(HGraphics.allObj["pic"], hWindowControl.HalconWindow); HOperatorSet.SetColor(hWindowControl.HalconWindow, "green"); HDevelopExport.disp_message(hWindowControl.HalconWindow, PoseInfo.TupleSelectRange(0, 5) + ": ???", "window", 12, 12, "green", "false"); HOperatorSet.SetSystem("flush_graphic", "true"); HOperatorSet.DispLine(hWindowControl.HalconWindow, -4, -4, -4, -4); } }
public App() { InitializeComponent(); // Load saved data from JSON file string DataBaseFileName = "savedata.JSON"; string DataBasePath = Path.Combine(Environment.CurrentDirectory, @"database", DataBaseFileName); String JSONstring = File.ReadAllText(DataBasePath); savedata = JsonConvert.DeserializeObject <List <ReportInterface.DimensionLine> >(JSONstring); // If JSON is empty we have null if (savedata == null) { savedata = new List <ReportInterface.DimensionLine>(); } // Load test data from JSON file string TestDataBaseFileName = "testdata.JSON"; string TestDataBasePath = Path.Combine(Environment.CurrentDirectory, @"database", TestDataBaseFileName); String TestJSONstring = File.ReadAllText(TestDataBasePath); testdata = JsonConvert.DeserializeObject <List <ReportInterface.TestData> >(TestJSONstring); // If JSON is empty we have null if (testdata == null) { testdata = new List <ReportInterface.TestData>(); } System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.High; //MainReportInterface = ((ReportInterface)Application.Current.FindResource("MainReport")); PLC = ((PLCInterface)Application.Current.FindResource("PLCinterf")); HDevExp = new HDevelopExport(); pIzvjestaji = new PIzvjestaji(); pPostavke = new PPostavke(); pRobot = new PRobot(); pPoroznost = new PPoroznost(); pUcenje = new PUcenje(); pVisine = new PVisine(); pDijametri = new PDijametri(); pRucno = new PRucno(); //Report interface //initReportInterface = new ReportInterface(); PLC.StartCyclic(); // Possible system null reference PLC.Update_Online_Flag += new PLCInterface.OnlineMarker(PLCInterface_PLCOnlineChanged); PLC.Update_100_ms += new PLCInterface.UpdateHandler(PLC_Update_100_ms); //PLC.Update_1_s += new PLCInterface.UpdateHandler(PLC_Update_1_s); HDevExp.UpdateResult += new HDevelopExport.UpdateHandler(HalconUpdate); HDevExp.UpdateResultPick += new HDevelopExport.UpdateHandlerPick(PickUpdate); HDevExp.PorosityDetected += new HDevelopExport.PorosityDetectedEventHandler(PorosityIsDetected); HDevExp.PorosityDetectionStart += new HDevelopExport.PorosityDetectionStartEventHandler(DetectionStart); HDevExp.PorosityDetectionHorStart += new HDevelopExport.PorosityDetectionHorStartEventHandler(DetectionHorStart); // Frame always ON CAM4 //HDevExp.OpenCamFrame(); }
public HDevelopTemplate() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // HDevExp = new HDevelopExport(); }
public frmMain() { InitializeComponent(); //myConfig = new ConfigInfo(); //Pro.SelectedObject = myConfig; //Pro.PropertyValueChanged += Pro_PropertyValueChanged; nExpTime = 2000; fCamGain = 1.1f; bVideoMode = false; strSavePathOK = ""; strSavePathNG = ""; strFileName = ""; imgOri = null; detectInstanceDyn = null; detectInstanceNorm = null; }
public override bool ProcessImage(VisionControl ctl) { try { ctl.clearObj(); ctl.DisplayResults(); //保存图像 //string imageName = $"{DateTime.Now:HHmmss}.tiff"; //if (AutoForm._autoForm.Param.IsSaveImageAll) //{ // //保存原图 // string path = $@"{ProductMgr.GetInstance().ProductPath}Images\Platform\{DateTime.Now:yyMMdd}\Source\"; // if (!System.IO.Directory.Exists(path)) // { // System.IO.Directory.CreateDirectory(path); // } // string fileName = $"{path}{imageName}"; // HDevelopExport.WriteImage(imgSrc, fileName); //} //图像预处理 HObject image; if (ProductMgr.GetInstance().Param.PlatformRegion != null) { HOperatorSet.ReduceDomain(imgSrc, ProductMgr.GetInstance().Param.PlatformRegion, out image); //if (ProductMgr.GetInstance().Param.IsPerprocess) //{ // image = HDevelopExport.Preprocess(image, ProductMgr.GetInstance().Param.Emphasize, false); //} } else { image = imgSrc; } //查找模板 HTuple row, column, angle, scale, score; bool result = HDevelopExport.FindScaleShapeModel(image, out row, out column, out angle, out scale, out score); //显示轮廓 HDevelopExport.dev_display_shape_matching_results(ctl.GetHalconWindow(), ProductMgr.GetInstance().Param.ModelID, "blue", row, column, angle, scale, scale, 0); /* * //二次定位 * if (result && ProductMgr.GetInstance().Param.IsSecondPos) * { * HTuple transRow, transColumn, transRadian; * result = HDevelopExport.FindPinCenter(imgSrc, row, column, angle, out transRow, out transColumn, out transRadian); * * if (result) * { * row = transRow; * column = transColumn; * angle = transRadian; * } * * //ctl.DisplayResults(); * } */ if (!result) { Log.Show("查找模板失败"); } else { //弧度差 HTuple relRow, relColumn, relRadian, rowTrans, colTrans; //relRadian = PlatformCalibData.MarkRadian - angle; relRadian = 0 - angle; //旋转特征点 //HTuple homMat2D; //HOperatorSet.HomMat2dIdentity(out homMat2D); //HOperatorSet.HomMat2dRotate(homMat2D, relRadian, PlatformCalibData.CenterRow, PlatformCalibData.CenterColumn, out homMat2D); //HOperatorSet.AffineTransPixel(homMat2D, row, column, out rowTrans, out colTrans); //以平台Mark点为基准 //relRow = PlatformCalibData.MarkRow - rowTrans; //relColumn = PlatformCalibData.MarkColumn - colTrans; //没有旋转,直接计算X和Y方向的差值,下面的角度只用于显示 //relRow = PlatformCalibData.MarkRow - row; //relColumn = PlatformCalibData.MarkColumn - column; //弧度转角度 HTuple degree; HOperatorSet.TupleDeg(relRadian, out degree); //赋值给需要发送的数据 //SendData.X = PlatformCalibData.PixelToMm(relColumn); //SendData.Y = PlatformCalibData.PixelToMm(relRow); //SendData.Angle = degree; //用矩阵获得Mark点的世界坐标和模板的世界坐标,求差值 HTuple colMark, rowMark; HOperatorSet.AffineTransPixel(PlatformCalibData.HomMat2D, PlatformCalibData.MarkColumn, PlatformCalibData.MarkRow, out colMark, out rowMark); HOperatorSet.AffineTransPixel(PlatformCalibData.HomMat2D, column, row, out colTrans, out rowTrans); SendData.X = colMark - colTrans; SendData.Y = rowMark - rowTrans; ctl.AddToStack(ProductMgr.GetInstance().Param.ModelContours); ctl.AddToStack(ProductMgr.GetInstance().Param.ModelOriginContours); ctl.AddToStack(ProductMgr.GetInstance().Param.MarkContours); ctl.DisplayResults(); //显示数据到窗口 HTuple deg; HOperatorSet.TupleDeg(angle, out deg); Log.Show($"查找模板:row:{row.D:F2},column:{column.D:F2},degree:{deg.D:F2},分数:{score.D:F2}"); HDevelopExport.disp_message(ctl.GetHalconWindow(), $"位置:{row.D:F2},{column.D:F2},{degree.D:F2}", "window", 10, -1, "green", "false"); HDevelopExport.disp_message(ctl.GetHalconWindow(), $"分数:{score.D:F2}", "window", 30, -1, "green", "false"); HDevelopExport.disp_message(ctl.GetHalconWindow(), $"X:{SendData.X:F2},Y:{SendData.Y:F2},A:{SendData.Angle:F2}", "window", 150, -1, "green", "false"); Log.Show($"目标位置:X:{SendData.X:F2},Y:{SendData.Y:F2},A:{SendData.Angle:F2}"); } //保存查找模板的窗口图片和原图 if (AutoForm._autoForm.Param.IsSaveImageAll) { SaveImage(ctl.GetHalconWindow(), result); } else { if (AutoForm._autoForm.Param.IsSaveImageNG && !result) { SaveImage(ctl.GetHalconWindow(), result); } } return(result); } catch (Exception) { return(false); } }
void ThreadRun() { HDevelopExport HD = new HDevelopExport(rectHalcon, hWindow); }
private void btnCalc_Click(object sender, EventArgs e) { HDevelopExport hd = new HDevelopExport(); hd.RunHalcon(hWindowControl1.HalconWindow); }
private void MainForm_Load(object sender, EventArgs e) { GetInitialFormSize(); //this.AutoScroll = true; //this.SetAutoSizeMode(FormSizeWidth,FormSizeHeight); //this.AutoScrollMinSize.Width = FormSizeWidth; //this.AutoScrollMinSize.Height = FormSizeHeight; GetAllCrlLocation(this); GetAllCrlSize(this); defect_detection_method = 0;//图像形态学方法 rb_Morphology.Checked = true; rb_deeplearning.Checked = false; //this.Resize += new EventHandler(MainForm_Resize); X = this.Width; Y = this.Height; /* * sim_timer = new System.Windows.Forms.Timer(); * sim_timer.Interval = 1000; * sim_timer.Enabled = true; * sim_timer.Tick += new EventHandler(sim_timer_Tick); */ setTag(this); imageList1.Dispose(); imageList1 = new ImageList(); skillArray = JsonMapper.ToObject <Image_Resource[]>(File.ReadAllText("images\\res.json", Encoding.UTF8));//使用这种方法,泛型类的字段,属性必须为public,而且字段名,顺序必须与json文件中对应 foreach (var temp in skillArray) { Console.WriteLine(temp); } //imageList1.Images.Clear(); //for (int i=1;i<= skillArray[0].number; i++) //{ // imageList1.Images.Add(Image.FromFile(skillArray[0].path + skillArray[0].prefix+string.Format("{0:00}.bmp", i))); // HOperatorSet.ReadImage(out ImageArrary[i-1], skillArray[0].path + skillArray[0].prefix + string.Format("{0:00}.bmp", i)); //} for (int i = 0; i < skillArray.Length; i++) { cbSampleData.Items.Add(skillArray[i].name); } /* * 2018.09拍摄钢管 * 2018.08东莞样图 * 2018.06塑料样图 */ cbSampleData.SelectedIndex = 2; //this.lvPictureList.View = View.LargeIcon; //this.lvPictureList.LargeImageList = this.imageList1; //this.lvPictureList.BeginUpdate(); ////数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度 //for (int i = 0; i < skillArray[0].number; i++)//添加10行数据 //{ // ListViewItem lvi = new ListViewItem(); // lvi.ImageIndex = i; // //通过与imageList绑定,显示imageList中第i项图标 // lvi.Text = skillArray[0].prefix + string.Format("{0:00}.bmp", i+1); // lvi.Text = skillArray[0].prefix + string.Format("{0:00}.bmp", i + 1); // this.lvPictureList.Items.Add(lvi); //} //this.lvPictureList.EndUpdate(); hdev_export = new HDevelopExport(hWindowControl1.HalconWindow); // hdev_export = new HDevelopExport(); //MainForm_Resize(new object(), new EventArgs());//x,y可在实例化时赋值,最后这句是新加的,在MDI时有用 }
void RunCheck() { Stopwatch sw = new Stopwatch(); sw.Start(); //计时开始 string strLog = null; //判断用变量 try { int judgeFlag = 1; HDevelopExport HD = new HDevelopExport(); HD.RunHalcon(HWCWPF.HalconWindow); //HD.cs_Quality[] 结果数组 for (int i = 0; i < HD.cs_Quality.Length; i++) { strLog += HD.cs_Quality[i].F.ToString("f2") + ","; //log输出用 resultList[i].Content = HD.cs_Quality[i].F.ToString("f2"); //界面显示 if (HD.cs_Quality[i].F > Convert.ToDouble(spectable.Rows[i][1])) { this.judgeList[i].Content = "OK"; this.judgeList[i].Foreground = new SolidColorBrush(Color.FromRgb(0, 255, 0)); } else { judgeList[i].Content = "NG"; this.judgeList[i].Foreground = new SolidColorBrush(Color.FromRgb(255, 0, 0)); HOperatorSet.SetColor(HWCWPF.HalconWindow, "red"); HOperatorSet.SetDraw(HWCWPF.HalconWindow, "margin"); HOperatorSet.SetLineWidth(HWCWPF.HalconWindow, 3); HOperatorSet.DispCircle(HWCWPF.HalconWindow, HD.cs_y[i], HD.cs_x[i], 20); judgeFlag = -1; } } //总的判断 if (judgeFlag == 1) { this.finalLbl.Content = "OK"; this.finalLbl.Foreground = new SolidColorBrush(Colors.Green); using (SoundPlayer player = new SoundPlayer()) { string location = System.Environment.CurrentDirectory + "/OK.wav"; player.SoundLocation = location; player.Play(); } okCount++; okCountLbl.Content = okCount; } else { this.finalLbl.Content = "NG"; this.finalLbl.Foreground = new SolidColorBrush(Colors.Red); using (SoundPlayer player = new SoundPlayer()) { string location = System.Environment.CurrentDirectory + "/NG.wav"; player.SoundLocation = location; player.Play(); } ngCount++; ngCountLbl.Content = ngCount; } } catch (Exception Err) { MessageBox.Show(Err.Message); LogSet(Err.Message); } finally { GC.Collect(); } //计时结束 sw.Stop(); TimeSpan ts = sw.Elapsed; tactLbl.Content = ts.TotalSeconds.ToString("0.000"); insLog(strLog); }
/// <summary> /// 检测函数 /// </summary> private void Detect() { pbImage.Visible = false; hWindowCtrl.Visible = true; if (imgOri != null) { Int32 nDefects = 0; Int32 nMode = 0; // detection method selection String strFullFileName; if (string.IsNullOrEmpty(ParamSetting.ImageSavePath)) { ParamSetting.ImageSavePath = Application.StartupPath; } strFullFileName = ParamSetting.ImageSavePath + "\\" + strFileName; // save temp image imgOri.Save(strFullFileName); switch (nMode) { case 0: // method 0: dynamic thresholding detectInstanceDyn = new HDevelopExport(); detectInstanceDyn.InitHalcon(); if (File.Exists(strFullFileName)) { detectInstanceDyn.RunHalcon(hWindowCtrl.HalconWindow, strFullFileName, ParamSetting.MeasureParam.MinArea, ParamSetting.MeasureParam.FilterSize, ParamSetting.MeasureParam.DynamicRange, out nDefects); } break; case 1: // method 1: normal thresholding detectInstanceNorm = new HDevelopExport1(); detectInstanceNorm.InitHalcon(); if (File.Exists(strFullFileName)) { detectInstanceNorm.RunHalcon(hWindowCtrl.HalconWindow, strFullFileName, ParamSetting.MeasureParam.MinArea, ParamSetting.MeasureParam.GrayThreshold, out nDefects); } break; } if (nDefects > 0) { lblResult.Text = "NG"; lblResult.BackColor = Color.Red; if (!string.IsNullOrEmpty(ParamSetting.ImageSavePath)) { strSavePathNG = ParamSetting.ImageSavePath + "\\" + DateTime.Now.ToShortDateString().Replace("/", "-") + "\\NG"; CheckAndCreatePath(strSavePathNG); if (pbImage.Image != null) { pbImage.Image.Save(strSavePathNG + "\\" + strFileName); } } } else { lblResult.Text = "OK"; lblResult.BackColor = Color.Green; if (!string.IsNullOrEmpty(ParamSetting.ImageSavePath)) { strSavePathOK = ParamSetting.ImageSavePath + "\\" + DateTime.Now.ToShortDateString().Replace("/", "-") + "\\OK"; CheckAndCreatePath(strSavePathOK); if (pbImage.Image != null) { pbImage.Image.Save(strSavePathOK + "\\" + strFileName); } } } } pbImage.Image = imgOri; }
public HDevelopTemplate() // Constructor { InitializeComponent(); HDevExp = new HDevelopExport(); }
private void button1_Click(object sender, EventArgs e) { HDevelopExport HD = new HDevelopExport(); HD.action(); }
/* 检测按钮事件 */ private void btnDetect_Click(object sender, EventArgs e) { pbImage.Visible = false; hWindowCtrl.Visible = true; if (imgOri != null) { Int32 nDefects = 0; Int32 nMode = 1; String strFullFileName; if (strSavePath == "") { strSavePath = Application.StartupPath; } strFullFileName = strSavePath + strFileName; // save temp image imgOri.Save(strFullFileName); switch (nMode) { case 0: // method 0: dynamic thresholding detectInstanceDyn = new HDevelopExport(); detectInstanceDyn.InitHalcon(); if (File.Exists(strFullFileName)) { detectInstanceDyn.RunHalcon(hWindowCtrl.HalconWindow, strFullFileName, myConfig.面积, myConfig.滤波尺寸, myConfig.动态二值化阈值, out nDefects); } break; case 1: // method 1: normal thresholding detectInstanceNorm = new HDevelopExport1(); detectInstanceNorm.InitHalcon(); if (File.Exists(strFullFileName)) { detectInstanceNorm.RunHalcon(hWindowCtrl.HalconWindow, strFullFileName, myConfig.面积, myConfig.灰度值, out nDefects); } break; } if (nDefects > 0) { lblResult.Text = "NG"; lblResult.BackColor = Color.Red; if (strSavePath != null && strSavePath.Length != 0) { strSavePathNG = strSavePath + "\\NG"; CheckAndCreatePath(strSavePathNG); if (pbImage.Image != null) { pbImage.Image.Save(strSavePathNG + "\\" + strFileName); } } } else { lblResult.Text = "OK"; lblResult.BackColor = Color.Green; if (strSavePath != null && strSavePath.Length != 0) { strSavePathOK = strSavePath + "\\OK"; CheckAndCreatePath(strSavePathOK); if (pbImage.Image != null) { pbImage.Image.Save(strSavePathOK + "\\" + strFileName); } } } } pbImage.Image = imgOri; }
private void button1_Click(object sender, EventArgs e) { string file = ""; if (comboBox1.Text.ToUpper() == "TOP") { mSizdType = SideType.TOP; file = "车顶.txt"; offsetImgageX = offsetImgageXTop; offsetImgageY = offsetImgageYTop; } else if (comboBox1.Text.ToUpper() == "LEFT") { mSizdType = SideType.LEFT; file = "侧边.txt"; offsetImgageX = offsetImgageXLft; offsetImgageY = offsetImgageYLft; } else { MessageBox.Show("选择面"); return; } int countAdd = 0; //Y方向的间隔 补齐参数 老的是10 if (System.IO.File.Exists(file) == false) { MessageBox.Show("File :" + file + " not exist"); return; } FileStream fs = new FileStream(file, FileMode.Open); StreamReader sr = new StreamReader(fs); obj_MotorP.Clear(); obj_MotorP2P.Clear(); string str; XYZ tempXyz; long count = 0; obj_xyz.Clear(); int[][] buffer; while ((str = sr.ReadLine()) != null) { string[] temp = str.Split(' '); if (temp.Length != 3) { continue; } tempXyz.x = (int)double.Parse(temp[0]) + offsetImgageX; tempXyz.y = double.Parse(temp[1]) - offsetImgageY; tempXyz.z = double.Parse(temp[2]); if (obj_xyz.Count == 0) { obj_xyz.Add(tempXyz); } else { if (tempXyz.x != obj_xyz[obj_xyz.Count - 1].x) { obj_xyz.Add(tempXyz); } } } Bitmap bt = new Bitmap(1080, 3000); for (int w = 0; w < bt.Width; w++) { for (int h = 0; h < bt.Height; h++) { bt.SetPixel(w, h, System.Drawing.Color.FromArgb(0, 0, 0)); } } for (int i = 0; i < obj_xyz.Count; i++) { //bt.SetPixel(obj_xyz[i].x, (int)obj_xyz[i].y, System.Drawing.Color.FromArgb(255, 255, 255)); if (i > 1) { int offset = obj_xyz[i].x - obj_xyz[i - 1].x;//补齐 x 方向的缺点 if (offset > 1 && offset < 10 && obj_xyz[i].y == obj_xyz[i - 1].y) { for (int index = 0; index < offset; index++) { bt.SetPixel(obj_xyz[i].x - index, (int)obj_xyz[i].y, System.Drawing.Color.FromArgb(255, 255, 255)); for (int indexAdd = 0; indexAdd < countAdd; indexAdd++) { bt.SetPixel(obj_xyz[i].x - index, (int)obj_xyz[i].y + indexAdd, System.Drawing.Color.FromArgb(255, 255, 255)); } } } else { bt.SetPixel(obj_xyz[i].x, (int)obj_xyz[i].y, System.Drawing.Color.FromArgb(255, 255, 255)); for (int indexAdd = 0; indexAdd < countAdd; indexAdd++) //补齐Y方向 { bt.SetPixel(obj_xyz[i].x, (int)obj_xyz[i].y + indexAdd, System.Drawing.Color.FromArgb(255, 255, 255)); } } } else { bt.SetPixel(obj_xyz[i].x, (int)obj_xyz[i].y, System.Drawing.Color.FromArgb(255, 255, 255)); for (int index = 0; index < 10; index++)// 补齐y 方向的间隔 { bt.SetPixel(obj_xyz[i].x, (int)obj_xyz[i].y + index, System.Drawing.Color.FromArgb(255, 255, 255)); } } } sr.Close(); fs.Close(); bt.Save("Conv2.bmp", System.Drawing.Imaging.ImageFormat.Bmp); if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); } pictureBox1.Image = bt; List <Str_Ht> lsHT = new List <Str_Ht>(); HDevelopExport hd = new HDevelopExport(); hd.RunHalcon(ref lsHT, mSizdType); GetNewImage(lsHT); }
private void Execute_Click(object sender, EventArgs e) { HTuple Width, Height, AbsoluteHisto; HObject Rectangle, Image; Image = HGraphics.allObj["pic"].Clone(); //Calculate absolute histogram of the image HOperatorSet.GetImageSize(HGraphics.allObj["pic"], out Width, out Height); HOperatorSet.GenRectangle1(out Rectangle, 0, 0, Height - 1, Width - 1); HOperatorSet.GrayHistoAbs(Rectangle, HGraphics.allObj["pic"], 1, out AbsoluteHisto); //find the gray value with the greatest frequency HTuple Indices, BackgroundGrayValue; HOperatorSet.TupleSortIndex(AbsoluteHisto, out Indices); HOperatorSet.TupleInverse(Indices, out Indices); BackgroundGrayValue = Indices.I; if (BackgroundGrayValue > 255 - 21) { BackgroundGrayValue = 255 - 20; } //Thresholding HTuple DilationRadius = 5; HObject TempRegion, TempContour; HOperatorSet.Threshold(HGraphics.allObj["pic"], out TempRegion, new HTuple(BackgroundGrayValue.I + 20, 0), new HTuple(255, BackgroundGrayValue.I - 20)); HOperatorSet.Connection(TempRegion, out TempRegion); HOperatorSet.SelectShape(TempRegion, out TempRegion, "area", "and", 30, 999999); HOperatorSet.Union1(TempRegion, out TempRegion); HOperatorSet.DilationCircle(TempRegion, out TempRegion, DilationRadius); HOperatorSet.FillUp(TempRegion, out TempRegion); HOperatorSet.GenContourRegionXld(TempRegion, out TempContour, "border"); HOperatorSet.SmoothContoursXld(TempContour, out TempContour, 5); HOperatorSet.GenRegionContourXld(TempContour, out TempRegion, "filled"); HOperatorSet.ErosionCircle(TempRegion, out TempRegion, 5); HGraphics.allObj["1_defectregion_erosion_red_margin_thick"] = TempRegion.Clone(); HOperatorSet.Union1(TempRegion, out TempRegion); HOperatorSet.ReduceDomain(Image, TempRegion, out Image); HObject DiffOfGauss, RegionCrossings; HOperatorSet.DiffOfGauss(Image, out DiffOfGauss, 4, 50); HOperatorSet.DualThreshold(DiffOfGauss, out RegionCrossings, 20, 11, 11); HGraphics.allObj["crossingregion_colored_margin"] = RegionCrossings; HGraphics.display(); HTuple Number, Area, Row, Column, Convexity, Min, Max, Range, Mean, Deviation, Circularity; HTuple DefectInfo = new HTuple("XY", "Size", "Max", "Min", "Mean", "Deviation", "Circularity", "Convexity"); HOperatorSet.CountObj(HGraphics.allObj["1_defectregion_erosion_red_margin_thick"], out Number); HOperatorSet.SetFont(hWindowControl.HalconWindow, "-Arial-12-*-0.5-*-*-1-ANSI_CHARSET-"); for (int Index = 1; Index <= Number; Index++) { HOperatorSet.SelectObj(HGraphics.allObj["1_defectregion_erosion_red_margin_thick"], out TempRegion, Index); HOperatorSet.AreaCenter(TempRegion, out Area, out Row, out Column); HOperatorSet.Convexity(TempRegion, out Convexity); HOperatorSet.MinMaxGray(TempRegion, Image, 0, out Min, out Max, out Range); HOperatorSet.Intensity(TempRegion, Image, out Mean, out Deviation); HOperatorSet.RegionFeatures(TempRegion, "circularity", out Circularity); HTuple Unit = new HTuple("(" + Row + ", " + Column + ")", Area, Max, Min, Mean, Deviation, Circularity, Convexity); HDevelopExport.disp_message(hWindowControl.HalconWindow, DefectInfo + ": " + Unit, "image", Row, Column, "green", "false"); } HOperatorSet.SetFont(hWindowControl.HalconWindow, "-Courier New-18-*-*-*-*-1-"); HDevelopExport.disp_message(hWindowControl.HalconWindow, "Number of Defect: " + Number, "window", 12, 12, "green", "false"); }
public override bool ProcessImage(VisionControl ctl) { try { //清理数据 foreach (var mea in MeasureMgr.GetInstance().MeasureList) { mea.ClearResult(); } ctl.clearObj(); ctl.DisplayResults(); //保存图像 //string imageName = $"{DateTime.Now:HHmmss}.tiff"; //if (AutoForm._autoForm.Param.IsSaveImageAll) //{ // //保存原图 // string path = $@"{ProductMgr.GetInstance().ProductPath}Images\Robot\{DateTime.Now:yyMMdd}\Source\"; // if (!System.IO.Directory.Exists(path)) // { // System.IO.Directory.CreateDirectory(path); // } // string fileName = $"{path}{imageName}"; // HDevelopExport.WriteImage(imgSrc, fileName); //} //图像预处理 HObject image; if (ProductMgr.GetInstance().Param.PlatformRegion != null) { HOperatorSet.ReduceDomain(imgSrc, ProductMgr.GetInstance().Param.PlatformRegion, out image); //if (ProductMgr.GetInstance().Param.IsPerprocess) //{ // image = HDevelopExport.Preprocess(image, ProductMgr.GetInstance().Param.Emphasize, false); //} } else { image = imgSrc; } //查找模板 HTuple row, column, angle, scale, score; bool result = HDevelopExport.FindScaleShapeModel(image, out row, out column, out angle, out scale, out score); //显示轮廓 HDevelopExport.dev_display_shape_matching_results(ctl.GetHalconWindow(), ProductMgr.GetInstance().Param.ModelID, "blue", row, column, angle, scale, scale, 0); if (result && ProductMgr.GetInstance().Param.IsSecondPos) { HTuple transRow, transColumn, transRadian; result = HDevelopExport.FindPinCenter(imgSrc, row, column, angle, out transRow, out transColumn, out transRadian); if (result) { row = transRow; column = transColumn; angle = transRadian; } //ctl.DisplayResults(); } if (!result) { Log.Show("查找模板失败"); return(false); } //*************相对位置************** //HTuple relRow, relColumn; //relRow = PlatformCalibData.MarkRow - row; //relColumn = PlatformCalibData.MarkColumn - column; //SendData.X = PlatformCalibData.PixelToMm(relColumn); //SendData.Y = PlatformCalibData.PixelToMm(relRow); //用矩阵获得Mark点的世界坐标和模板的世界坐标,求差值 HTuple colMark, rowMark, rowTrans, colTrans; HOperatorSet.AffineTransPixel(PlatformCalibData.HomMat2D, PlatformCalibData.MarkColumn, PlatformCalibData.MarkRow, out colMark, out rowMark); HOperatorSet.AffineTransPixel(PlatformCalibData.HomMat2D, column, row, out colTrans, out rowTrans); SendData.X = colMark - colTrans; SendData.Y = rowMark - rowTrans; Log.Show($"目标位置:X:{SendData.X:F2},Y:{SendData.Y:F2}"); //***********************测量**************************** MeasureMgr.GetInstance().MeasureAll(image, row, column, angle); //显示数据 int hasCount = 0, meaCount = 0; for (int i = 0; i < MeasureMgr.GetInstance().MeasureList.Count; i++) { var mea = MeasureMgr.GetInstance().MeasureList[i]; hasCount += mea.PinCount; meaCount += mea.CountOK + mea.CountAreaNG + mea.CountPosNG; //发送的数据 SendData.CountAreaNG += mea.CountAreaNG; SendData.CountPosNG += mea.CountPosNG; if (mea.DiameterMax.Length > 0) { //显示和保存数据 Data.Show(i, mea.DiameterMax.ToDArr(), mea.DisLeft.ToDArr(), mea.DisRight.ToDArr(), mea.DisTop.ToDArr()); } } ctl.AddToStack(ProductMgr.GetInstance().Param.ModelContours); ctl.AddToStack(ProductMgr.GetInstance().Param.ModelOriginContours); ctl.AddToStack(ProductMgr.GetInstance().Param.MarkContours); ctl.DisplayResults(); //显示数据到窗口 HTuple degree; HOperatorSet.TupleDeg(angle, out degree); Log.Show($"查找模板:row:{row.D:F2},column:{column.D:F2},degree:{degree.D:F2},分数:{score.D:F2}"); HDevelopExport.disp_message(ctl.GetHalconWindow(), $"位置:{row.D:F2},{column.D:F2},{degree.D:F2}", "window", 10, -1, "green", "false"); HDevelopExport.disp_message(ctl.GetHalconWindow(), $"分数:{score.D:F2}", "window", 30, -1, "green", "false"); HDevelopExport.disp_message(ctl.GetHalconWindow(), $"X:{SendData.X:F2},Y:{SendData.Y:F2}", "window", 150, -1, "green", "false"); HDevelopExport.disp_message(ctl.GetHalconWindow(), $"{hasCount}-{meaCount}", "window", 170, -1, "green", "false"); if (SendData.CountAreaNG > 0) { HDevelopExport.disp_message(ctl.GetHalconWindow(), $"面积NG:{SendData.CountAreaNG}", "window", 190, -1, "red", "false"); } if (SendData.CountPosNG > 0) { HDevelopExport.disp_message(ctl.GetHalconWindow(), $"位置NG:{SendData.CountPosNG}", "window", 210, -1, "magenta", "false"); } //显示日志 Log.Show($"面积NG:{SendData.CountAreaNG},位置NG:{SendData.CountPosNG}"); //保存窗口图像和原图 result = result && SendData.CountAreaNG == 0 && SendData.CountPosNG == 0; if (AutoForm._autoForm.Param.IsSaveImageAll) { SaveImage(ctl.GetHalconWindow(), result); } else { if (AutoForm._autoForm.Param.IsSaveImageNG && !result) { SaveImage(ctl.GetHalconWindow(), result); } } return(true); } catch (Exception) { return(false); } }
private void Form1_Load(object sender, EventArgs e) { HDevelopExport hd = new HDevelopExport(); hd.RunHalcon(hWindowControl1.HalconWindow); }
private void btnCreateRoi_Click(object sender, EventArgs e) { HDevelopExport HD = new HDevelopExport(); HD.RunHalcon(hWindowControl1.HalconWindow); }
public static void thisStart( ) { HDevelopExport.acquireimage(); }
public HDevelopTemplate() { InitializeComponent(); HDevExp = new HDevelopExport(); }
static HDevelopExport() { Singletone = new HDevelopExport(); }
public override bool ProcessImage(VisionControl ctl) { try { //清理数据 foreach (var mea in MeasureMgr.GetInstance().MeasureList) { mea.ClearResult(); } ctl.clearObj(); ctl.DisplayResults(); //图像预处理 HObject image; if (ProductMgr.GetInstance().Param.PlatformRegion != null) { HOperatorSet.ReduceDomain(imgSrc, ProductMgr.GetInstance().Param.PlatformRegion, out image); } else { image = imgSrc; } //查找模板 HTuple row, column, angle, scale, score; bool result = HDevelopExport.FindScaleShapeModel(image, out row, out column, out angle, out scale, out score); //显示轮廓 HDevelopExport.dev_display_shape_matching_results(ctl.GetHalconWindow(), ProductMgr.GetInstance().Param.ModelID, "blue", row, column, angle, scale, scale, 0); if (!result) { Log.Show("查找模板失败"); return(false); } //***********************测量**************************** image = MeasureMgr.GetInstance().ImagePre(image); MeasureMgr.GetInstance().MeasureAll(image, row, column, angle); //ctl.AddToStack(image); //显示数据 bool resRoi = true;//每个测量区域都做判断 int hasCount = 0, meaCount = 0; for (int i = 0; i < MeasureMgr.GetInstance().MeasureList.Count; i++) { var mea = MeasureMgr.GetInstance().MeasureList[i]; if (mea.PinCount != mea.CountPinMea) { resRoi = false; } hasCount += mea.PinCount; //meaCount += mea.CountOK + mea.CountAreaNG + mea.CountPosNG; meaCount += mea.CountPinMea; //发送的数据 //SendData.CountAreaNG += mea.CountAreaNG; //SendData.CountPosNG += mea.CountPosNG; //if (mea.DiameterMax.Length > 0) //{ // //显示和保存数据 // Data.Show(i, mea.DiameterMax.ToDArr(), mea.DisLeft.ToDArr(), mea.DisRight.ToDArr(), mea.DisTop.ToDArr()); //} } string color = "green"; if (resRoi && hasCount == meaCount) { color = "green"; SendData.PinCountOK = true; } else { color = "red"; SendData.PinCountOK = false; } ctl.AddToStack(ProductMgr.GetInstance().Param.ModelContours); ctl.AddToStack(ProductMgr.GetInstance().Param.ModelOriginContours); //ctl.AddToStack(ProductMgr.GetInstance().Param.MarkContours); ctl.DisplayResults(); for (int i = 0; i < MeasureMgr.GetInstance().MeasureList.Count; i++) { var mea = MeasureMgr.GetInstance().MeasureList[i]; if (mea.PinCount == mea.CountPinMea) { HDevelopExport.disp_message(ctl.GetHalconWindow(), $"ROI{i}数量:{mea.PinCount},测量数量:{mea.CountPinMea}", "window", 10 + 20 * i, -1, "green", "false"); } else { HDevelopExport.disp_message(ctl.GetHalconWindow(), $"ROI{i}数量:{mea.PinCount},测量数量:{mea.CountPinMea}", "window", 10 + 20 * i, -1, "red", "false"); } } HDevelopExport.disp_message(ctl.GetHalconWindow(), $"总数量:{hasCount},测量数量:{meaCount}", "window", 10 + 20 * MeasureMgr.GetInstance().MeasureList.Count, -1, color, "false"); //保存窗口图像和原图 result = result && SendData.CountAreaNG == 0 && SendData.CountPosNG == 0; if (AutoForm._autoForm.Param.IsSaveImageAll) { SaveImage(ctl.GetHalconWindow(), result); } else { if (AutoForm._autoForm.Param.IsSaveImageNG && !result) { SaveImage(ctl.GetHalconWindow(), result); } } return(true); } catch (Exception) { return(false); } }
public static void Init(HTuple wind) { HDevelopExport.mWindow = wind; HDevelopExport.acquireimage(); }
private void HalconUpdate(HDevelopExport sender, HalconEventArgs e) { App.PLC.WriteTag(PLC.STATUS.Kamere.CAM4Rezultat, e.PXvalue); App.PLC.WriteTag(PLC.STATUS.Kamere.CAM4AnalizaOk, true); App.PLC.WriteTag(PLC.STATUS.Kamere.CAM4AnalizaOk, false); }