【机械视觉】C#+VisionPro联合编程———【四、检测彩色保险丝实例,以及C#+VisionPro的两种写法】

news/2025/3/14 8:46:23/

【机械视觉】C#+VisionPro联合编程———【四、检测彩色保险丝实例,以及C#+VisionPro的两种写法】

在机械视觉C#+VisionPro联合编程编程中,在处理业务逻辑时通常会有两种写法,一种是将逻辑代码编写在visionPro中然后再使用C#将visionPro工具加载到vs中,另一种是先通过C#加载visionPro工具到vs中再使用C#在vs中编写逻辑代码。

本篇文章将用检测彩色保险丝的实例将这两种写法分别展现出来。


实例一写法(在vs中编写逻辑代码)

所用的winform工具:

  • button
  • label
  • cogRecordDisplay

实现逻辑

此案例用的是复合颜色匹配工具CogCompositeColorMatchTool和CogPMAlignTool,用了脚本实现,功能更加强大,这个借用的脚本能实现多个颜色数量一起显示。

先将复合颜色匹配工具训练各个颜色数据,将PMA匹配到的每个保险丝,然后保存工具。

在vs中加载复合颜色匹配工具和PMA工具,将PMA匹配到的每个保险丝位置信息传给复合颜色匹配工具,然后在代码中运行此工具,将匹配得到的颜色数量存储在一个变量中,最后再用label进行显示。

第一步、训练复合颜色匹配工具和PMA工具(并且保存)

第二步、将工具加载到vs中

Pma = (CogPMAlignTool)CogSerializer.LoadObjectFromFile("./pma.vpp");
Col = (CogCompositeColorMatchTool)CogSerializer.LoadObjectFromFile("./col.vpp");

第三步、将PMA匹配到的每个保险丝位置信息传给复合颜色匹配工具,然后在代码中运行此工具,获取匹配结果并将结果展示在label

for (int i = 0; i < Pma.Results.Count; i++)
{CogCircle cir = Col.Region as CogCircle;cir.CenterX = Pma.Results[i].GetPose().TranslationX;cir.CenterY = Pma.Results[i].GetPose().TranslationY;Col.Region = cir;Col.Run();string name = Col.Result.ResultOfBestMatch.Color.Name;switch (name){case "red":dic["红色"] = dic["红色"] += 1;break;case "blue":dic["蓝色"] = dic["蓝色"] += 1;break;case "green":dic["绿色"] = dic["绿色"] += 1;break;case "orange":dic["橙色"] = dic["橙色"] += 1;break;case "yellow":dic["黄色"] = dic["黄色"] += 1;break;}}this.label1.Text = $"红色:{dic["红色"]}, 蓝色: {dic["蓝色"]}, 绿色: {dic["绿色"]}, 橙色: {dic["橙色"]}, 黄色: {dic["黄色"]}";

完整代码

