将Bitmap转换为Iplimage时出错

时间:2012-11-27 19:47:51

标签: c++ .net

我有一个必须转换为Open Cv image

的.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

0 个答案:

没有答案