检测球形轴承的安装错误
模板匹配 用建模器新建模型 并将多余的斑点删除掉
抓取训练图像
训练完成后
定位工具
添加高通过滤将图像简单处理、锐化图像,增强图像边缘对比
找⚪
极性展开
展开后
模板匹配 轴承滚珠间隙 抓取训练图像
匹配个数
训练完成
高级脚本
添加高级脚本sort
添加dll配置文件
定位dll文件所在目录
引入命名空间
定义标签列表变量
获取工具 并将匹配到的结果排序
排序结果弹窗展示(测试使用)
计算平均值
结果判断
添加高级脚本showResult
引入命名空间
定义变量
结果输出
c#
#region namespace imports
using System;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Cognex.VisionPro;
using Cognex.VisionPro.ToolBlock;
using Cognex.VisionPro3D;
using Cognex.VisionPro.PMAlign;
#endregion
public class CogToolBlockSimpleScript : CogToolBlockAdvancedScript
{
public ArrayList mySortedResults = new ArrayList();
ArrayList labels = new ArrayList();//标签列表
/// <summary>
/// Called when the parent tool is run.
/// Add code here to customize or replace the normal run behavior.
/// </summary>
/// <param name="message">Sets the Message in the tool's RunStatus.</param>
/// <param name="result">Sets the Result in the tool's RunStatus</param>
/// <returns>True if the tool should run normally,
/// False if GroupRun customizes run behavior</returns>
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
// Get the PMAlignResults from the input terminal
CogPMAlignResults myPMAlignResults = Inputs.Results as CogPMAlignResults; //获取工具
mySortedResults.Clear(); //标签清除
// Sort the PMAlignResults. Add them to mySortedResults in order, based on the
// TranslationX of the found result.
for (int resultIdx = 0; resultIdx <= myPMAlignResults.Count - 1; resultIdx++)
{
CogPMAlignResult myResult = myPMAlignResults[resultIdx];
if (mySortedResults.Count == 0)
{
mySortedResults.Add(myResult);
}
else
{
bool isFound = false;
int sortedResultIdx = 0;
while (!isFound & sortedResultIdx < mySortedResults.Count)
{
CogPMAlignResult sortedResult = mySortedResults[sortedResultIdx] as CogPMAlignResult;
if (myResult.GetPose().TranslationX < sortedResult.GetPose().TranslationX)
{
mySortedResults.Insert(sortedResultIdx, myResult);
isFound = true;
}
sortedResultIdx = sortedResultIdx + 1;
}
if (!isFound)
{
mySortedResults.Add(myResult);
}
}
}
Outputs.SortResults = mySortedResults;
/* 排序结果测试
String outputString = "Sorted X values are :";
for(int resultIdx = 0 ;resultIdx < mySortedResults.Count - 1; resultIdx++)
{
CogPMAlignResult sortedResult = mySortedResults[resultIdx] as CogPMAlignResult;
outputString = outputString + sortedResult.GetPose().TranslationX.ToString();
outputString = outputString + ", ";
}
System.Windows.Forms.MessageBox.Show(outputString); */
//------------------------以上是排序-----------------------------------------------
//获取相邻元素之间的间距
double[] myDistances = new double[mySortedResults.Count];
ArrayList SortArray = new ArrayList();
SortArray.Clear();
for(int i = 0; i < mySortedResults.Count - 2;i++){
CogPMAlignResult myRes ;
CogPMAlignResult myNextRes ;
myRes = mySortedResults[i] as CogPMAlignResult; //当前元素
myNextRes = mySortedResults[i + 1] as CogPMAlignResult; //相邻元素
myDistances[i] = myNextRes.GetPose().TranslationX - myRes.GetPose().TranslationX;
SortArray.Add(myDistances[i]);
}
SortArray.Sort(); //升序排序
/*-- 排序结果测试
String outputString = "Sorted distance values are :";
for(int resultIdx = 0 ;resultIdx < SortArray.Count - 1; resultIdx++){
outputString = outputString + SortArray[resultIdx].ToString();
outputString = outputString + ", ";
}
System.Windows.Forms.MessageBox.Show(outputString); *///
//计算距离平均值
double myAverageDistance = 0.0; //平均距离
int myNumAverageVals = (int) (mySortedResults.Count * 0.2);
int ctr = 0;
for(int i = (mySortedResults.Count / 2) - (myNumAverageVals / 2) ; i <= (mySortedResults.Count / 2) + (myNumAverageVals / 2); i++)
{
myAverageDistance = myAverageDistance + (double) SortArray[i];
ctr = ctr + 1; //统计元素个数
}
myAverageDistance = myAverageDistance / ctr;
//System.Windows.Forms.MessageBox.Show(myAverageDistance.ToString());
//--------------------------------以上是计算距离 计算平均值---------------------------------------
//---判断结果 生成标注标签 正确的就是标注绿色的圆 有瑕疵的标注红色的框
labels.Clear();
Boolean BadBearing = false;
for(int i = 0; i <= mySortedResults.Count - 1 ;i++)
{
CogPointMarker myPMarker = new CogPointMarker();
CogPMAlignResult myRes;
myRes = mySortedResults[i] as CogPMAlignResult;
myPMarker.X = myRes.GetPose().TranslationX;
myPMarker.Y = myRes.GetPose().TranslationY;
myPMarker.Color = Cognex.VisionPro.CogColorConstants.Green;
myPMarker.GraphicType = Cognex.VisionPro.CogPointMarkerGraphicTypeConstants.Circle;
myPMarker.LineWidthInScreenPixels = 2;
labels.Add(myPMarker);
if( myDistances[i] > myAverageDistance * 1.2)
{
CogPointMarker myPMarker1 = new CogPointMarker();
myRes = mySortedResults[i] as CogPMAlignResult;
myPMarker1.X = myRes.GetPose().TranslationX + (myDistances[i] / 2.0);
myPMarker1.Y = myRes.GetPose().TranslationY;
myPMarker1.Color = Cognex.VisionPro.CogColorConstants.Red;
myPMarker1.GraphicType = Cognex.VisionPro.CogPointMarkerGraphicTypeConstants.Square;
myPMarker1.LineWidthInScreenPixels = 2;
labels.Add(myPMarker1);
BadBearing = true;
}
}
Outputs.labels = labels;
//----标签生成完毕
return false;
}
#region When the Script is Initialized
/// <summary>
/// Perform any initialization required by your script here
/// </summary>
/// <param name="host">The host tool</param>
public override void Initialize(Cognex.VisionPro.ToolGroup.CogToolGroup host)
{
// DO NOT REMOVE - Call the base class implementation first - DO NOT REMOVE
base.Initialize(host);
}
#endregion
}
#region auto-generated
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// VisionPro Version: 9.0 CR2
// Generated: 2022-2-24 17:07:26
// Name: CogToolBlockScript, Version: 1.0
// Options:
// IncludeMainScriptClass, OverrideGroupRun,
// OverrideInitialize, IncludeInputsAdapterClass,
// IncludeOutputsAdapterClass, IncludeToolsAdapterClass,
// ExposeToolBlockReference, PlaceInAutoGeneratedRegion,
// AdapterClassIsEnumerable, IncludeRunToolFunction
//
// Changes to this code below this comment may cause incorrect behavior
// and will be lost if the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
public class CogToolBlockAdvancedScript : CogToolBlockAdvancedScriptBase
{
#region Private Member Variables
private Cognex.VisionPro.ToolBlock.CogToolBlock mToolBlock;
private CollectionAdapterInputs mInputs;
private CollectionAdapterOutputs mOutputs;
#endregion
/// <summary>
/// Called when the parent tool is run.
/// Add code here to customize or replace the normal run behavior.
/// </summary>
/// <param name="message">Sets the Message in the tool's RunStatus.</param>
/// <param name="result">Sets the Result in the tool's RunStatus</param>
/// <returns>True if the tool should run normally,
/// False if GroupRun customizes run behavior</returns>
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
return false;
}
#region When the Script is Initialized
/// <summary>
/// Perform any initialization required by your script here
/// </summary>
/// <param name="host">The host tool</param>
public override void Initialize(Cognex.VisionPro.ToolGroup.CogToolGroup host)
{
// DO NOT REMOVE - Call the base class implementation first - DO NOT REMOVE
base.Initialize(host);
// Initialize convenience types for ToolBlock Inputs, Outputs, and Tools
this.mInputs = new CollectionAdapterInputs(((Cognex.VisionPro.ToolBlock.CogToolBlock)(host)));
this.mOutputs = new CollectionAdapterOutputs(((Cognex.VisionPro.ToolBlock.CogToolBlock)(host)));
// Store a local copy of the script host
this.mToolBlock = ((Cognex.VisionPro.ToolBlock.CogToolBlock)(host));
}
#endregion
/// <summary>
/// Access the Tool's Inputs through an adapter class
/// </summary>
public CollectionAdapterInputs Inputs
{
get
{
return this.mInputs;
}
}
/// <summary>
/// Access the Tool's Outputs through an adapter class
/// </summary>
public CollectionAdapterOutputs Outputs
{
get
{
return this.mOutputs;
}
}
#region Public Methods
/// <summary>
/// Called from a script to run a tool.
/// </summary>
/// <param name="tool">The tool to run.</param>
/// <param name="message">The RunStatus Message.</param>
/// <param name="result">The RunStatus Result.</param>
/// <exception cref="System.Exception">
/// Thrown when <paramref name="tool"/> returns and
/// the calling tool's AbortRunOnToolFailure property is True.</exception>
protected virtual void RunTool(Cognex.VisionPro.ICogTool tool, ref string message, ref CogToolResultConstants result)
{
this.mToolBlock.RunTool(tool, ref message, ref result);
}
#endregion
}
#region Adapter Classes
public class CollectionAdapterInputs
{
private Cognex.VisionPro.ToolBlock.CogToolBlock mToolBlock;
public CollectionAdapterInputs(Cognex.VisionPro.ToolBlock.CogToolBlock toolBlock)
{
this.mToolBlock = toolBlock;
}
public Cognex.VisionPro.PMAlign.CogPMAlignResults Results
{
get
{
try
{
return ((Cognex.VisionPro.PMAlign.CogPMAlignResults)(this.mToolBlock.Inputs["Results"].Value));
}
catch (System.Exception ex)
{
throw new System.Exception(String.Format(Cognex.VisionPro.CogLocalizer.GetString(typeof(Cognex.VisionPro.ToolGroup.Resources.CogResourceKeys), Cognex.VisionPro.ToolGroup.Resources.CogResourceKeys.RkScritptAdapterMemberAccessError), this.mToolBlock.Name, "Inputs.Results"), ex);
}
}
}
}
public class CollectionAdapterOutputs
{
private Cognex.VisionPro.ToolBlock.CogToolBlock mToolBlock;
public CollectionAdapterOutputs(Cognex.VisionPro.ToolBlock.CogToolBlock toolBlock)
{
this.mToolBlock = toolBlock;
}
public System.Collections.ArrayList SortResults
{
get
{
try
{
return ((System.Collections.ArrayList)(this.mToolBlock.Outputs["SortResults"].Value));
}
catch (System.Exception ex)
{
throw new System.Exception(String.Format(Cognex.VisionPro.CogLocalizer.GetString(typeof(Cognex.VisionPro.ToolGroup.Resources.CogResourceKeys), Cognex.VisionPro.ToolGroup.Resources.CogResourceKeys.RkScritptAdapterMemberAccessError), this.mToolBlock.Name, "Outputs.SortResults"), ex);
}
}
set
{
this.mToolBlock.Outputs["SortResults"].Value = value;
}
}
public System.Collections.ArrayList labels
{
get
{
try
{
return ((System.Collections.ArrayList)(this.mToolBlock.Outputs["labels"].Value));
}
catch (System.Exception ex)
{
throw new System.Exception(String.Format(Cognex.VisionPro.CogLocalizer.GetString(typeof(Cognex.VisionPro.ToolGroup.Resources.CogResourceKeys), Cognex.VisionPro.ToolGroup.Resources.CogResourceKeys.RkScritptAdapterMemberAccessError), this.mToolBlock.Name, "Outputs.labels"), ex);
}
}
set
{
this.mToolBlock.Outputs["labels"].Value = value;
}
}
}
#endregion
#endregion
c#
#region namespace imports
using System;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Cognex.VisionPro;
using Cognex.VisionPro.ToolBlock;
using Cognex.VisionPro3D;
using Cognex.VisionPro.Implementation;
#endregion
public class CogToolBlockAdvancedScript : CogToolBlockAdvancedScriptBase
{
#region Private Member Variables
private Cognex.VisionPro.ToolBlock.CogToolBlock mToolBlock;
#endregion
/// <summary>
/// Called when the parent tool is run.
/// Add code here to customize or replace the normal run behavior.
/// </summary>
/// <param name="message">Sets the Message in the tool's RunStatus.</param>
/// <param name="result">Sets the Result in the tool's RunStatus</param>
/// <returns>True if the tool should run normally,
/// False if GroupRun customizes run behavior</returns>
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
// Run each tool using the RunTool function
foreach(ICogTool tool in mToolBlock.Tools)
mToolBlock.RunTool(tool, ref message, ref result);
return false;
}
#region When the Current Run Record is Created
/// <summary>
/// Called when the current record may have changed and is being reconstructed
/// </summary>
/// <param name="currentRecord">
/// The new currentRecord is available to be initialized or customized.</param>
public override void ModifyCurrentRunRecord(Cognex.VisionPro.ICogRecord currentRecord)
{
}
#endregion
#region When the Last Run Record is Created
/// <summary>
/// Called when the last run record may have changed and is being reconstructed
/// </summary>
/// <param name="lastRecord">
/// The new last run record is available to be initialized or customized.</param>
public override void ModifyLastRunRecord(Cognex.VisionPro.ICogRecord lastRecord)
{
CogImage8Grey myOutputImage = mToolBlock.Inputs["OutputImage"].Value as CogImage8Grey;
CogRecord leftRec = new CogRecord("Evaluation.OutputImage", myOutputImage.GetType(),
CogRecordUsageConstants.Result, false, myOutputImage, "Evaluation.OutputImage");
lastRecord.SubRecords.Add(leftRec);
ArrayList labels = mToolBlock.Inputs["labels"].Value as ArrayList;
foreach( CogPointMarker label in labels ) //item 图形集合中的任意一个元素
{
//MessageBox.Show(label.X.ToString());
mToolBlock.AddGraphicToRunRecord(label, lastRecord, "Evaluation.OutputImage", "script");
}
}
#endregion
#region When the Script is Initialized
/// <summary>
/// Perform any initialization required by your script here
/// </summary>
/// <param name="host">The host tool</param>
public override void Initialize(Cognex.VisionPro.ToolGroup.CogToolGroup host)
{
// DO NOT REMOVE - Call the base class implementation first - DO NOT REMOVE
base.Initialize(host);
// Store a local copy of the script host
this.mToolBlock = ((Cognex.VisionPro.ToolBlock.CogToolBlock)(host));
}
#endregion
}