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;
    }
}
相关推荐
longlongzihan2 分钟前
LeetCode 56合并区间:排序与贪心
c++·算法·leetcode
程序员老陆2 分钟前
C++ 继承方式:公有、保护、私有,到底在控制什么
开发语言·c++
AI备忘录6 分钟前
(二十二)华为华三锐捷迈普思科 802.1X 端口认证配置命令(网络准入五厂商对照)
运维·服务器·开发语言·网络·安全·华为
坤坤子吖8 分钟前
C++11——Lambda、function、bind 与可调用对象
c++·笔记·学习
free-elcmacom8 分钟前
手撕 memcpy 和 memmove:从字节级拷贝到内存重叠的终极较量
c语言·开发语言·青少年编程·visual studio code·visual studio
白杨尚青31 分钟前
C++入门篇(十一):string(中)——容量与增删改查:一篇吃透所有常用接口(万字详解)
java·开发语言·c++
老歌老听老掉牙32 分钟前
旅行商问题:从数学模型到 Python 实战
开发语言·python
CC数分32 分钟前
数据可视化入门:用Python把一堆数字变成一张图
开发语言·python·信息可视化·数据分析
java_nnnn33 分钟前
JavaEE进阶-JavaScript初识
开发语言·前端·javascript·java-ee·ecmascript
朔北之忘 Clancy1 小时前
2024 CSP-J 第二轮真题解析
c++·算法·青少年编程·noip·csp·信奥赛·noi