/// <summary> /// 从相机中获取图像 /// </summary> /// <param name="camera"></param> /// <param name="errMsg"></param> /// <returns></returns> public static CogImage8Grey GetImage(CogAcqFifoTool camera, ref string errMsg) { if (camera != null) { CogImage8Grey image = null; try { camera.Run(); if (camera.RunStatus.Result == CogToolResultConstants.Accept) { image = (CogImage8Grey)camera.OutputImage; } else { image = null; } //偶尔会有取像异常,需要二次取像 if (image == null) { camera.Run(); if (camera.RunStatus.Result == CogToolResultConstants.Accept) { image = (CogImage8Grey)camera.OutputImage; } else { errMsg = "相机二次取像都失败,无法获取图片"; } } } catch (Exception ex) { image = null; errMsg = "相机取像出现异常,异常信息:" + ex.Message; } return(image); } else { errMsg = "相机尚未初始化"; } return(null); }
private void cmdImageAcquisitionLiveOrOpenCommand_Click(System.Object sender, System.EventArgs e) { CogDisplay1.StaticGraphics.Clear(); CogDisplay1.InteractiveGraphics.Clear(); cogRecordDisplay1.StaticGraphics.Clear(); cogRecordDisplay1.InteractiveGraphics.Clear(); ROIParams = myAcqFifo.OwnedROIParams; //if (AppGen.Inst.MDImain.frmVisionMain.FrmUnloadCarrier.flagFullTray) //{ ROIParams.SetROIXYWidthHeight(StartXIndx, StartYIndx, MaxXWidth, MaxYWidth); //PatMaxSearchRegion.SetXYWidthHeight(0, 0, 349.08, 296.54); //cogPMAlignTool.SearchRegion = PatMaxSearchRegion; //} //else //{ // // ROIParams.SetROIXYWidthHeight(Convert.ToInt32(StartXIndx * PixFactor), Convert.ToInt32(CurrLineCoord * PixFactor), Convert.ToInt32((xSearchReg + 10) * PixFactor), Convert.ToInt32((ySearchReg + 10) * PixFactor)); // try // { // CurrLineCoord = StartYIndx + (((AppGen.Inst.MainCycle.UnloadCarrierSliceNo - 1) * ySearchReg)); //added 11.06.14 by asaf // //111111 ROIParams.SetROIXYWidthHeight(Convert.ToInt32(StartXIndx * 2.5), Convert.ToInt32(CurrLineCoord), xSearchReg - 1100, ySearchReg + 150); // } // catch (Exception ex) // { // MessageBox.Show(ex.Message, "PatMax Setup Error"); // } //} //"Live Video" & "Stop Live" button when Frame Grabber option is selected. //Using our EnableAll & DisableAll subroutine to force the user stop live //video before doing anything else. if (optImageAcquisitionOptionFrameGrabber.Checked == true) { if (cogRecordDisplay1.LiveDisplayRunning) { cogRecordDisplay1.StopLiveDisplay(); EnableAll(settingLiveVideo); AcqFifoTool.Run(); cogRecordDisplay1.Fit(true); cogToolBlockEditV21.Subject.Inputs["Image"].Value = cogRecordDisplay1.Image; } else if ((AcqFifoTool.Operator != null)) { AcqFifoTool.Run(); cogRecordDisplay1.Fit(true); cogRecordDisplay1.StartLiveDisplay(AcqFifoTool.Operator, false); cogRecordDisplay1.Fit(true); cogToolBlockEditV21.Subject.Inputs["Image"].Value = cogRecordDisplay1.Image; DisableAll(settingLiveVideo); cogRecordDisplay1.Fit(true); } } else { //"Open File" button when image file option is selected //DrawingEnabled is used to simply hide the image while the Fit is performed. //This prevents the image from being diplayed at the initial zoom factor //prior to fit being called. try { DialogResult result = ImageAcquisitionCommonDialog.ShowDialog(); if (result != System.Windows.Forms.DialogResult.Cancel) { ImageFileTool.Operator.Open(ImageAcquisitionCommonDialog.FileName, CogImageFileModeConstants.Read); cogRecordDisplay1.DrawingEnabled = false; ImageFileTool.Run(); cogRecordDisplay1.Fit(true); cogRecordDisplay1.DrawingEnabled = true; } } catch (CogException cogex) { MessageBox.Show("Following Specific Cognex Error Occured:" + cogex.Message); } catch (Exception ex) { MessageBox.Show("Following Error Occured:" + ex.Message); } cogToolBlockEditV21.Subject.Inputs["Image"].Value = cogRecordDisplay1.Image; //!!!!! Neet to solve why pic doesn't get into tool } cogRecordDisplay1.Fit(true); }
public void InitVision() { SettingUp = false; ImageFileTool = CogImageFileEdit1.Subject; ImageFileTool.Ran += ImageFileTool_Ran; //Set reference to CogAcqFifoTool created by Edit Control //The Acq Fifo Edit Control creates its subject when its AutoCreateTool property is True AcqFifoTool = CogAcqFifoEdit1.Subject; AcqFifoTool.Ran += AcqFifoTool_Ran; cogAcqTool = CogAcqFifoEdit1.Subject; cogAcqTool = cogToolBlockEditV21.Subject.Tools["CogAcqFifoTool1"] as CogAcqFifoTool; cogAcqTool.Run(); //Operator will be Nothing if no Frame Grabber is available. Disable the Frame Grabber //option on the "VisionPro Demo" tab if no frame grabber available. if (AcqFifoTool.Operator == null) { optImageAcquisitionOptionFrameGrabber.Enabled = false; } //Initialize the Dialog box for the "Open File" button on the "VisionPro Demo" tab. ImageAcquisitionCommonDialog.Filter = ImageFileTool.Operator.FilterText; ImageAcquisitionCommonDialog.CheckFileExists = true; ImageAcquisitionCommonDialog.ReadOnlyChecked = true; //AutoCreateTool for the PMAlign edit control is False, therefore, we must create //a PMAlign tool and set the subject of the control to reference the new tool. PatMaxTool = new CogPMAlignTool(); PatMaxTool.Changed += PatMaxTool_Changed; CogPMAlignEdit1.Subject = PatMaxTool; //Change the default Train Region to center of a 640x480 image & change the DOFs //so that Skew is not enabled. Note - TrainRegion is of type ICogRegion, therefore, //we must use a CogRectangleAffine reference in order to call CogRectangleAffine //properties. CogRectangleAffine PatMaxTrainRegion = default(CogRectangleAffine); PatMaxTrainRegion = PatMaxTool.Pattern.TrainRegion as CogRectangleAffine; //PatMaxTrainRegion = cogPMAlignTool.Pattern.TrainRegion as CogRectangleAffine; if ((PatMaxTrainRegion != null)) { PatMaxTrainRegion.SetCenterLengthsRotationSkew(320, 240, 100, 100, 0, 0); PatMaxTrainRegion.GraphicDOFEnable = CogRectangleAffineDOFConstants.Position | CogRectangleAffineDOFConstants.Rotation | CogRectangleAffineDOFConstants.Size; } //PatMaxTool.SearchRegion = PatMaxSearchRegion; //PatMaxSearchRegion.SetCenterWidthHeight(320, 240, 640, 480); //PatMaxSearchRegion.GraphicDOFEnable = CogRectangleDOFConstants.Position | CogRectangleDOFConstants.Size; //PatMaxSearchRegion.Interactive = true; numericUpDown1.Value = Convert.ToDecimal(cogPMAlignTool.RunParams.AcceptThreshold); PatMaxTool.RunParams.AcceptThreshold = Convert.ToDouble(numericUpDown1.Value); numericUpDown2.Value = Convert.ToDecimal(cogPMAlignTool.RunParams.ApproximateNumberToFind); PatMaxTool.RunParams.ApproximateNumberToFind = Convert.ToInt32(numericUpDown2.Value); myAcqFifo = AcqFifoTool.Operator; try { myFrameGrabber = cogAcqTool.Operator.FrameGrabber; myAcqFifo = cogAcqTool.Operator; AcqFifoTool.Operator = myAcqFifo; myAcqFifo.OwnedContrastParams.Contrast = cogAcqTool.Operator.OwnedContrastParams.Contrast; myAcqFifo.OwnedBrightnessParams.Brightness = cogAcqTool.Operator.OwnedBrightnessParams.Brightness; brightnessParams = myAcqFifo.OwnedBrightnessParams; contrastParams = myAcqFifo.OwnedContrastParams; } catch (Exception ex) { MessageBox.Show(ex.Message); } if (brightnessParams != null) { brightnessUpDown.Value = Convert.ToDecimal(brightnessParams.Brightness); } if (contrastParams != null) { contrastUpDown.Value = Convert.ToDecimal(contrastParams.Contrast); } try { cogToolBlockEditV21.Subject.Inputs["Image"].Value = cogRecordDisplay1.Image; } catch (Exception ex) { MessageBox.Show("Input image wasn't set"); } }
private void cmdImageAcquisitionLiveOrOpenCommand_Click(System.Object sender, System.EventArgs e) { txtCurrentIndex.Text = (AppGen.Inst.LoadTray.CurrIndex + 1).ToString(); //Clear graphics, assuming a new image will be in the display once user //completes either Live Video or Open File operation, therefore, graphics //will be out of sync. CogDisplay1.StaticGraphics.Clear(); CogDisplay1.InteractiveGraphics.Clear(); cogRecordDisplay1.StaticGraphics.Clear(); cogRecordDisplay1.InteractiveGraphics.Clear(); ROIParams = myAcqFifo.OwnedROIParams; if (AppGen.Inst.MDImain.frmVisionMain.FrmLoadtray.flagFullTray) { //PatMaxSearchRegion.SetXYWidthHeight(0, 0, 349.08, 296.54); //cogPMAlignTool.SearchRegion = PatMaxSearchRegion; PatMaxSearchRegion.SetCenterWidthHeight(StartXIndx, StartYIndx, MaxXWidth + 555, MaxYWidth + 555); cogPMAlignTool.SearchRegion = PatMaxSearchRegion; } else { cogTransform2DLinearN2N = CalibNPointTool.Calibration.GetComputedUncalibratedFromCalibratedTransform() as CogTransform2DLinear; PatMaxSearchRegion.SetCenterWidthHeight(173 + (AppGen.Inst.LoadTray. IndexList[AppGen.Inst.LoadTray.CurrIndex].X_file), (593.7 - AppGen.Inst.LoadTray.IndexList[AppGen.Inst.LoadTray.CurrIndex].Y_file), (xSearchReg), (ySearchReg)); cogPMAlignTool.SearchRegion = PatMaxSearchRegion; //if ((cogPMAlignTool.SearchRegion != null)) //{ // cogRecordDisplay1.StaticGraphics.Add(cogPMAlignTool.SearchRegion as ICogGraphic, "test"); // cogToolBlockEditV21.Subject.Inputs["Image"].Value = cogRecordDisplay1.Image; //} } //"Live Video" & "Stop Live" button when Frame Grabber option is selected. //Using our EnableAll & DisableAll subroutine to force the user stop live //video before doing anything else. if (optImageAcquisitionOptionFrameGrabber.Checked == true) { if (cogRecordDisplay1.LiveDisplayRunning) { cogRecordDisplay1.StopLiveDisplay(); EnableAll(settingLiveVideo); AcqFifoTool.Run(); cogRecordDisplay1.Fit(true); cogToolBlockEditV21.Subject.Inputs["Image"].Value = cogRecordDisplay1.Image; } else if ((AcqFifoTool.Operator != null)) { AcqFifoTool.Run(); cogRecordDisplay1.Fit(true); cogRecordDisplay1.StartLiveDisplay(AcqFifoTool.Operator, false); cogRecordDisplay1.Fit(true); cogToolBlockEditV21.Subject.Inputs["Image"].Value = cogRecordDisplay1.Image; DisableAll(settingLiveVideo); cogRecordDisplay1.Fit(true); } } else { //"Open File" button when image file option is selected //DrawingEnabled is used to simply hide the image while the Fit is performed. //This prevents the image from being diplayed at the initial zoom factor //prior to fit being called. try { DialogResult result = ImageAcquisitionCommonDialog.ShowDialog(); if (result != System.Windows.Forms.DialogResult.Cancel) { ImageFileTool.Operator.Open(ImageAcquisitionCommonDialog.FileName, CogImageFileModeConstants.Read); cogRecordDisplay1.DrawingEnabled = false; ImageFileTool.Run(); cogRecordDisplay1.Fit(true); cogRecordDisplay1.DrawingEnabled = true; } } catch (CogException cogex) { MessageBox.Show("Following Specific Cognex Error Occured:" + cogex.Message); } catch (Exception ex) { MessageBox.Show("Following Error Occured:" + ex.Message); } cogToolBlockEditV21.Subject.Inputs["Image"].Value = cogRecordDisplay1.Image; //!!!!! Need to solve why pic doesn't get into tool } cogRecordDisplay1.Fit(true); }
private void ThreadProcess() { while (true) { if (runStart && processEndStatus) { processEndStatus = false; try { visionResult = new VisionResult(); visionResult.StartTime = DateTime.Now; //程序运行 acqFifoTool.Run(); if (acqFifoTool.OutputImage != null) { visionResult.InputImage = acqFifoTool.OutputImage; processToolBlock.Inputs[0].Value = visionResult.InputImage; processToolBlock.Run(); if (processToolBlock.RunStatus.Result == CogToolResultConstants.Accept) { CogCalibCheckerboardTool checkerboardTool = (CogCalibCheckerboardTool)processToolBlock.Tools[0]; visionResult.OutputImage = checkerboardTool.OutputImage; visionResult.cogRecord = processToolBlock.CreateLastRunRecord(); visionResult.width1 = (double)processToolBlock.Outputs[0].Value; visionResult.width2 = (double)processToolBlock.Outputs[1].Value; visionResult.CoordX = (double)processToolBlock.Outputs[4].Value; visionResult.RunStatus = true; visionResult.RunStatusText = "OK"; //判断是否重复 if (Math.Abs(visionResult.CoordX - lastCoordX) < 0.05) { recurCount++; if (recurCount > 9) { toolStrip1.Invoke(new Action(delegate { tsbStart_Click(null, null); MessageBox.Show(string.Format("检测到产品未移动,次数{0},自动停止运行,请适当挪动产品", recurCount)); })); } } else { recurCount = 0; } lastCoordX = visionResult.CoordX; //判断处理 visionResult.ExamineStatus = true; } else { visionResult.OutputImage = visionResult.InputImage; visionResult.cogRecord = null; visionResult.RunStatusText = "未识别"; visionResult.RunStatus = false; visionResult.width1 = 999; visionResult.width2 = 999; visionResult.CoordX = 0; } //保存原图图片 if (isSaveImage && visionResult.RunStatus) { visionResult.ImagePath = string.Format("{0}\\{2}\\{1}", imageSavePath, visionResult.ExamineStatus ? "OK" : "NG", visionResult.StartTime.ToString("yyMMdd")); if (!Directory.Exists(visionResult.ImagePath)) { Directory.CreateDirectory(visionResult.ImagePath); } CogImageFile cogImageFile = new CogImageFile(); cogImageFile.Open(visionResult.ImagePath + "\\" + visionResult.StartTime.ToString("HHmmssfff") + ".bmp", CogImageFileModeConstants.Write); cogImageFile.Append(visionResult.InputImage); cogImageFile.Close(); } crdResultImage.Invoke(new Action(delegate { crdResultImage.InteractiveGraphics.Clear(); crdResultImage.StaticGraphics.Clear(); crdResultImage.Image = null; crdResultImage.Image = visionResult.OutputImage; crdResultImage.Record = visionResult.cogRecord; lblRunStatus.Text = visionResult.RunStatusText; lblRunStatus.ForeColor = visionResult.RunStatus ? Color.Green : Color.Red; lblWidth1.Text = visionResult.width1.ToString("0.000"); lblWidth2.Text = visionResult.width2.ToString("0.000"); //保存画线图 if (isSaveImage && visionResult.RunStatus && !visionResult.ExamineStatus) { Bitmap crdImage = (Bitmap)crdResultImage.CreateContentBitmap(Cognex.VisionPro.Display.CogDisplayContentBitmapConstants.Image); crdImage.Save(visionResult.ImagePath + "\\crd_" + visionResult.StartTime.ToString("HHmmssfff") + ".jpeg", ImageFormat.Jpeg); } })); } else { CognexAreaCamera_CameraStatusChange(1, false); } } catch (Exception ex) { MessageBox.Show("图片处理异常:" + ex); tsbStart_Click(null, null); } processEndStatus = true; } if (!cameraStatus) { acqFifoTool.Run(); if (acqFifoTool.RunStatus.Result == CogToolResultConstants.Accept) { CognexAreaCamera_CameraStatusChange(1, true); } } Thread.Sleep(1); } }
public void Run(ref ICogImage cogImage, int nFlipRotation) { // 2013.05.03 try { m_nAcqCount++; if (nFlipRotation == 0) { //Acquire(cogDisplay); // 2015.04.08 m_bRan = false; m_cogAcqFifoTool.Run(); // 2015.04.08 WaitRanEvent(); if (m_cogAcqFifoTool.OutputImage != null) { cogImage = m_cogAcqFifoTool.OutputImage; #if !_USE_TRIGGER_ACQ // 2017.11.16 by kdi. m_cogImageTrigger = cogImage; AUtil.PostMessage(m_hMain, _WM_ACQFIFO_COMPLETE, m_nPoint, m_nSection); #endif } #if !_USE_TRIGGER_ACQ else { cogImage = null; //var property = m_cogAcqFifoTool.RunStatus.Exception.GetType().GetProperty("HResult", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); //var value = property.GetValue(m_cogAcqFifoTool.RunStatus.Exception, null); int nHResult = System.Runtime.InteropServices.Marshal.GetHRForException(m_cogAcqFifoTool.RunStatus.Exception); //if (m_cogAcqFifoTool.RunStatus.Message.Contains(_CONST_CAMERA_DISCONNECTION_MESSAGE) == true || // m_cogAcqFifoTool.RunStatus.Message.Contains(_CONST_CAMERA_DISCONNECTION_MESSAGE2) == true || // m_cogAcqFifoTool.RunStatus.Message.Contains(_CONST_CAMERA_DISCONNECTION_MESSAGE3) == true // ) //** to do: // 1. 네트워크 단절 에러와 일반 예외 값이 동일한지 확인 필요 // 동일한 값을 가진다면, 이 조건을 적용할 수 없음 if ((UInt32)nHResult == (UInt32)0x80131600) // Application Exception { // ip address System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse(m_cogAcqFifoTool.Operator.FrameGrabber.OwnedGigEAccess.CurrentIPAddress); int intAddress = BitConverter.ToInt32(ipaddress.GetAddressBytes(), 0); //AUtil.PostMessage(m_hMain, ASDef._WM_CAMERA_IS_DISCONNECTED, m_nPoint, intAddress); AUtil.PostMessage(m_hMain, clsCamera._WM_CAMERA_IS_DISCONNECTED, m_nPoint, intAddress); } string strMsg = ""; strMsg = string.Format("AAcqFifo.Run: Error. {0}", m_cogAcqFifoTool.RunStatus.Message); m_strError = strMsg; AVisionProBuild.WriteLogFile(strMsg, ".AcqFifo.err.txt"); } #endif return; } // 2015.04.08 m_bRan = false; //DateTime Now = DateTime.Now; m_cogAcqFifoTool.Run(); // 2015.04.08 WaitRanEvent(); //TimeSpan span = DateTime.Now - Now; if (m_cogAcqFifoTool.OutputImage != null) { // 2011.07.29 CogIPOneImageFlipRotate cogIPOneImageFlipRotate = new CogIPOneImageFlipRotate(); cogIPOneImageFlipRotate.OperationInPixelSpace = (CogIPOneImageFlipRotateOperationConstants)nFlipRotation; // 2012.04.25 ICogImage cogImageFR = cogIPOneImageFlipRotate.Execute(m_cogAcqFifoTool.OutputImage, CogRegionModeConstants.PixelAlignedBoundingBox, null); Bitmap Bmp = cogImageFR.ToBitmap(); if ((Bmp.Flags & (16 | 32 | 64 | 128 | 256)) != 0) { cogImage = new CogImage24PlanarColor(Bmp); } else { cogImage = new CogImage8Grey(Bmp); } #if !_USE_TRIGGER_ACQ // 2017.11.16 by kdi. m_cogImageTrigger = cogImage; AUtil.PostMessage(m_hMain, _WM_ACQFIFO_COMPLETE, m_nPoint, m_nSection); #endif // 2012.06.06 if (Bmp != null) { Bmp.Dispose(); Bmp = null; } } #if !_USE_TRIGGER_ACQ else { cogImage = null; int nHResult = System.Runtime.InteropServices.Marshal.GetHRForException(m_cogAcqFifoTool.RunStatus.Exception); //if (m_cogAcqFifoTool.RunStatus.Message.Contains(_CONST_CAMERA_DISCONNECTION_MESSAGE) == true || // m_cogAcqFifoTool.RunStatus.Message.Contains(_CONST_CAMERA_DISCONNECTION_MESSAGE2) == true || // m_cogAcqFifoTool.RunStatus.Message.Contains(_CONST_CAMERA_DISCONNECTION_MESSAGE3) == true // ) //** to do: // 1. 네트워크 단절 에러와 일반 예외 값이 동일한지 확인 필요 // 동일한 값을 가진다면, 이 조건을 적용할 수 없음 if ((UInt32)nHResult == (UInt32)0x80131600) // Application Exception { // 2018.04.09 //AUtil.PostMessage(m_hMain, ASDef._WM_CAMERA_IS_DISCONNECTED, m_nPoint, 0); AUtil.PostMessage(m_hMain, clsCamera._WM_CAMERA_IS_DISCONNECTED, m_nPoint, 0); } string strMsg = ""; strMsg = string.Format("AAcqFifo.Run: Error. {0}", m_cogAcqFifoTool.RunStatus.Message); m_strError = strMsg; AVisionProBuild.WriteLogFile(strMsg, ".AcqFifo.err.txt"); } #endif /* * ICogImage cogImageFR = cogIPOneImageFlipRotate.Execute(m_cogAcqFifoTool.OutputImage, CogRegionModeConstants.PixelAlignedBoundingBox, null); * * lock (m_cogImageFile) * { * string strFName = "c:\\" + AVisionProBuild.MakeName("Flip", DateTime.Now) + ".bmp"; * m_cogImageFile.Open(strFName, CogImageFileModeConstants.Write); * m_cogImageFile.Append(cogImageFR); * m_cogImageFile.Close(); * m_cogImageFile.Open(strFName, CogImageFileModeConstants.Read); * cogImage = m_cogImageFile[0]; * m_cogImageFile.Close(); * File.Delete(strFName); * } */ } catch (CogException ex) { cogImage = null; m_cogImageTrigger = cogImage; #if !_USE_TRIGGER_ACQ if (ex.Message.Contains(_CONST_CAMERA_DISCONNECTION_MESSAGE) == true || ex.Message.Contains(_CONST_CAMERA_DISCONNECTION_MESSAGE2) == true) { // 2018.04.09 //AUtil.PostMessage(m_hMain, ASDef._WM_CAMERA_IS_DISCONNECTED, m_nPoint, 0); AUtil.PostMessage(m_hMain, clsCamera._WM_CAMERA_IS_DISCONNECTED, m_nPoint, 0); } string strMsg = ""; strMsg = string.Format("AAcqFifo.Run: CogException. {0}", ex.Message); m_strError = strMsg; AVisionProBuild.WriteLogFile(strMsg, ".AcqFifo.err.txt"); #endif } catch { cogImage = null; } }