views:

155

answers:

4

Hi,

I have myself a handle to a bitmap, in C++, on Windows:

HBITMAP hBitmap;

On this image I want to do some Image Recognition, pattern analysis, that sort of thing. In my studies at University, I have done this in Matlab, it is quite easy to get at the individual pixels based on their position, but I have no idea how to do this in C++ under Windows - I haven't really been able to understand what I have read so far. I have seen some references to a nice looking Bitmap class that lets you setPixel() and getPixel() and that sort of thing, but I think this is with .net .

How should I go about turning my HBITMAP into something I can play with easily? I need to be able to get at the RGBA information. Are there libraries that allow me to work with the data without having to learn about DCs and BitBlt and that sort of thing?

+5  A: 

You can use OpenCV library as a full image processing tool.

You can also use MFC's CImage or VCL's TBitmap just to extract pixel values from HBITMAP.

Janusz Lenar
This library looks like it could be incredibly useful for me, for more than just the problem in this question.
Oliver
+1  A: 

Try this using GetPixel from GDI:

COLORREF GetBitmapBixel(HBITMAP hBitmap, int xPos, int yPos)
{
  HDC hDC = GetDC(NULL);
  HDC hMemDC = CreateCompatibleDC(hDC);
  COLORREF pixelColor;
  HBITMAP hOld = (HBITMAP)SelectObject(hMemDC, hBitmap);

  pixelColor = ::GetPixel(hMemDC, xPos, yPos);

  SelectObject(hMemDC, hOld);
  DeleteDC(hMemDC);
  ReleaseDC(NULL, hDC);

  return pixelColor;
}
mjmarsh
Everything above is 'straight' GDI not GDI+.
Eugen Constantin Dinca
Thanks, edited it to reflect that
mjmarsh
How is the performance of GetPixel in GDI? I know it is atrocious in GDI+, and any serious image processing will likely be intense enough to require direct memory access. It's really not that hard or error prone to loop through the bits of an image.
Ed Swangren
+3  A: 
Gdiplus::Bitmap* pBitmap = Gdiplus::Bitmap::FromHBITMAP( hBitmap, NULL );
Gdiplus::Color pixel_color;
pBitmap->GetPixel( x, y, &pixel_color ); // read pixel at x,y into pixel_color
// ...
delete pBitmap; // do not forget to delete
Kirill V. Lyadvinsky
+2  A: 

With:

DIBSECTION ds;
::GetObject(hbmp/*your HBITMAP*/, sizeof DIBSECTION, &ds);

you will get all you need (including pixel format and pixel buffer adress) in ds.dsBm. see the doc
cheers, AR

Alain Rist