public partial class Form1 : Form
{public Form1(){InitializeComponent();}CogPMAlignTool Pma = null;CogCompositeColorMatchTool Col = null;Dictionary<string, int> dic = null;/// <summary>/// 加载/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button1_Click(object sender, EventArgs e){dic = new System.Collections.Generic.Dictionary<string, int>();if (Pma != null&&Col!=null){MessageBox.Show("已加载");}Pma = (CogPMAlignTool)CogSerializer.LoadObjectFromFile("./pma.vpp");Col = (CogCompositeColorMatchTool)CogSerializer.LoadObjectFromFile("./col.vpp");Bitmap bitmap = Image.FromFile("./bxs.png") as Bitmap;CogImage8Grey img8 = new CogImage8Grey(bitmap);Pma.InputImage = img8;CogImage24PlanarColor img24 = new CogImage24PlanarColor(bitmap);Col.InputImage = img24;Pma.Run();this.cogRecordDisplay1.Image = img24;this.cogRecordDisplay1.Fit();// this.cogRecordDisplay1.Record = Pma.CreateLastRunRecord().SubRecords[0];this.label2.Text = "Count: "+Pma.Results.Count;dic.Add("红色",0);dic.Add("黄色",0);dic.Add("绿色",0);dic.Add("橙色",0);dic.Add("蓝色",0);}/// <summary>/// 匹配/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button2_Click(object sender, EventArgs e){for (int i = 0; i < Pma.Results.Count; i++){CogCircle cir = Col.Region as CogCircle;cir.CenterX = Pma.Results[i].GetPose().TranslationX;cir.CenterY = Pma.Results[i].GetPose().TranslationY;Col.Region = cir;Col.Run();string name = Col.Result.ResultOfBestMatch.Color.Name;switch (name){case "red":dic["红色"] = dic["红色"] += 1;break;case "blue":dic["蓝色"] = dic["蓝色"] += 1;break;case "green":dic["绿色"] = dic["绿色"] += 1;break;case "orange":dic["橙色"] = dic["橙色"] += 1;break;case "yellow":dic["黄色"] = dic["黄色"] += 1;break;}}this.label1.Text = $"红色:{dic["红色"]}, 蓝色: {dic["蓝色"]}, 绿色: {dic["绿色"]}, 橙色: {dic["橙色"]}, 黄色: {dic["黄色"]}";}}


实例二写法(在visionPro中编写逻辑代码)

所用的winform工具:

