将opencv图像转换为gdi位图不起作用取决于图像大小 [英] Converting opencv image to gdi bitmap doesn't work depends on image size
问题描述
我有这个代码将opencv图像转换为位图:
I have this code that converts an opencv image to a bitmap:
void processimage(MAT imageData)
{
Gdiplus::Bitmap bitmap(imageData.cols,imageData.rows,stride, PixelFormat24bppRGB,imageData.data);
// do some work with bitmap
}
它当图像大小为2748 X 3664时效果很好。但是我想要处理尺寸为1374 X 1832的图像,它不起作用。
It is working well when the size of image is 2748 X 3664. But I am tring to process an image wth size 1374 X 1832, it doesn't work.
错误是无效的参数(2)。
The error is invalid parameter(2).
我检查过并确认:
in 2748 * 3664:
in 2748 *3664:
- cols = 2748
- rows = 3664
- stride = 8244
- 图片继续。
- cols=2748
- rows=3664
- stride= 8244
- image is continues.
in 1374 X 1832
in 1374 X 1832
- cols = 1374
- rows = 1832
- stride = 4122
- 图片继续。
- cols=1374
- rows=1832
- stride= 4122
- image is continues.
所以一切看起来都对我不错,但它会产生错误。
So everything seems correct to me, but it generate error.
问题是什么?我该如何解决?
What is the problem and how can I fix it?
根据答案解释了为什么我无法创建位图。我终于以这种方式实现了它:
Based on answer which explained why I can not create bitmap. I finally implemented it in this way:
Mat newImage;
cvtColor(imageData, newImage, CV_BGR2BGRA);
Gdiplus::Bitmap bitmap(newImage.cols,newImage.rows,newImage.step1(), PixelFormat32bppRGB,newImage.data);
如此有效,我将输入图像转换为每像素4个字节,然后使用将其转换为位图。
So effectively, I convert input image to a 4 byte per pixel and then use the convert it to bitmap.
Roger Rowland 的所有信用额度。
推荐答案
我认为问题是BMP格式的步幅必须是4的倍数。
I think the problem is that a BMP format must have a stride that is a multiple of 4.
您的放大图像的步幅为8244 ,这是有效的(8244/4 = 2061),但你的小图像的步幅为4122,而不是(4122/4 = 1030.5)。
Your larger image has a stride of 8244, which is valid (8244/4 = 2061) but your smaller image has a stride of 4122, which is not (4122/4 = 1030.5).
as 它在MSDN上说 stride 参数(我强调):
As it says on MSDN for the stride parameter (with my emphasis):
整数,指定一个$开头之间的字节偏移量b $ b扫描线和下一个。这通常(但不一定)像素格式的
字节数(例如,每
像素16位的2)乘以位图的宽度。传递给此
参数的值必须是四的倍数。
假设您的步幅是的,我认为你唯一的选择是逐行复制它。所以,比如:
Assuming your stride is correct, I think you're only option is to copy it row by row. So, something like:
- 伟大的
Gdiplus :: Bitmap
所需大小和格式 - 使用 LockBits 获取位图像素数据。
- 一次复制一行OpenCV图像。
- 致电 UnlockBits 发布位图数据。
- Great a
Gdiplus::Bitmap
of the required size and format - Use LockBits to get the bitmap pixel data.
- Copy the OpenCV image one row at a time.
- Call UnlockBits to release the bitmap data.
这篇关于将opencv图像转换为gdi位图不起作用取决于图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!