gpt4 book ai didi

c++ - 如何将 CBitmap 转换为 cv::Mat?

转载 作者:行者123 更新时间:2023-11-28 04:48:46 30 4
gpt4 key购买 nike

如何将 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 步: CBitmapHBITMAP

HBITMAP hBmp = (HBITMAP)yourCBitmap.GetSafeHandle();

第 2 步: HBITMAPGdiplus::Bitmap(从 this 问题复制)

#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::Bitmapcv::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 像素格式。

关于c++ - 如何将 CBitmap 转换为 cv::Mat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48651448/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com