  • button
  • label
  • cogRecordDisplay

实现逻辑

先在visionPro中添加toolblock工具并在工具中训练复合颜色和pma匹配工具,然后使用toolblock工具中的C# Advanced Script脚本编写逻辑代码,将PMA匹配到的每个保险丝位置信息传给复合颜色匹配工具,然后在代码中运行此工具,将匹配结果进行展现。

将工具保存到本地,然后使用C#在vs中加载,将匹配结果展现在winform中。

第一步、在toolblock中训练复合颜色匹配工具和PMA工具

第二步、在toolblock中编写逻辑代码,并且保存

将PMA匹配到的每个保险丝位置信息传给复合颜色匹配工具,然后在代码中运行此工具,将匹配结果进行展现。

#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.ImageProcessing;
using Cognex.VisionPro.PMAlign;
using Cognex.VisionPro.CompositeColorMatch;
#endregionpublic class CogToolBlockAdvancedScript : CogToolBlockAdvancedScriptBase
{#region Private Member Variablesprivate Cognex.VisionPro.ToolBlock.CogToolBlock mToolBlock;#endregionCogGraphicCollection cc = new CogGraphicCollection();/// <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();// #endifcc.Clear();// Run each tool using the RunTool functionforeach(ICogTool tool in mToolBlock.Tools)mToolBlock.RunTool(tool, ref message, ref result);CogPMAlignTool pma = mToolBlock.Tools["CogPMAlignTool1"] as CogPMAlignTool;CogCompositeColorMatchTool match = mToolBlock.Tools["CogCompositeColorMatchTool1"] as CogCompositeColorMatchTool;for (int i = 0; i < pma.Results.Count; i++){CogRectangleAffine ret = match.Region as CogRectangleAffine;ret.CenterX = pma.Results[i].GetPose().TranslationX;ret.CenterY = pma.Results[i].GetPose().TranslationY;ret.Rotation = pma.Results[i].GetPose().Rotation;match.Region = ret;match.Run();CogGraphicLabel label = new CogGraphicLabel();label.SetXYText(pma.Results[i].GetPose().TranslationX,pma.Results[i].GetPose().TranslationY-20,match.Result.ResultOfBestMatch.Color.Name);cc.Add(label);}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){foreach (ICogGraphic item in cc){mToolBlock.AddGraphicToRunRecord(item,lastRecord,"CogImageConvertTool1.InputImage","");}}#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 REMOVEbase.Initialize(host);// Store a local copy of the script hostthis.mToolBlock = ((Cognex.VisionPro.ToolBlock.CogToolBlock)(host));}#endregion}

第三步、将工具加载到vs中并且展示结果

public partial class Form1 : Form
{public Form1(){InitializeComponent();}CogToolBlock tb;/// <summary>/// 加载/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button1_Click(object sender, EventArgs e){tb = CogSerializer.LoadObjectFromFile("./Bxs.vpp") as CogToolBlock;if (tb != null) { MessageBox.Show("加载完成!!!"); }}/// <summary>/// 匹配/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button2_Click(object sender, EventArgs e){tb.Run();this.cogRecordDisplay1.Record = tb.CreateLastRunRecord().SubRecords[0];this.label2.Text = "Count: "+(tb.Tools[1] as CogPMAlignTool).Results.Count.ToString();}
}


http://www.ppmy.cn/news/1578995.html

相关文章

Ollama有安全漏洞! 国家网络安全通报中心紧急通报

最新消息&#xff01;国家网络安全通报中心昨夜发布紧急通告&#xff1a;全球超火的AI神器Ollama惊现重大漏洞&#xff01;正在用DeepSeek、Llama的你&#xff0c;赶紧自查&#xff01; &#x1f6d1; 你正美滋滋用Ollama跑着大模型&#xff0c;殊不知黑客正像逛超市一样随意进…

C++ std::list超详细指南:基础实践(手搓list)

目录 一.核心特性 1.双向循环链表结构 2.头文件&#xff1a;#include 3.时间复杂度 4.内存特性 二.构造函数 三.list iterator的使用 1.学习list iterator之前我们要知道iterator的区分 ​编辑 2.begin()end() 3. rbegin()rend() 四.list关键接口 1.empty() 2. size…

【微知】tmux如何在某个会话session中创建多个窗口?如何切换?(Ctrl+b + c创建;Ctrl+b + 数字 切换;Ctrl+b + 关闭)

创建窗口 创建新窗口&#xff1a;Ctrlb c 切换窗口&#xff1a; 切换到下一个窗口&#xff1a;Ctrlb n 切换到上一个窗口&#xff1a;Ctrlb p 切换到指定窗口&#xff1a;Ctrlb 数字&#xff08;窗口编号&#xff09; 重命名窗口&#xff1a;Ctrlb ,&#xff08;逗号&a…

使用 ESP32 和 Python 进行手势识别

使用手势控制 LED 这个 ESP32 项目是一种使用手势控制 LED 的令人兴奋的交互式方式。我们将使用 ESP32 开发板、Python、MediaPipe 和 OpenCV 创建一个系统,该系统可以检测特定的手势并将其转换为控制 LED 的作。MediaPipe 将用于识别手势,而 OpenCV 将捕获来自网络摄像头的…

Win11 + cherry studio deepseek本地部署,保姆级教程

目录 1.API申请 2.API调用 3.添加本地知识库 4.内容检索 1.API申请 我们首先需要申请一个账号&#xff0c;注册后可以直接获取2000万免费tokens&#xff0c;新增我们的秘钥用于后续使用&#xff0c;申请方法如下。 账号登录地址&#xff1a; 硅基流动统一登录 点击秘钥&am…

FX-std::map

std::map 是 C 标准库中的一个关联容器&#xff0c;用于存储键值对&#xff08;key-value pairs&#xff09;&#xff0c;并根据键自动排序。它基于红黑树实现&#xff0c;具有对数时间复杂度的插入、删除和查找操作。 基本用法 1. 包含头文件 使用 std::map 需要包含头文件…

Python刷题:Python基础

今天刷的是PythonTip的Python 入门挑战中的题&#xff0c;整体难度不高&#xff0c;适合小白练手以及巩固知识点。下面会进行详细讲解。 每日一句 梦想不会发光&#xff0c;发光的是追逐梦想的我们。 只要你真的愿意为自己的梦想去努力&#xff0c; 最差的结果&#xff0c;…

rtsp在网页上显示(webrtc-stream)

一&#xff1a;windos 平台 1&#xff1a;下载已经编译好的windos平台程序 Releases mpromonet/webrtc-streamer (github.com) or 【免费】webrtc-streamerv0.8.6一款werbrtc服务器&#xff08;windos版本&#xff09;&#xff0c;可以直接将rtsp流拉到网页上显示资源-CSDN文…