[英]how to convert CBitmap to cv::Mat?
如何將 CBitmap 轉換為 cv::Mat? 也許有一些庫或其他東西......比如......
CBitmap bitmap;
bitmap.CreateBitmap(128, 128, 1, 24, someData);
cv::Mat outBitmap(128,128,someData,1,24);
但該代碼不正確。
謝謝!
還有另一種方法,您可以將CBitmap
轉換為HBitmap
,然后將HBitmap
轉換為GdiPlus::Bitmap
,然后將其轉換為cv::Mat
。 這是您可以執行的操作,但請注意,此解決方案僅適用於 RGB24 像素格式:
第 1 步: CBitmap
到HBITMAP
HBITMAP hBmp = (HBITMAP)yourCBitmap.GetSafeHandle();
第 2 步: HBITMAP
到Gdiplus::Bitmap
(從這個問題復制)
#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;
}
調用此函數並將您的HBITMAP
傳遞給它。
第 3 步: Gdiplus::Bitmap
到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;
}
將您在上一步中創建的Gdiplus::Bitmap
傳遞給此函數,您將獲得cv:Mat
。 正如我之前所說,這個函數只適用於 RGB24 像素格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.