1 | initial version |
Here's a method I'm using to copy data from a 'cv::Mat' to a 'System::Drawing::Bitmap'. If I remember right, it is inspired by EmguCV's way to deal with this problem, but I'm not sure. I just slightly edited this code to simplify it, so no guarantee it will work.
System::Drawing::Bitmap^ MatToBitmap(const cv::Mat& img)
{
if (img.type() != CV_8UC3)
{
throw gcnew NotSupportedException("Only images of type CV_8UC3 are supported for conversion to Bitmap");
}
//create the bitmap and get the pointer to the data
PixelFormat fmt(PixelFormat::Format24bppRgb);
Bitmap ^bmpimg = gcnew Bitmap(img.cols, img.rows, fmt);
BitmapData ^data = bmpimg->LockBits(System::Drawing::Rectangle(0, 0, img.cols, img.rows), ImageLockMode::WriteOnly, fmt);
byte *dstData = reinterpret_cast<byte*>(data->Scan0.ToPointer());
unsigned char *srcData = img.data;
for (int row = 0; row < data->Height; ++row)
{
memcpy(reinterpret_cast<void*>(&dstData[row*data->Stride]), reinterpret_cast<void*>(&srcData[row*img.step]), img.cols*img.channels());
}
bmpimg->UnlockBits(data);
return bmpimg;
}
2 | No.2 Revision |
Here's a method I'm using to copy data from a 'cv::Mat' cv::Mat
to a 'System::Drawing::Bitmap'.
System::Drawing::Bitmap
.
If I remember right, it is inspired by EmguCV's way to deal with this problem, but I'm not sure.
I just slightly edited this code to simplify it, so no guarantee it will work.
System::Drawing::Bitmap^ MatToBitmap(const cv::Mat& img)
{
if (img.type() != CV_8UC3)
{
throw gcnew NotSupportedException("Only images of type CV_8UC3 are supported for conversion to Bitmap");
}
//create the bitmap and get the pointer to the data
PixelFormat fmt(PixelFormat::Format24bppRgb);
Bitmap ^bmpimg = gcnew Bitmap(img.cols, img.rows, fmt);
BitmapData ^data = bmpimg->LockBits(System::Drawing::Rectangle(0, 0, img.cols, img.rows), ImageLockMode::WriteOnly, fmt);
byte *dstData = reinterpret_cast<byte*>(data->Scan0.ToPointer());
unsigned char *srcData = img.data;
for (int row = 0; row < data->Height; ++row)
{
memcpy(reinterpret_cast<void*>(&dstData[row*data->Stride]), reinterpret_cast<void*>(&srcData[row*img.step]), img.cols*img.channels());
}
bmpimg->UnlockBits(data);
return bmpimg;
}