public Boolean LoadFromVPPFile(string FileName, CogRecordDisplay mCogRecordDisplay)//檔案參數載入 { string ProcID = System.Reflection.MethodInfo.GetCurrentMethod().Name.ToString(); string TempFileName = (string)FileName; try { //從CogTool裡面讀出來 string strFolderPath = @"D:\VPS_File\Product\PMA_Tool\" + @FileName + @"\"; CogToolBlock ToolBlock1 = new CogToolBlock(); FileName = strFolderPath + FileName + "_PMA.vpp"; ToolBlock1 = (CogToolBlock)CogSerializer.LoadObjectFromFile(FileName);//開啟ToolBlock vpp檔案 //依序載入 mPMA_Tool = (CogPMAlignTool)ToolBlock1.Tools[TempFileName + "_PMA_Tool_"]; this.ROI_Create(mCogRecordDisplay); SaveLog.Msg_("Data of PMA_Tool Loaded : " + @FileName); ToolBlock1 = null; return(true); } catch (Exception ex) { SaveLog.Msg_("Load PMA_Tool Data Failed : " + ModularID + ":\r\n" + ProcID + ":\r\n" + ex.ToString()); return(false); } }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //생성 : //수정 : //목적 : Load //설명 : ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public override bool HLLoadRecipe(string strRecipePath, string strRecipeName) { bool bReturn = false; do { string strFileName = strRecipePath + "\\" + strRecipeName + "\\" + string.Format("PMAlign{0}.VPP", m_iIndex); try { m_objPMAlignTool = CogSerializer.LoadObjectFromFile(strFileName) as CogPMAlignTool; // 처음이 느려서 한번찍어줌 //m_objPMAlignTool.Run(); //m_objFixtureTool.Run(); // m_objROI = ( CogRectangleAffine )m_objPMAlignTool.SearchRegion; // m_objTrainRegion = ( CogRectangleAffine )m_objPMAlignTool.Pattern.TrainRegion; // m_objTrainedImage = ( CogImage8Grey )m_objPMAlignTool.Pattern.TrainImage; // // m_objROI.Color = CogColorConstants.Blue; // m_objTrainRegion.Color = CogColorConstants.Red; m_objTrainRegion.LineStyle = CogGraphicLineStyleConstants.Dot; } catch (System.Exception ex) { Trace.WriteLine(ex.Message + " -> " + ex.StackTrace); MakeErrorMessage("HLLoadRecipe", 5203, ex.Message); break; } bReturn = true; } while(false); return(bReturn); }
public Form1() { InitializeComponent(); PMTool = new CogPMAlignTool(); //툴생성 cogPMAlignEditor.Subject = PMTool; //툴 확인용 에디터 }
public InspectionPattern() { PatternProc = new CogPMAlignTool(); PatternProc.Pattern.TrainAlgorithm = CogPMAlignTrainAlgorithmConstants.PatQuick; PatternProc.RunParams.ContrastThreshold = 5; PatternResults = new CogPMAlignResults(); }
/// <summary> /// Handles a click to the Retrain Button, when clicked the PMAlignTool /// will retrain its pattern. The new trained pattern will reflect any /// changes made to the train image record in the CogRecordDisplay. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RetrainButton_Click(object sender, EventArgs e) { CogToolGroup myTG = myJob.VisionTool as CogToolGroup; CogPMAlignTool myPMTool = myTG.Tools["CogPMAlignTool1"] as CogPMAlignTool; myPMTool.Pattern.Train(); }
/// <summary> /// This handles a click to the Show Train Image button. /// It allows the user to view train image record the pattern was /// trained off of and also enable the Retrain button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ShowTrainCheckBox_CheckedChanged( object sender, EventArgs e) { if (this.ShowTrainCheckBox.Checked) { RunOnceButton.Enabled = false; RunContCheckBox.Enabled = false; RetrainButton.Enabled = true; CogToolGroup myTG = myJob.VisionTool as CogToolGroup; CogPMAlignTool myPMTool = myTG.Tools["CogPMAlignTool1"] as CogPMAlignTool; Cognex.VisionPro.ICogRecord tmpRecord; tmpRecord = myPMTool.CreateCurrentRecord(); tmpRecord = tmpRecord.SubRecords["TrainImage"]; cogRecordDisplay1.Record = tmpRecord; cogRecordDisplay1.Fit(true); RunStatusTextBox.Text = ""; } else { RunOnceButton.Enabled = true; RunContCheckBox.Enabled = true; RetrainButton.Enabled = false; cogRecordDisplay1.Record = null; } }
public PatternRecognizer() { InitializeComponent(); _PMAlignTool = new CogPMAlignTool(); this.cogDisplayToolbarV21.Display = this.cogDisplayTrain; this.cogDisplayToolbarV22.Display = this.cogDisplayRecognize; }
public static void RunOnce() { _formMain.Invoke((MethodInvoker)(() => { _formMain.btnReset.Enabled = true; })); _block.Run(); _formMain.Invoke((MethodInvoker)(() => { _formMain.cogRecordDisplay1.Record = _block.CreateLastRunRecord().SubRecords["CogIPOneImageTool1.OutputImage"]; })); string runResult; if (CogToolResultConstants.Accept == _block.RunStatus.Result) { runResult = resultOK; } else { CogPMAlignTool pma = (CogPMAlignTool)_block.Tools["主定位"]; runResult = pma.Results.Count == 0 ? resultNoProduct : resultNG; } HandleResult(runResult); Y1 = (double)_block.Outputs["Y1"].Value; Y2 = (double)_block.Outputs["Y2"].Value; X1 = (double)_block.Outputs["X1"].Value; X2 = (double)_block.Outputs["X2"].Value; angle = (double)_block.Outputs["Angle"].Value; angleUncalib = (double)_block.Outputs["AngleUncalib"].Value; X1_pixel = (double)_block.Outputs["X1_pixel"].Value; X2_pixel = (double)_block.Outputs["X2_pixel"].Value; Y1_pixel = (double)_block.Outputs["Y1_pixel"].Value; Y2_pixel = (double)_block.Outputs["Y2_pixel"].Value; lock (_formMain._chartFormMarshaller.mu_currentIndex) { SaveLog(_formMain._chartFormMarshaller.currentIndex, runResult); _formMain.showCurrentIndex(_formMain._chartFormMarshaller.currentIndex); _formMain._chartFormMarshaller.incrementItemCount(); noErrorInThisRound &= (_block.RunStatus.Result != CogToolResultConstants.Error); _formMain._chartFormMarshaller.collectData(X1, X2, Y1, Y2, angle); if (_formMain._chartFormMarshaller.RoundEndReached()) { // if no error occur within a round, update summery and clear. Otherwise, just clear. _formMain._chartFormMarshaller.resetItemCount(); if (noErrorInThisRound) { _formMain._chartFormMarshaller.GenerateSummery(); } _formMain._chartFormMarshaller.clearDataBuffers(); // reset this flag for next round noErrorInThisRound = true; } } }
private void AssignToolResult(CogPMAlignTool cogPMAlign) { CogPMAlignResults cogPMAlignResults = cogPMAlign.Results; if (cogPMAlignResults != null) { AssignToolResult(cogPMAlign.Name, cogPMAlignResults); } }
private void button2_Click(object sender, EventArgs e) { // CogSerializer.SaveObjectToFile(toolBlock,@"C:\PROJECTS\Stahli.Net\Bin\Debug\CognexStahli\Camera1.vpp"); CogSerializer.SaveObjectToFile(toolBlock, System.IO.Directory.GetCurrentDirectory() + "\\CognexStahli\\Camera1.vpp"); cogAcqTool = cogToolBlockEditV21.Subject.Tools["CogAcqFifoTool1"] as CogAcqFifoTool; calbCheckerBoard = cogToolBlockEditV21.Subject.Tools["CogCalibCheckerboardTool1"] as CogCalibCheckerboardTool; CalibNPointTool = cogToolBlockEditV21.Subject.Tools["CogCalibNPointToNPointTool1"] as CogCalibNPointToNPointTool; cogPMAlignTool = cogToolBlockEditV21.Subject.Tools["CogPMAlignTool1"] as CogPMAlignTool; cogPMAlignTool.InputImage = CalibNPointTool.OutputImage as CogImage8Grey; }
public FrmLoadTray() { visionActionDelegate = new VisionActionDelegate(VisionActionDelegateFunc); InitializeComponent(); //Add any initialization after the InitializeComponent() call cogToolBlockEditV21.LocalDisplayVisible = false; mIFTool = new CogImageFileTool(); //mIFTool.Operator.Open(Environment.GetEnvironmentVariable("VPRO_ROOT") + @"\images\coins.idb", CogImageFileModeConstants.Read); mAcqTool = new CogAcqFifoTool(); toolBlock = cogToolBlockEditV21.Subject; try { // toolBlock = CogSerializer.LoadObjectFromFile(@"C:\PROJECTS\Stahli.Net\Bin\Debug\CognexStahli\Camera1.vpp") as CogToolBlock; //Need to upload insernt name as given by asaf toolBlock = CogSerializer.LoadObjectFromFile(System.IO.Directory.GetCurrentDirectory() + "\\CognexStahli\\Camera1.vpp") as CogToolBlock; //Need to upload insernt name as given by asaf //if it is new insert, upload a defult } catch (Exception ex) { MessageBox.Show("Tool block is error"); } cogToolBlockEditV21.Subject = toolBlock; cogToolBlockEditV21.Subject.Ran += new EventHandler(Subject_Ran); cogToolBlockEditV21.SubjectChanged += new EventHandler(cogToolBlockEditV21_SubjectChanged); foreach (ICogTool tool in toolBlock.Tools) { calbCheckerBoard = tool as CogCalibCheckerboardTool; if (calbCheckerBoard != null) { break; } } foreach (ICogTool tool in toolBlock.Tools) { CalibNPointTool = tool as CogCalibNPointToNPointTool; if (CalibNPointTool != null) { break; } } foreach (ICogTool tool in toolBlock.Tools) { cogPMAlignTool = tool as CogPMAlignTool; if (cogPMAlignTool != null) { break; } } loadOrderDataDelegate = new LoadOrderDataDelegate(LoadOrderDataDelegateFunc); // LoadPatternFromFile(); //13.07.15 (Ziv) }
//툴 자체를 불러오는 방법 private void button1_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog() { Filter = "vpp|*.vpp" }; if (dialog.ShowDialog() == DialogResult.OK) { PMTool = CogSerializer.LoadObjectFromFile(dialog.FileName) as CogPMAlignTool; cogPMAlignEdit.Subject = PMTool; } }
public void Subject_Ran(object sender, EventArgs e) //Run tool { cogAcqTool = cogToolBlockEditV21.Subject.Tools["CogAcqFifoTool1"] as CogAcqFifoTool; calbCheckerBoard.InputImage = cogToolBlockEditV21.Subject.Inputs["Image"].Value as CogImage8Grey; calbCheckerBoard = cogToolBlockEditV21.Subject.Tools["CogCalibCheckerboardTool1"] as CogCalibCheckerboardTool; calbCheckerBoard.Run(); CalibNPointTool = cogToolBlockEditV21.Subject.Tools["CogCalibNPointToNPointTool1"] as CogCalibNPointToNPointTool; CalibNPointTool.InputImage = calbCheckerBoard.OutputImage; cogPMAlignTool = cogToolBlockEditV21.Subject.Tools["CogPMAlignTool1"] as CogPMAlignTool; cogPMAlignTool.InputImage = CalibNPointTool.OutputImage as CogImage8Grey; cogRecordDisplay1.Image = cogPMAlignTool.InputImage; cogPMAlignTool.Run(); cogRecordDisplay1.Record = cogPMAlignTool.CreateLastRunRecord(); cogRecordDisplay1.Fit(true); if (dataGridView1.Visible == false) { dataGridView1.Visible = true; } dataGridView1.Rows.Clear(); TrayIndexData TIS; AppGen.Inst.UnLoadCarrier.CurrIndex = 0; AppGen.Inst.UnLoadCarrier.IndexList.Clear(); try { for (int i = 0; i < cogPMAlignTool.Results.Count; i++) { TIS = new TrayIndexData(); dataGridView1.Rows.Add(); dataGridView1[0, i].Value = cogPMAlignTool.Results[i].ID.ToString(); dataGridView1[1, i].Value = cogPMAlignTool.Results[i].Score.ToString(); dataGridView1[2, i].Value = cogPMAlignTool.Results[i].GetPose().Rotation *(180 / Math.PI); dataGridView1[3, i].Value = cogPMAlignTool.Results[i].GetPose().TranslationX; dataGridView1[4, i].Value = cogPMAlignTool.Results[i].GetPose().TranslationY; TIS.X_VisRes = cogPMAlignTool.Results[i].GetPose().TranslationX; TIS.Y_VisRes = cogPMAlignTool.Results[i].GetPose().TranslationY; TIS.Angle_VisRes = cogPMAlignTool.Results[i].GetPose().Rotation *(180 / Math.PI); AppGen.Inst.UnLoadCarrier.IndexList.Add(TIS); } txtPatMaxScoreValue.Text = cogPMAlignTool.Results.Count.ToString(); } catch (Exception) { MessageBox.Show("No Input Image available for setup.", "PatMax Setup Error"); } }
//模板匹配工具的结果获取函数 private bool getPMAToolResult(out double[] item_x, out double[] item_y, out int item_number, int toolNum) { CogPMAlignTool PMATool = null; switch (toolNum) { case 1: PMATool = pmaTool_1; break; case 2: PMATool = pmaTool_2; break; case 3: PMATool = pmaTool_3; break; default: item_x = new double[0]; item_y = new double[0]; item_number = 0; return(false); break; } item_number = PMATool.Results.Count; if (item_number <= 0) { item_x = new double[0]; item_y = new double[0]; return(false); } item_x = new double[item_number]; item_y = new double[item_number]; for (int i = 0; i < item_number; i++) { item_x[i] = PMATool.Results[i].GetPose().TranslationX; item_y[i] = PMATool.Results[i].GetPose().TranslationY; } return(true); }
public InspectionAutoPattern() { HistogramProc = new CogHistogram(); HistogramResult = new CogHistogramResult(); OneImageProc = new CogIPOneImageTool(); BlobProc = new CogBlob(); BlobResults = new CogBlobResults(); BlobResult = new CogBlobResult(); PMAlignProc = new CogPMAlignTool(); PMAlignProc.Pattern.TrainAlgorithm = CogPMAlignTrainAlgorithmConstants.PatMax; PMAlignResult = new CogPMAlignResult(); }
public bool RunTool_Pattern(int cameraModule) //no need { bool runStatus = true; String colResult; CogToolResultConstants toolColResult; int i; if (this.cogToolRun[cameraModule] != null) { //configure the vision tool this.cogToolRun[cameraModule].Inputs["InputImage"].Value = grabImage[cameraModule] as CogImage8Grey; this.cogToolRun[cameraModule].Inputs["SaveImage"].Value = true; this.cogToolRun[cameraModule].Inputs["ImageDirectoryPath"].Value = "c:\\Seagate\\vision\\"; this.cogToolRun[cameraModule].Run(); ICogRunStatus cogStatus = this.cogToolRun[cameraModule].RunStatus; if (cogStatus.Result == CogToolResultConstants.Error) { runStatus = false; // error default all to invalid for (i = 0; i < MAX_RESULT; i++) { this.inspectResult[cameraModule, i] = HGAStatus.Unknown; } } else { double[] score = { 0, 0, 0, 0, 0, 0 }; double[] centerofmass_X = { 0, 0, 0, 0, 0, 0 }; cogpmaligntool = (CogPMAlignTool)this.cogToolRun[cameraModule].Tools["PatternTool"]; CogPMAlignResults resultcollection = cogpmaligntool.Results; for (int x = 0; x < resultcollection.Count; x++) { score[x] = resultcollection[x].Score; centerofmass_X[x] = resultcollection[x].GetPose().TranslationX; } } } else { runStatus = false; } return(runStatus); }
public bool unLoad() { string ProcID = System.Reflection.MethodInfo.GetCurrentMethod().Name.ToString(); try { mPMA_Tool = null; mPMA_ROI = null; return(true); } catch (Exception ex) { SaveLog.Msg_("PMA_Tool unLoad Failed : " + ModularID + ":\r\n" + ProcID + ":\r\n" + ex.ToString()); return(false); } }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //생성 : //수정 : //목적 : 초기화 //설명 : ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public override bool HLInitialize(HLDevice.Abstract.CVisionLibraryAbstract.CInitializeParameter objInitializeParameter) { bool bReturn = false; do { m_objInitializeParameter = (HLDevice.Abstract.CVisionLibraryAbstract.CInitializeParameter)objInitializeParameter.Clone(); m_objGraphics = new ICogRecord[( int )Abstract.CVisionLibraryAbstract.CResultData.enumInspectPosition.INSPECT_POSITION_FINAL]; // for( int iLoopCount = 0; iLoopCount < ( int )Abstract.CVisionLibraryAbstract.CResultData.enumInspectPosition.INSPECT_POSITION_FINAL; iLoopCount++ ) // m_objGraphics[ iLoopCount ] = new ICogRecord(); m_objPMAlignTool = new CogPMAlignTool(); m_objFixtureTool = new CogFixtureTool(); m_iIndex = m_objInitializeParameter.iIndex; m_objInitializeParameter = ( CInitializeParameter )objInitializeParameter.Clone(); HLLoadRecipe(m_objInitializeParameter.strRecipePath, m_objInitializeParameter.strRecipeName); bReturn = true; } while(false); return(bReturn); }
public BlockRunner(ResultMode resultMode = ResultMode.OK_NG_ProductMissing_Error, Func <ICogTool, bool> productMissingCondition = null) { _resultMode = resultMode; // If no productMissingCondition is given, set a default one if (productMissingCondition == null) { _productMissingCondition = block => { var toolBlock = (CogToolBlock)block; CogPMAlignTool pmAlignTool = null; foreach (ICogTool tool in toolBlock.Tools) { if (!(tool is CogPMAlignTool alignTool)) { continue; } pmAlignTool = alignTool; break; } if (pmAlignTool == null) { throw new NullReferenceException( "Make sure there is a PMAlignTool in your block for telling whether the product is missing"); } return(pmAlignTool.Results.Count == 0); } } ; else { _productMissingCondition = productMissingCondition; } }
//#region "when the tool group is run" // The GroupRun function is called when the tool group is run. The default // implementation provided here is equivalent to the normal behavior of the // tool group. Modifying this function will allow you to change the behavior // when the tool group is run. public override bool GroupRun(ref string message, ref CogToolResultConstants result) { // To let the execution stop in this script when a debugger is attached, uncomment the following lines. #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Debugger.Break(); } #endif histCntr = 0; CogGraphicLabel myBaslerLabel = new CogGraphicLabel(); CogGraphicLabel myAreaLabel = new CogGraphicLabel(); CogGraphicLabel myFlirLabel = new CogGraphicLabel(); CogPointMarker baslerMarker; //= new CogPointMarker(); double blobAngle = 0; double blobAngleRadians = 0; //Get references to the tools //CogBlobTool blobBaslerTool = (CogBlobTool) toolGroup.Tools["FindWrappersInBasler"]; CogBlobTool blobFlirTool = (CogBlobTool)toolGroup.Tools["PopsicleBlobFinder"]; CogPMAlignTool patternBaslerTool = (CogPMAlignTool)toolGroup.Tools["FindWrapperPatterns"]; CogHistogramTool popsicleHistTool = (CogHistogramTool)toolGroup.Tools["PopsicleHistogramTool"]; CogCaliperTool xDistEdgeFinder = (CogCaliperTool)toolGroup.Tools["CogCaliperTool_XDist"]; //Define the regions CogRectangleAffine popsicleRegion = blobFlirTool.Region as CogRectangleAffine; CogRectangleAffine histogramRegion = blobFlirTool.Region as CogRectangleAffine; //Define the fonts System.Drawing.Font myBaslerFont = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); System.Drawing.Font myAreaFont = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); System.Drawing.Font myFlirFont = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); //Reset stats angleFailures = 0; thermalFailures = 0; //Reset any labels and rectangles from previous runs BaslerLabels.Clear(); FlirLabels.Clear(); FlirRectangles.Clear(); AreaLabel.Clear(); //***** Run the tools to perform the search in the basler image ***** //Update status strings for Visual Studio. Do not popup a message box for errors, this causes confusion with the operators. toolGroup.SetScriptTerminalData("BaslerStatus", "OK"); toolGroup.SetScriptTerminalData("FlirStatus", "OK"); bool acquireException = false; try { //Aquire an image from the Basler, send Exception to Visual Studio toolGroup.RunTool(toolGroup.Tools["BaslerAcqFifo"], ref message, ref result); } catch (Exception ex) { toolGroup.SetScriptTerminalData("BaslerStatus", "Script Error: " + ex.Message + " Check power connections and communication cables."); acquireException = true; } try { //Aquire an image from the Flir, send Exception to Visual Studio toolGroup.RunTool(toolGroup.Tools["FlirAcqFifo"], ref message, ref result); } catch (Exception ex) { toolGroup.SetScriptTerminalData("FlirStatus", "Script Error: " + ex.Message + " Check power connections and communication cables."); acquireException = true; } if (acquireException) { return(false); } try { // Scale the Flir image to zoom in to smaller temperature range toolGroup.RunTool(toolGroup.Tools["ScaleFlirImagePmap"], ref message, ref result); } catch (Exception ex) { toolGroup.SetScriptTerminalData("FlirStatus", "Script Error: " + ex.Message + " Failed: ScaleFlirImagePmap"); return(false); } try { // Transform the images to calibrated space toolGroup.RunTool(toolGroup.Tools["CalBasler"], ref message, ref result); toolGroup.RunTool(toolGroup.Tools["CalFlir"], ref message, ref result); } catch (Exception ex) { //MessageBox.Show("Calibration tool error: " + ex.Message, "Script Exception"); toolGroup.SetScriptTerminalData("BaslerStatus", "Script Error: " + ex.Message + " Failed: CalBasler"); toolGroup.SetScriptTerminalData("FlirStatus", "Script Error: " + ex.Message + " Failed: CalFlir"); return(false); } try { toolGroup.RunTool(toolGroup.Tools["CogPixelMapBasler"], ref message, ref result); } catch (Exception ex) { toolGroup.SetScriptTerminalData("BaslerStatus", "Script Error: " + ex.Message + " Failed: CogPixelMapBasler"); return(false); } try { // Run the Flir hist tool toolGroup.RunTool(toolGroup.Tools["PopsicleHistogramTool"], ref message, ref result); } catch (Exception ex) { toolGroup.SetScriptTerminalData("FlirStatus", "Script Error: " + ex.Message + " Failed: PopsicleHistogramTool"); return(false); } try { // Run the blob tool and get a reference to the results. toolGroup.RunTool(patternBaslerTool, ref message, ref result); } catch (Exception ex) { toolGroup.SetScriptTerminalData("BaslerStatus", "Script Error: " + ex.Message + " Failed: Basler patternBaslerTool"); return(false); } CogPMAlignResults patternResults = patternBaslerTool.Results; // Clear list before starting loop malBlobPoses.Clear(); Crosshairs.Clear(); // Get group input terminal data try { disableHist = (bool)toolGroup.GetScriptTerminalData("DisableHistogramInspection"); minPickAngle = (double)toolGroup.GetScriptTerminalData("MinPickAngle"); maxPickAngle = (double)toolGroup.GetScriptTerminalData("MaxPickAngle"); minPopsicleHistCount = (double)toolGroup.GetScriptTerminalData("MinPopsicleHistCount"); VisStudio_Running = (bool)toolGroup.GetScriptTerminalData("VS_Running"); showArea = (bool)toolGroup.GetScriptTerminalData("ShowArea"); showHist = (bool)toolGroup.GetScriptTerminalData("ShowHistCount"); visSideXLength = (double)toolGroup.GetScriptTerminalData("VisSideXLength"); visSideYLength = (double)toolGroup.GetScriptTerminalData("VisSideYLength"); visXwindowMin = (double)toolGroup.GetScriptTerminalData("VisXwindowMin"); visXwindowMax = (double)toolGroup.GetScriptTerminalData("VisXwindowMax"); visFlirRegionXadj = (double)toolGroup.GetScriptTerminalData("VisFlirRegionXadj"); visFlirRegionYadj = (double)toolGroup.GetScriptTerminalData("VisFlirRegionYadj"); } catch (Exception ex) { //MessageBox.Show("Getting terminal data exception: ", ex.Message); toolGroup.SetScriptTerminalData("BaslerStatus", "Getting script data: " + ex.Message); } // Set run variables for manual triggering if (!VisStudio_Running) { minPopsicleHistCount = 0; minPickAngle = -20; maxPickAngle = 20; showArea = true; showHist = true; visSideXLength = 200; visSideYLength = 70; visXwindowMin = -2000; visXwindowMax = 2000; visFlirRegionXadj = 0; visFlirRegionYadj = 0; } // *************************************** // ******** Process the patterns ********* // *************************************** try { foreach (CogPMAlignResult patternResult in patternResults) { // Set the transform for collections CogTransform2DLinear l2d = new CogTransform2DLinear(); l2d.TranslationX = patternResult.GetPose().TranslationX; l2d.TranslationY = patternResult.GetPose().TranslationY; l2d.Rotation = patternResult.GetPose().Rotation; blobAngleRadians = patternResult.GetPose().Rotation; // Check for clipped Patterns if ((l2d.TranslationX < visXwindowMin) || (l2d.TranslationX > visXwindowMax)) { //MessageBox.Show("Fail"); continue; } // Setup the Caliper tool xDistEdgeFinder.Region.CenterX = l2d.TranslationX; xDistEdgeFinder.Region.CenterY = l2d.TranslationY; xDistEdgeFinder.Region.Rotation = l2d.Rotation; // Run the Caliper tool and get a reference to the results. toolGroup.RunTool(xDistEdgeFinder, ref message, ref result); //MessageBox.Show("Caliper result: "+xDistEdgeFinder.Results[0].PositionX.ToString()); //MessageBox.Show("Diff: "+Math.Abs(xDistEdgeFinder.Results[0].PositionX - l2d.TranslationX).ToString()); //MessageBox.Show("Caliper width: "+xDistEdgeFinder.Results[0].Width.ToString()); // Check for low width (end to end product that matched) if (xDistEdgeFinder.Results[0].Width < 150) { continue; } // Adjust the X based on Caliper tool result l2d.TranslationX = xDistEdgeFinder.Results[0].PositionX; // Crosshair setup for the Basler baslerMarker = new CogPointMarker(); baslerMarker.X = l2d.TranslationX; baslerMarker.Y = l2d.TranslationY; baslerMarker.Color = CogColorConstants.Green; baslerMarker.GraphicType = CogPointMarkerGraphicTypeConstants.Crosshair; // Flir region CogRectangleAffine myFlirRegion = new CogRectangleAffine(); myFlirRegion.CenterX = l2d.TranslationX + visFlirRegionXadj; myFlirRegion.CenterY = l2d.TranslationY + visFlirRegionYadj; myFlirRegion.Rotation = l2d.Rotation; myFlirRegion.SideXLength = (double)visSideXLength; myFlirRegion.SideYLength = (double)visSideYLength; blobFlirTool.Region = myFlirRegion; toolGroup.RunTool(blobFlirTool, ref message, ref result); popsicleHistTool.Region = myFlirRegion; toolGroup.RunTool(popsicleHistTool, ref message, ref result); // Get the histogram results from the bin binHist = popsicleHistTool.Result.GetHistogram(); // Count total pixels histCntr = 1; for (int i = 0; i < blobFlirTool.RunParams.SegmentationParams.HardFixedThreshold; i++) { histCntr = histCntr + binHist[i]; } myBaslerLabel = new CogGraphicLabel(); myBaslerLabel.SetXYText(0, 0, ""); myAreaLabel = new CogGraphicLabel(); myFlirLabel = new CogGraphicLabel(); myBaslerLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); myAreaLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); myFlirLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); myFlirRegion.Visible = true; myBaslerLabel.Alignment = CogGraphicLabelAlignmentConstants.BaselineCenter; myFlirLabel.Alignment = CogGraphicLabelAlignmentConstants.BaselineCenter; myAreaLabel.Alignment = CogGraphicLabelAlignmentConstants.BaselineCenter; // Decide to add the popsicle blob to the collection list if ((histCntr < minPopsicleHistCount) && (!disableHist)) { myBaslerLabel.Color = CogColorConstants.Red; myFlirRegion.Color = CogColorConstants.Red; // Show the hist count in the Flir image myFlirLabel.Color = CogColorConstants.Red; if (showHist) { myFlirLabel.SetXYText(patternResult.GetPose().TranslationX, patternResult.GetPose().TranslationY, "Size: " + histCntr.ToString()); } thermalFailures++; } else { myBaslerLabel.Color = CogColorConstants.Green; myAreaLabel.Color = CogColorConstants.Green; // If histogram check is disabled, draw rectangle in yellow, else green if (disableHist) { myFlirRegion.Color = CogColorConstants.Yellow; } else { if ((histCntr > 1) && (patternResult.Score >= patternBaslerTool.RunParams.AcceptThreshold)) { myFlirRegion.Color = CogColorConstants.Green; } else { myFlirRegion.Color = CogColorConstants.Yellow; } } // Show the hist count in the Flir image if (patternResult.Score >= patternBaslerTool.RunParams.AcceptThreshold) { myFlirLabel.Color = CogColorConstants.Green; } else { myFlirLabel.Color = CogColorConstants.Yellow; } if (showHist) { myFlirLabel.SetXYText(patternResult.GetPose().TranslationX, patternResult.GetPose().TranslationY, "Size: " + histCntr.ToString()); } // Convert blob angle to degrees blobAngle = patternResult.GetPose().Rotation * 180 / Math.PI; //MessageBox.Show("blob.Angle:" + blobAngle.ToString()); if ((blobAngle > (double)minPickAngle) && (blobAngle < (double)maxPickAngle)) { if (patternResult.Score >= patternBaslerTool.RunParams.AcceptThreshold) { malBlobPoses.Add(l2d); } else { myAreaLabel.Color = CogColorConstants.Red; } if (showArea) { myAreaLabel.SetXYText(l2d.TranslationX, l2d.TranslationY - 15, "Score: " + (patternResult.Score * 100).ToString("0")); } AreaLabel.Add(myAreaLabel); } else { myBaslerLabel.Color = CogColorConstants.Red; myBaslerLabel.SetXYText(l2d.TranslationX, l2d.TranslationY, "Angle: " + blobAngle.ToString("0")); myFlirLabel.Color = CogColorConstants.Red; myFlirRegion.Color = CogColorConstants.Red; angleFailures++; } } myBaslerLabel.Rotation = blobAngleRadians; BaslerLabels.Add(myBaslerLabel); FlirLabels.Add(myFlirLabel); FlirRectangles.Add(myFlirRegion); Crosshairs.Add(baslerMarker); } // Update group output terminals toolGroup.SetScriptTerminalData("AngleFailures", angleFailures); toolGroup.SetScriptTerminalData("ThermalFailures", thermalFailures); toolGroup.SetScriptTerminalData("BlobCollection", malBlobPoses); } catch (Exception ex) { toolGroup.SetScriptTerminalData("BaslerStatus", "Script Error during Pattern processing: " + ex.Message); malBlobPoses.Clear(); // Clear positional data for this frame } // Returning False indicates we ran the tools in script, and they should not be // run by VisionPro return(false); }
//初始化函数2 private void initToolEdit() { //JobManagerEdit.Subject = m_JobManager; //一级视觉 CogToolGroup m_ToolGroup_1 = (CogToolGroup)m_Job_1.VisionTool; cogToolGroupEditV21.Subject = m_ToolGroup_1; if (m_ToolGroup_1 == null) { MessageBox.Show("toolgroup1工具读取失败,窗口将自动关闭"); this.Close(); return; } blobTool_1 = (CogBlobTool)m_ToolGroup_1.Tools["CogBlobTool1"]; if (blobTool_1 == null) { MessageBox.Show("blob1工具读取失败,请退出软件"); } pmaTool_1 = (CogPMAlignTool)m_ToolGroup_1.Tools["caliPMATool"]; if (pmaTool_1 == null) { MessageBox.Show("pma1工具读取失败,请退出软件"); } calibTool_1 = (CogCalibNPointToNPointTool)m_ToolGroup_1.Tools["CogCalibNPointToNPointTool1"]; if (calibTool_1 == null) { MessageBox.Show("calib1工具读取失败,请退出软件"); } acqFifoTool_1 = (CogAcqFifoTool)m_ToolGroup_1.Tools["CogAcqFifoTool1"]; if (acqFifoTool_1 == null) { MessageBox.Show("acqfifo1工具读取失败,窗口将自动关闭"); this.Close(); return; } mAcqFifo_1 = acqFifoTool_1.Operator; if (mAcqFifo_1 == null) { MessageBox.Show("macqfifo1为 null,窗口将自动关闭"); this.Close(); return; } mAcqFifo_1.Timeout = 1000; //二级视觉 CogToolGroup m_ToolGroup_2 = (CogToolGroup)m_Job_2.VisionTool; cogToolGroupEditV22.Subject = m_ToolGroup_2; if (m_ToolGroup_2 == null) { MessageBox.Show("toolgroup2工具读取失败,窗口将自动关闭"); this.Close(); return; } blobTool_2 = (CogBlobTool)m_ToolGroup_2.Tools["CogBlobTool1"]; if (blobTool_2 == null) { MessageBox.Show("blob2工具读取失败,请退出软件"); } pmaTool_2 = (CogPMAlignTool)m_ToolGroup_2.Tools["caliPMATool"]; if (pmaTool_2 == null) { MessageBox.Show("pma2工具读取失败,请退出软件"); } calibTool_2 = (CogCalibNPointToNPointTool)m_ToolGroup_2.Tools["CogCalibNPointToNPointTool1"]; if (calibTool_2 == null) { MessageBox.Show("calib2工具读取失败,请退出软件"); } acqFifoTool_2 = (CogAcqFifoTool)m_ToolGroup_2.Tools["CogAcqFifoTool1"]; if (acqFifoTool_2 == null) { MessageBox.Show("acqfifo2工具读取失败,窗口将自动关闭"); this.Close(); return; } mAcqFifo_2 = acqFifoTool_2.Operator; if (mAcqFifo_2 == null) { MessageBox.Show("macqfifo2为 null,窗口将自动关闭"); this.Close(); return; } mAcqFifo_2.Timeout = 1000; ////对比度Test //ICogAcqContrast mContrast = mAcqFifo_2.OwnedContrastParams; //double val = mContrast.Contrast; //Console.WriteLine(val); //三级视觉 CogToolGroup m_ToolGroup_3 = (CogToolGroup)m_Job_3.VisionTool; cogToolGroupEditV23.Subject = m_ToolGroup_3; if (m_ToolGroup_3 == null) { MessageBox.Show("toolgroup3工具读取失败,窗口将自动关闭"); this.Close(); return; } blobTool_3 = (CogBlobTool)m_ToolGroup_3.Tools["CogBlobTool1"]; if (blobTool_3 == null) { MessageBox.Show("blob3工具读取失败,请退出软件"); } pmaTool_3 = (CogPMAlignTool)m_ToolGroup_3.Tools["caliPMATool"]; if (pmaTool_3 == null) { MessageBox.Show("pma3工具读取失败,请退出软件"); } calibTool_3 = (CogCalibNPointToNPointTool)m_ToolGroup_3.Tools["CogCalibNPointToNPointTool1"]; if (calibTool_3 == null) { MessageBox.Show("calib3工具读取失败,请退出软件"); } acqFifoTool_3 = (CogAcqFifoTool)m_ToolGroup_3.Tools["CogAcqFifoTool1"]; if (acqFifoTool_3 == null) { MessageBox.Show("acqfifo3工具读取失败,窗口将自动关闭"); this.Close(); return; } mAcqFifo_3 = acqFifoTool_3.Operator; if (mAcqFifo_3 == null) { MessageBox.Show("macqfifo3为 null,窗口将自动关闭"); this.Close(); return; } mAcqFifo_3.Timeout = 1000; }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //생성 : //추가 : //목적 : 생성자 //설명 : ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public CDialogCogPMAlign(CogPMAlignTool objPMAlignTool) { m_objPMAlignTool = objPMAlignTool; InitializeComponent(); }
public InspectionMultiPattern() { PatternProc = new CogPMAlignTool(); PatternResults = new CogPMAlignResults(); AnglePointProc = new CogAnglePointPointTool(); }
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"); } }
public void Subject_Ran(object sender, EventArgs e) { if (RunAgainFlag) { PatMaxTool.RunParams.AcceptThreshold = Convert.ToDouble(numericUpDown1.Value * Convert.ToDecimal(0.9)); cogPMAlignTool.RunParams.AcceptThreshold = Convert.ToDouble(numericUpDown1.Value * Convert.ToDecimal(0.9)); } cogAcqTool = cogToolBlockEditV21.Subject.Tools["CogAcqFifoTool1"] as CogAcqFifoTool; calbCheckerBoard.InputImage = cogToolBlockEditV21.Subject.Inputs["Image"].Value as CogImage8Grey; calbCheckerBoard = cogToolBlockEditV21.Subject.Tools["CogCalibCheckerboardTool1"] as CogCalibCheckerboardTool; calbCheckerBoard.Run(); CalibNPointTool = cogToolBlockEditV21.Subject.Tools["CogCalibNPointToNPointTool1"] as CogCalibNPointToNPointTool; CalibNPointTool.InputImage = calbCheckerBoard.OutputImage; cogPMAlignTool = cogToolBlockEditV21.Subject.Tools["CogPMAlignTool1"] as CogPMAlignTool; cogPMAlignTool.InputImage = CalibNPointTool.OutputImage as CogImage8Grey; //cogRecordDisplay1.Image = cogPMAlignTool.InputImage; cogPMAlignTool.Run(); if (flagDisplayResult) //add on 25/11/14 { cogRecordDisplay1.Image = cogPMAlignTool.InputImage; cogRecordDisplay1.Record = cogPMAlignTool.CreateLastRunRecord(); cogRecordDisplay1.Fit(true); } dataGridView1.Rows.Clear(); try { if ((cogPMAlignTool.Results.Count == 0) && (!AppGen.Inst.MDImain.frmVisionMain.FrmLoadtray.flagFullTray)) //no insert founded { AppGen.Inst.LoadTray.IndexList[AppGen.Inst.LoadTray.CurrIndex].IsFound = false; UnfoundInsertList.Add(AppGen.Inst.LoadTray.IndexList[AppGen.Inst.LoadTray.CurrIndex]); //not in use!! } else //insert founded { AppGen.Inst.LoadTray.IndexList[AppGen.Inst.LoadTray.CurrIndex].X_VisRes = cogPMAlignTool.Results[0].GetPose().TranslationX; AppGen.Inst.LoadTray.IndexList[AppGen.Inst.LoadTray.CurrIndex].Y_VisRes = cogPMAlignTool.Results[0].GetPose().TranslationY; AppGen.Inst.LoadTray.IndexList[AppGen.Inst.LoadTray.CurrIndex].Angle_VisRes = cogPMAlignTool.Results[0].GetPose().Rotation *(180 / Math.PI); //converted to degree } for (int i = 0; i < cogPMAlignTool.Results.Count; i++) { dataGridView1.Rows.Add(); dataGridView1[0, i].Value = cogPMAlignTool.Results[i].ID.ToString(); dataGridView1[1, i].Value = cogPMAlignTool.Results[i].Score.ToString(); dataGridView1[2, i].Value = cogPMAlignTool.Results[i].GetPose().Rotation *(180 / Math.PI); dataGridView1[3, i].Value = cogPMAlignTool.Results[i].GetPose().TranslationX; dataGridView1[4, i].Value = cogPMAlignTool.Results[i].GetPose().TranslationY; } txtPatMaxScoreValue.Text = cogPMAlignTool.Results.Count.ToString(); if ((cogPMAlignTool.SearchRegion != null)) { //cogPMAlignTool.SearchRegion.FitToImage(cogRecordDisplay1.Image, 0.990,0.999); cogRecordDisplay1.StaticGraphics.Add(cogPMAlignTool.SearchRegion as ICogGraphic, "test"); cogToolBlockEditV21.Subject.Inputs["Image"].Value = cogRecordDisplay1.Image; } } catch (Exception) { MessageBox.Show("Insert wasn't found", "Run tool Error"); } }