How to convert CBitmap to cv::Mat? Maybe there are some libs or something else... like...
CBitmap bitmap;
bitmap.CreateBitmap(128, 128, 1, 24, someData);
cv::Mat outBitmap(128,128,someData,1,24);
but that code is incorrect.
thanks!
How to convert CBitmap to cv::Mat? Maybe there are some libs or something else... like...
CBitmap bitmap;
bitmap.CreateBitmap(128, 128, 1, 24, someData);
cv::Mat outBitmap(128,128,someData,1,24);
but that code is incorrect.
thanks!
There is another way around, you can convert your CBitmap
to HBitmap
, then convert HBitmap
to GdiPlus::Bitmap
, then convert it to cv::Mat
.
Here's what you can do, but beware, this solution only works for RGB24 pixel format :
Step 1: CBitmap
to HBITMAP
HBITMAP hBmp = (HBITMAP)yourCBitmap.GetSafeHandle();
Step 2: HBITMAP
to Gdiplus::Bitmap
(copied from this question)
#include <GdiPlus.h>
#include <memory>
Gdiplus::Status HBitmapToBitmap( HBITMAP source, Gdiplus::PixelFormat pixel_format, Gdiplus::Bitmap** result_out )
{
BITMAP source_info = { 0 };
if( !::GetObject( source, sizeof( source_info ), &source_info ) )
return Gdiplus::GenericError;
Gdiplus::Status s;
std::auto_ptr< Gdiplus::Bitmap > target( new Gdiplus::Bitmap( source_info.bmWidth, source_info.bmHeight, pixel_format ) );
if( !target.get() )
return Gdiplus::OutOfMemory;
if( ( s = target->GetLastStatus() ) != Gdiplus::Ok )
return s;
Gdiplus::BitmapData target_info;
Gdiplus::Rect rect( 0, 0, source_info.bmWidth, source_info.bmHeight );
s = target->LockBits( &rect, Gdiplus::ImageLockModeWrite, pixel_format, &target_info );
if( s != Gdiplus::Ok )
return s;
if( target_info.Stride != source_info.bmWidthBytes )
return Gdiplus::InvalidParameter; // pixel_format is wrong!
CopyMemory( target_info.Scan0, source_info.bmBits, source_info.bmWidthBytes * source_info.bmHeight );
s = target->UnlockBits( &target_info );
if( s != Gdiplus::Ok )
return s;
*result_out = target.release();
return Gdiplus::Ok;
}
Call this function and pass your HBITMAP
to it.
Step 3: Gdiplus::Bitmap
to cv::Mat
cv::Mat GdiPlusBitmapToCvMat(Gdiplus::Bitmap* bmp)
{
auto format = bmp->GetPixelFormat();
if (format != PixelFormat24bppRGB)
return cv::Mat();
int width = bmp->GetWidth();
int height = bmp->GetHeight();
Gdiplus::Rect rcLock(0, 0, width, height);
Gdiplus::BitmapData bmpData;
if (!bmp->LockBits(&rcLock, Gdiplus::ImageLockModeRead, format, &bmpData) == Gdiplus::Ok)
return cv::Mat();
cv::Mat mat = cv::Mat(height, width, CV_8UC3, static_cast<unsigned char*>(bmpData.Scan0), bmpData.Stride).clone();
bmp->UnlockBits(&bmpData);
return mat;
}
Pass the Gdiplus::Bitmap
that you created in last step to this function and you will get your cv:Mat
. As I said before this function just works with RGB24 pixel format.