Halcon C# HObject HTuple 扩展方法

 public static class HalconEx
    {
        #region Public Methods
        /// <summary>
        /// Determines whether the specified halcon object, image, xld or region is not null and is initialized.
        /// </summary>
        /// <param name="from"> Halcon Object</param>
        /// <returns></returns>
        public static bool IsValid(this HObject source)
        {
            var result = false;
            if (null != @source)
            {
                if (@source.IsInitialized())
                {
                    result = @source.CountObj() > 0;
                }
            }
            return result;
        }

        /// <summary>
        /// convert an HObject containing an image to an HImage
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public static HImage ToHImage(this HObject source)
        {
            var imageTemp = new HImage();
            if (source.IsValid())
            {
                if (source.GetObjClass().S == "image")
                {
                    imageTemp.Dispose();
                    imageTemp = new HImage(source);
                }
            }
            return imageTemp;
        }

        /// <summary>
        /// Converts a bitmap to a Halcon image.
        /// </summary>
        /// <param name="from"></param>
        /// <returns></returns>
        public static HImage ToHImage(this Bitmap source)
        {
            Contract.Requires(source != null);
            Rectangle rectangle = new Rectangle(0, 0, source.Width, source.Height);
            var interleavedHalconImage = new HImage();

            // Convert 24 bit bitmap to 32 bit bitmap in order to ensure
            // that the bit width of the image (the Stride) is divisible by four.
            // Otherwise, one might obtain skewed conversions.
            var image32 = new Bitmap(source.Width, source.Height, PixelFormat.Format32bppRgb);
            image32.SetResolution(source.HorizontalResolution, source.VerticalResolution);
            using (Graphics g = Graphics.FromImage(image32))
            {
                g.DrawImage(source, new Point(0, 0));
            }

            // Obtain the image pointer.
            var bitmapData = image32.LockBits(rectangle, ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
            IntPtr pointerToBitmap = bitmapData.Scan0;
            IntPtr pointerToPixels = pointerToBitmap;

            // Create HALCON image from the pointer.
            interleavedHalconImage.GenImageInterleaved(pointerToPixels, "bgrx", source.Width, source.Height,
                -1, "byte", source.Width, source.Height, 0, 0, -1, 0);

            // Don't forget to unlock the bits again. ;-)
            image32.UnlockBits(bitmapData);
            var outputHalconImage = interleavedHalconImage.CopyImage();

            // Release memory by dereferencing and garbage collection
            interleavedHalconImage.Dispose();
            image32.Dispose();

            GC.Collect();
            GC.WaitForPendingFinalizers();

            return outputHalconImage;
        }

        /// <summary>
        /// Converts an HObject containing an region to an HRegion.
        /// </summary>
        /// <param name="from"></param>
        /// <returns></returns>
        public static HRegion ToHRegion(this HObject source)
        {
            var newRegion = new HRegion();
            if (source.IsValid())
            {
                if (source.GetObjClass().S == "region")
                {
                    newRegion.Dispose();
                    newRegion = new HRegion(source);
                }
            }
            return newRegion;
        }

        /// <summary>
        /// Converts an HObject containing an xld_cont to an HXLDCont.
        /// </summary>
        /// <param name="from"></param>
        /// <returns></returns>
        public static HXLDCont ToHXLDCont(this HObject source)
        {
            var newXldCont = new HXLDCont();
            if (source.IsValid())
            {
                if (source.GetObjClass().S == "xld_cont")
                {
                    newXldCont.Dispose();
                    newXldCont = new HXLDCont(source);
                }
            }

            return newXldCont;
        }

        /// <summary>
        /// Converts an HObject containing an xld_parallel to an HXLDPara.
        /// </summary>
        /// <param name="from"></param>
        /// <returns></returns>
        public static HXLDPara ToHXLDPara(this HObject source)
        {
            var newXldPara = new HXLDPara();
            if (source.IsValid())
            {
                if (source.GetObjClass().S == "xld_parallel")
                {
                    newXldPara.Dispose();
                    newXldPara = new HXLDPara(source);
                }
            }

            return newXldPara;
        }

        /// <summary>
        /// Converts an HObject containing an xld_poly to an HXLDPoly.
        /// </summary>
        /// <param name="from"></param>
        /// <returns></returns>
        public static HXLDPoly ToHXLDPoly(this HObject source)
        {
            var newXldPoly = new HXLDPoly();
            if (source.IsValid())
            {
                if (source.GetObjClass().S == "xld_poly")
                {
                    newXldPoly.Dispose();
                    newXldPoly = new HXLDPoly(source);
                }
            }

            return newXldPoly;
        }

        /// <summary>
        /// Get an HTuple TypeName
        /// </summary>
        /// <param name="from"></param>
        /// <returns></returns>
        public static string ToTypedString(this HTuple source)
        {
            switch (source.Type)
            {
                case HTupleType.INTEGER:
                    return source.I.ToString();

                case HTupleType.LONG:
                    return source.L.ToString();

                case HTupleType.DOUBLE:
                    return source.D.ToString("G");

                case HTupleType.STRING:
                    return source;

                default:
                    return string.Empty;
            }
        }

        /// <summary>
        /// Get an HTupleElements TypeName
        /// </summary>
        /// <param name="from"></param>
        /// <returns></returns>
        public static string ToTypedString(this HTupleElements source)
        {
            switch (source.Type)
            {
                case HTupleType.INTEGER:
                    return source.I.ToString();

                case HTupleType.LONG:
                    return source.L.ToString();

                case HTupleType.DOUBLE:
                    return source.D.ToString("G");

                case HTupleType.STRING:
                    return source;

                default:
                    return string.Empty;
            }
        }

        /// <summary>
        /// Returns the convex hull from a collection of XLD contours.
        /// </summary>
        /// <param name="from">The collection of XLD contours to be processed.</param>
        /// <returns>An XLD contour that is the convex hull.</returns>
        /// <example> HXLDCont convexHullXld = MyXldContours.ConvexHull (); .</example>
        public static HXLDCont ConvexHull(this HXLDCont source)
        {
            HXLDCont tempContour = new HXLDCont(), convexHull = new HXLDCont();
            HTuple cumulativeRows = new HTuple(), cumulativeColumns = new HTuple();

            try
            {
                if (@source != null && @source.IsValid())
                {
                    int count = @source.CountObj();
                    if (count > 1)
                    {
                        for (int i = 1; i <= count; i++)
                        {
                            @source[i].GetContourXld(out HTuple rows, out HTuple columns);
                            cumulativeRows = cumulativeRows.TupleConcat(rows);
                            cumulativeColumns = cumulativeColumns.TupleConcat(columns);
                        }

                        tempContour.GenContourPolygonXld(
                        cumulativeRows,
                        cumulativeColumns);
                        convexHull = tempContour.ShapeTransXld("convex");
                    }
                    else
                    {
                        convexHull = @source.ShapeTransXld("convex");
                    }
                }

                if (convexHull.IsInitialized())
                {
                    return convexHull.CopyObj(1, -1);
                }
                else
                {
                    return new HXLDCont();
                }
            }
            finally
            {
                tempContour.Dispose();
                convexHull.Dispose();
            }
        }

        /// <summary>
        /// A helper method to ensure that a HALCON HImage is correctly disposed when assigned a new value.
        /// </summary>
        /// <param name="from">The source HImage.</param>
        /// <param name="to">The destination HImage.</param>
        /// <exception cref="ArgumentNullException">from must not be null.</exception>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static void HCopy(this HImage from, ref HImage to)
        {
            try
            {
                if (@from == null)
                {
                    throw new ArgumentNullException(nameof(from));
                }

                if (to == null)
                {
                    to = new HImage();
                }

                to.Dispose();
                to = @from.CopyObj(1, -1);
            }
            finally
            {
                if (@from != null)
                {
                    @from.Dispose();
                }
            }
        }

        /// <summary>
        /// A helper method to ensure that a HALCON HRegion is correctly disposed when assigned a
        /// new value.
        /// </summary>
        /// <param name="from">The source HRegion.</param>
        /// <param name="to">The destination HRegion.</param>
        /// <exception cref="ArgumentNullException">from must not be null.</exception>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static void HCopy(this HRegion from, ref HRegion to)
        {
            try
            {
                if (@from == null)
                {
                    throw new ArgumentNullException(nameof(from));
                }

                if (to == null)
                {
                    to = new HRegion();
                }

                to.Dispose();
                to = @from.CopyObj(1, -1);
            }
            finally
            {
                if (@from != null)
                {
                    @from.Dispose();
                }
            }
        }

        /// <summary>
        /// A helper method to ensure that a HALCON HXLD is correctly disposed when assigned a new value.
        /// </summary>
        /// <param name="from">The source HXLD.</param>
        /// <param name="to">The destination HXLD.</param>
        /// <exception cref="ArgumentNullException">from must not be null.</exception>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static void HCopy(this HXLD from, ref HXLD to)
        {
            try
            {
                if (@from == null)
                {
                    throw new ArgumentNullException(nameof(from));
                }

                if (to == null)
                {
                    to = new HXLD();
                }

                to.Dispose();
                to = @from.CopyObj(1, -1);
            }
            finally
            {
                if (@from != null)
                {
                    @from.Dispose();
                }
            }
        }

        /// <summary>
        /// A helper method to ensure that a HALCON XLD Contour is correctly disposed when assigned a
        /// new value.
        /// </summary>
        /// <param name="from">The source HXLDCont.</param>
        /// <param name="to">The destination HXLDCont.</param>
        /// <exception cref="ArgumentNullException">from must not be null.</exception>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static void HCopy(this HXLDCont from, ref HXLDCont to)
        {
            try
            {
                if (@from == null)
                {
                    throw new ArgumentNullException(nameof(from));
                }

                if (to == null)
                {
                    to = new HXLDCont();
                }

                to.Dispose();
                to = @from.CopyObj(1, -1);
            }
            finally
            {
                if (@from != null)
                {
                    @from.Dispose();
                }
            }
        }

        /// <summary>
        /// Converts a system color to a halcon color as string 
        /// </summary>
        /// <param name="color"></param>
        /// <returns></returns>
        public static string ToHalconColor(this Color color)
        {
            string colorStr = "";
            try
            {
                colorStr = "#" + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2") + color.A.ToString("X2");
            }
            catch
            { }
            return colorStr;
        }

        /// <summary>
        /// Converts a List HObject to a HObject
        /// </summary>
        /// <param name="listObj"></param>
        /// <returns></returns>
        public static HObject ListHobject2HObject(this List<HObject> listObj)
        {
            HObject concatHObject;
            HOperatorSet.GenEmptyObj(out concatHObject);
            foreach (HObject reg in listObj)
            {
                HObject ExpTmpOutVar_0;
                HOperatorSet.ConcatObj(concatHObject, reg, out ExpTmpOutVar_0);
                concatHObject.Dispose();
                concatHObject = ExpTmpOutVar_0;
            }
            return concatHObject;
        }
        #endregion
    }
<think>嗯,用户的问题是关于在C#中使用自定义Halcon窗口控件来显示图像的方法和教程。首先,我需要回忆一下HalconC#联合编程的基本步骤。根据用户提供的引用,特别是引用[1],里面提到了如何通过HOperatorSet.ReadImage读取图片并用hWindowControl控件显示。这可能是一个基础方法,但用户提到的是“自定义”窗口控件,所以可能需要更深入的步骤。 接下来,我应该考虑如何创建自定义控件。通常在C#中,自定义控件可以通过继承现有的控件来实现。Halcon的hWindowControl可能是一个UserControl,用户可能需要自己设计界面或者添加额外的功能。引用[2]和[3]提到了绘制ROI和鼠标交互,这可能涉及到事件的处理,比如鼠标点击或拖动,这些在自定义控件中可能需要重写或添加新的事件处理程序。 然后,我需要确保代码示例的正确性。比如,在引用[1]中,HOperatorSet.ReadImage读取图片,然后调用hWindowControl1.HalconWindow.DispObj来显示。但如果是自定义控件,可能需要确保控件的HalconWindow属性正确初始化,或者是否需要手动创建Halcon的窗口句柄。 另外,用户可能需要了解如何在自定义控件中嵌入Halcon的窗口。Halcon通常需要绑定到某个窗口句柄,所以在自定义控件中可能需要处理窗口的尺寸变化、重绘等事件,确保图像能正确显示。例如,当控件大小改变时,可能需要调整Halcon窗口的视图或重新绘制图像。 还要考虑可能的异常处理,比如图片路径错误时的提示,或者控件正确初始化的处理。引用[1]中的代码示例没有错误处理,用户在实际使用时可能需要添加try-catch块或其他机制。 另外,用户可能需要了解如何与其他功能结合,比如引用[3]中的鼠标拖动图片,这需要在自定义控件中实现事件处理,比如MouseDown、MouseMove等事件,并调用Halcon的相关函数来实现交互功能。 总结下来,步骤可能包括:创建自定义控件类,初始化Halcon窗口,处理控件大小变化,加载并显示图像,以及可能的交互功能实现。需要确保引用的代码正确,并按照用户的需求进行扩展,比如自定义控件的设计、事件处理等。同时,要提醒用户注意路径问题、引用Halcon的DLL,以及控件的命名空间是否正确导入。</think>### C#定义 Halcon 窗口控件显示图像的实现方法 #### 1. 基础实现步骤 **a. 创建自定义控件类** ```csharp public class CustomHalconWindow : UserControl { private HWindow _halconWindow; public CustomHalconWindow() { // 初始化Halcon窗口 _halconWindow = new HWindow(); this.Resize += (s, e) => UpdateHalconWindowSize(); } private void UpdateHalconWindowSize() { // 同步控件尺寸与Halcon窗口 _halconWindow.SetWindowParam("width", this.Width); _halconWindow.SetWindowParam("height", this.Height); } } ``` **b. 图像显示核心方法** ```csharp public void DisplayImage(string imagePath) { try { HObject image; HOperatorSet.ReadImage(out image, imagePath); // 读取图像[^1] _halconWindow.DispObj(image); // 显示图像 } catch (HalconException ex) { MessageBox.Show($"图像加载失败: {ex.Message}"); } } ``` #### 2. 高级功能扩展 **a. 窗口缩放适配** ```csharp public void FitImageToWindow(HObject image) { HTuple width, height; HOperatorSet.GetImageSize(image, out width, out height); _halconWindow.SetPart(0, 0, height-1, width-1); // 设置显示区域 _halconWindow.DispObj(image); } ``` **b. 交互功能集成** (参考鼠标事件处理实现[^3]) ```csharp protected override void OnMouseDown(MouseEventArgs e) { double row = e.Y, col = e.X; // 实现ROI绘制或图像拖动逻辑... } ``` #### 3. 完整调用示例 ```csharp // 在窗体中使用自定义控件 private CustomHalconWindow _customWindow = new CustomHalconWindow(); private void btnLoadImage_Click(object sender, EventArgs e) { _customWindow.DisplayImage(@"D:\test.jpg"); _customWindow.FitImageToWindow(); // 自动适配窗口 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值