bitmap为C#程序自带图片格式,将bitmap传入C++中是将bitmap数据的指针传入,C++中再利用OpenCV进行生成图片。
bitmap的PixelFormat.Format24bppRgb时对应的opencv是CV_8UC3,颜色通道分别B,G,R(虽然它标示的是24bppRgb,但是在opencv里面用cv::split出来看就知道了它是B,G,R的),PixelFormat.Format32bppPArgb对应CV_8UC4,Format8bppIndexed对应CV_8UC1,一般只要opencv的Mat类的stride和C#中bitmap图的stride对应上就可以正确解析。
C++部分代码:
extern "C" __declspec(dllexport) void GetBitmapToCSharp(uchar* data, int width, int height, int stride)
{
//对stride进行判断,同时得出不同的图片格式
cv::Mat img;
if (stride / width == 3)
img = cv::Mat(height, width, CV_8UC3, data, stride);
if (stride / width == 1)
img = cv::Mat(height, width, CV_8UC1, data, stride);
if (stride / width == 4)
img = cv::Mat(height, width, CV_8UC4, data, stride);
//显示
cv::namedWindow("image", 0);
cv::imshow("image", img);
cv::waitKey(0);
}
C#部分代码:先对C++dll进行调用,再对bitmap图片进行处理
[DllImport("Dll1.dll", CallingConvention = CallingConvention.Cdecl)]
extern static public void GetBitmapToCSharp(IntPtr data, int width, int height, int stride);
//读取图片
Bitmap bmp = new Bitmap("C:\\Users\\areok\\Desktop\\1.bmp");
BitmapData imgData = null;
//判断图片的格式
if (bmp.PixelFormat == PixelFormat.Format24bppRgb)
{
imgData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
}
else if (bmp.PixelFormat == PixelFormat.Format8bppIndexed)
{
imgData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
}
else if (bmp.PixelFormat == PixelFormat.Format32bppPArgb)
{
imgData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppPArgb);
}
//获取图片的参数
int width = imgData.Width;
int height = imgData.Height;
int stride = imgData.Stride;
//传入图片信息
GetBitmapToCSharp(imgData.Scan0, width, height, stride);