.Net彩色图像转成Halcon和OpenCV的图像

主要是有一个“四字节对齐”的问题。直接上代码:

    /// <summary>
    /// Bitmap 转成 Halcon 图像,注意 Bitmap 图像的数据是四字节对齐的
    /// </summary>
    /// <param name="src"></param>
    /// <returns></returns>
    HalconDotNet.HImage DotNetImageToHImage(Bitmap src)
    {
      // TODO: 获取通道数、每通道字节数、内存清理工作
      var w = src.Width;
      var h = src.Height;
      var r = new Rectangle(0, 0, w, h);

      var bmpData = src.LockBits(r, System.Drawing.Imaging.ImageLockMode.ReadOnly, src.PixelFormat);
      var srcPtr = bmpData.Scan0;

      int srcStep = bmpData.Stride; // or (w * 3 * 8 + 31) / 32 * 4;
      int dstStep = w * 3;
      
      // 开辟了 2 个内存块
      var srcSize = srcStep * h;
      var dstSize = dstStep * h;
      byte[] srcBuff = new byte[srcSize];
      byte[] dstBuff = new byte[dstSize];

      // 原图的数据
      Marshal.Copy(srcPtr, srcBuff, 0, srcSize);

      // 把原图的数据复制到目标图像
      // 注意步长不同
      for (int row = 0; row < h; row++)
      {
        Buffer.BlockCopy(srcBuff, srcStep * row, dstBuff, dstStep * row, dstStep);
      }

      var dstPtr = Marshal.UnsafeAddrOfPinnedArrayElement(dstBuff, 0);
      var dst = new HalconDotNet.HImage();
      dst.GenImageInterleaved(dstPtr, "bgr", w, h, 0, "byte", w, h, 0, 0, -1, 0);

      return dst;
    }

    /// <summary>
    /// Bitmap 转成 OpenCV 图像,注意 Bitmap 图像的数据是四字节对齐的
    /// </summary>
    /// <param name="src"></param>
    /// <returns></returns>
    OpenCvSharp.Mat DotNetImageToOpenCVImage(Bitmap src)
    {
      // TODO: 获取通道数、每通道字节数、内存清理工作
      var w = src.Width;
      var h = src.Height;
      var r = new Rectangle(0, 0, w, h);

      var bmpData = src.LockBits(r, System.Drawing.Imaging.ImageLockMode.ReadOnly, src.PixelFormat);
      var srcPtr = bmpData.Scan0;

      int step = bmpData.Stride; // or (w * 3 * 8 + 31) / 32 * 4;

      var dst = new OpenCvSharp.Mat(h, w, OpenCvSharp.MatType.CV_8UC3, srcPtr, step);

      return dst;
    }
上一篇:halcon安装教程


下一篇:halcon视觉缺陷检测系列(3)表面缺陷检测数据集汇总及其相关项目推荐