C++opencv图片(mat)传入C#bitmap图片

C++将OpenCV的图片传入主要是将图片信息放入uchar数组中,C#再使用byte数组读取信息,生成图片。

RGB图片传入方法:

C++部分程序

cpp 复制代码
extern "C" __declspec(dllexport) void MatToHobject(int& width, int& height, uchar * array)
{
    Mat matTemp;
 
    //依次将rgb数据放入uchar数组中	
    for (int i = 0; i < matTemp.rows; i++) {
	    for (int j = 0; j < matTemp.cols; j++) {
		    for (int k = 0; k < 3; k++) {
			array[i * matTemp.cols * 3 + j * 3 + k] = matTemp.at<cv::Vec3b>(i, j)[k];
		    }
	    }
    }
 
    //将图片的宽高传出
    width = matTemp.cols;
    height = matTemp.rows;
    
}

C#部分程序

cs 复制代码
//C#调用C++程序
[DllImport("Dll1.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void MatToHobject(ref int width, ref int height, ref byte array);
 
cs 复制代码
public Bitmap BitmapGenerateMask(int width, int height, byte[] maskArray)
{
    try
    {
        //生成maks图片
        Bitmap maskBmp = null;
        // 创建Bitmap对象
        using (Bitmap bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
        {
            Rectangle rect = new Rectangle(0, 0, width, height);
            // 锁定Bitmap区域以便进行写入
            BitmapData bmpData = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, bitmap.PixelFormat);
            int stride = bmpData.Stride; // 获取stride值

            // 遍历每一行并根据stride调整
            for (int y = 0; y < height; y++)
            {
                // 计算源和目标的起始位置
                IntPtr destPtr = (IntPtr)((long)bmpData.Scan0 + y * stride);
                int sourceIndex = y * width * 3; // 对于24bppRgb格式,每像素3字节

                // 将当前行的数据复制到bitmap
                Marshal.Copy(maskArray, sourceIndex, destPtr, width * 3); // 每行的字节数
            }

            //复制数据到新的Bitmap
            maskBmp = bitmap.Clone(new System.Drawing.RectangleF(new PointF(0, 0), new SizeF(bitmap.Width, bitmap.Height)), bitmap.PixelFormat);
            // 解锁Bitmap区域
            bitmap.UnlockBits(bmpData);
        }

        return maskBmp;
    }
    catch (Exception ex)
    {
        UIMessageBox.ShowError("绘制maks图异常" + ex.ToString());
        return null;
    }
}
相关推荐
余额瞒着我当琳3 小时前
C++--深拷贝三件套 + swap + 写时拷贝 + vector 扩容 + reserve
java·开发语言·c++
坐吃山猪4 小时前
WebClient内存配置解析
开发语言·springboot·webflux
jdksjw4 小时前
同步与异步、阻塞与非阻塞、多线程、协程超详细讲解(Python并发编程从入门到精通)
开发语言·python
Zach_菠萝侠4 小时前
【DeepSeek Harness 研究】进化方向4:安全加固 思考、设计与实现
开发语言·安全·deepseek
ShineWinsu5 小时前
对于C++:布隆过滤器(bloomfilter)的详细解析
c++·面试·位图·位运算·布隆过滤器·海量数据·比特位
SL-staff5 小时前
技术实践:HR如何用JVS-Logic可视化编排实现考勤数据同步(含节点配置与异常处理)
开发语言·python·低代码·钉钉·可视化编排·jvs-logic·hr技术
SomeB1oody5 小时前
【RustyML入门】6.0. 数学工具
开发语言·后端·机器学习·rust·教程
进制树6 小时前
【飞控开发实战·⑲】ROS2无人机开发环境搭建:Jazzy安装、工作空间与hello_drone节点实战
开发语言·安全·无人机·课程设计
牛马也想出海7 小时前
亚马逊爬虫代理IP:IP类型选择与配置指南
开发语言·php
菜冻鱼7 小时前
Python-pytorch-高级技巧
开发语言·人工智能·pytorch·python·深度学习·神经网络·聚类