You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HALCON + C# WinForms中如何显示Halcon程序选中的缺陷对象?

解决WinForms中Halcon HWindowControl无法显示Defects区域的问题

核心问题分析

你的Defects是通过select_mask_obj得到的区域对象(HRegion),而非图像(HImage),当前代码存在两个关键错误:

  1. 使用了错误的方法获取对象(GetParamTupleImage仅适用于图像,无法正确获取区域类型)
  2. 未设置区域的显示样式(默认颜色可能与图像/背景重合,导致视觉上不可见)

步骤1:确保Halcon脚本的输出参数配置正确

先检查你的hdvp程序,必须将Defects声明为输出参数:

  • 打开hdvp程序,在参数列表中添加Defects,类型选择Object,方向设为Output
  • 确保脚本执行完成后,Defects可被外部调用正常获取

步骤2:修正C#中获取并显示Defects的代码

替换错误的对象获取方法,同时添加区域显示样式设置:

private void GetDefectsProcedure () {
    try {
        ING_Halcon halconScript = new ING_Halcon(HALCON_SCRIPTS_LIST[SCRIPT_TWO]);
        halconScript.SetInputImage("Image", img1HParam);
        halconScript.Execute();
        
        // 替换为获取HRegion类型对象的方法,根据你的ING_Halcon封装调整
        HRegion defects = halconScript.GetParamRegion("Defects"); 
        
        HWindow hWin = hWindowControl1.HalconWindow;
        HImage result = img1HParam;
        
        // 重置窗口,确保坐标系与图像匹配
        hWin.ClearWindow();
        hWin.SetPart(0, 0, result.Height-1, result.Width-1);
        
        // 显示原图
        hWin.DispImage(result);
        
        // 设置区域显示样式(关键:用显眼的颜色区分)
        hWin.SetColor("red");
        hWin.SetDraw("margin"); // 可选:"fill"填充区域 / "margin"仅显示边框
        hWin.SetLineWidth(2); // 可选:加粗边框提升辨识度
        
        // 显示缺陷区域
        hWin.DispObj(defects);
        
        // 强制刷新窗口
        hWin.UpdateWindow();
    }
    catch (Exception exc) {
        Console.WriteLine($"GetDefectsProcedure Exception:\n\t{exc}.");
    }
}

如果你的ING_Halcon未封装GetParamRegion方法,需要补充封装逻辑,示例片段:

public HRegion GetParamRegion(string paramName) {
    HRegion region = new HRegion();
    _procedure.GetIconicParam(paramName, region);
    return region;
}

额外排查点

  • 检查defects是否为null:获取后添加Debug.Assert(defects != null)或日志打印,确认对象正常获取
  • 若Defects是多区域集合(HRegionArray),需遍历显示:
    foreach (HRegion reg in defects) {
        hWin.DispObj(reg);
    }
    
  • 确保HWindowControl的显示区域与图像尺寸适配,或通过SetPart强制窗口匹配图像范围

内容的提问来源于stack exchange,提问作者F A Fernández

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 13:38:29