我有一个必须转换为 Open Cv 图像的 .net 位图
在 .net 方面,我正在执行以下操作:
b = new Bitmap(@"C:\Projects\samples\alfarok.jpg");
b = b.Clone(new Rectangle(0, 0, b.Width, b.Height), PixelFormat.Format24bppRgb);
Rectangle rect = new Rectangle(0, 0, b.Width, b.Height);
BitmapData bmpData = b.LockBits(rect, ImageLockMode.ReadWrite, b.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int stride = bmpData.Stride;
int numBytes = b.Width * b.Height * 3;
byte[] rgbValues = new byte[numBytes];
for (int r = 0; r < bmpData.Height; ++r)
Marshal.Copy(new IntPtr((int)ptr + stride * r), rgbValues, bmpData.Width * 3 * r, bmpData.Width * 3);
wrapper.DetectDocumentPatter(b.GetHbitmap(), rgbValues,b.Width,b.Height, numBytes);
在 umanaged 中,我收到一个 HBITMAP 句柄和字节数组。我正在尝试先构建 DIB 映像,但通常会抛出异常:std::bad_alloc at memory location 0x004ffb6c
.
BITMAP bmp;
HDC hdc = GetDC(NULL);
GetObject(b,sizeof(tagBITMAP),&bmp);
long dwcBihSize = sizeof(BITMAPINFOHEADER);
long dwSize = dwcBihSize +(2>>bmp.bmBitsPixel) * sizeof(RGBQUAD) + ((bmp.bmBitsPixel * width) * height);
LPBITMAPINFO pDIB =(LPBITMAPINFO) new BYTE[dwSize]; // check this !
pDIB->bmiHeader.biSize = dwcBihSize;
pDIB->bmiHeader.biWidth = width;
pDIB->bmiHeader.biHeight = height;
pDIB->bmiHeader.biBitCount = bmp.bmBitsPixel;
pDIB->bmiHeader.biPlanes = 1;
pDIB->bmiHeader.biCompression = BI_RGB;
pDIB->bmiHeader.biXPelsPerMeter = 1000 ;
pDIB->bmiHeader.biYPelsPerMeter = 1000;
pDIB->bmiHeader.biClrUsed = 0;
pDIB->bmiHeader.biClrImportant = 0;
LPRGBQUAD lpColors =(LPRGBQUAD)(pDIB+pDIB->bmiHeader.biSize);
SetDIBColorTable(hdc,0,2>>bmp.bmBitsPixel * sizeof(RGBQUAD),lpColors);
int dibCols = 2>>pDIB->bmiHeader.biBitCount;
void* bitArray = pDIB + pDIB->bmiHeader.biSize+dibCols *sizeof(RGBQUAD);
for(int i=0;i<dibCols;i++)
{
lpColors[i].rgbRed=0;
lpColors[i].rgbBlue=0;
lpColors[i].rgbGreen=0;
lpColors[i].rgbReserved=0;
}
SetDIBColorTable(hdc,0,dibCols,lpColors);
int depth =bmp.bmBitsPixel == 1 ? IPL_DEPTH_1U : IPL_DEPTH_8U;
int nChannels = 3;
//IplImage* image= cvCreateImage(cvSize(width,height),depth,3);
GetDIBits(hdc,b,0,height,bitArray,pDIB,DIB_RGB_COLORS);
//image->imageData = (char*)bitArray;
//memcpy(image->imageData,(char*)(bmp.bmBits),bmp.bmHeight*bmp.bmWidth*3);
//cvSaveImage("c:\img.jpg",image);
我做对了,还是有更合适的方法?为什么会std::bad_alloc at memory location 0x004ffb6c
抛出错误?