Skip to content

Instantly share code, notes, and snippets.

@sailfish009
Created April 2, 2019 08:46
Show Gist options
  • Save sailfish009/71c243e07231bffef2c20b16ebb01bca to your computer and use it in GitHub Desktop.
Save sailfish009/71c243e07231bffef2c20b16ebb01bca to your computer and use it in GitHub Desktop.
https://gudanrkim.blogspot.com/2014/11/how-to-display-opencv-cvmat-to-mfc.html?_escaped_fragment_
void cvShowImageHWND(HWND hwnd, const CvArr* arr)
{
SIZE size = { 0, 0 };
int channels = 0;
void* dst_ptr = 0;
const int channels0 = 3;
int origin = 0;
CvMat stub, dst, *image;
bool changed_size = false; // philipg
if (!hwnd || !arr)
return; // keep silence here.
if (CV_IS_IMAGE_HDR(arr))
origin = ((IplImage*)arr)->origin;
image = cvGetMat(arr, &stub);
HDC hdc = ::GetDC(hwnd);
BITMAP bmp;
GdiFlush();
HGDIOBJ h = GetCurrentObject(hdc, OBJ_BITMAP);
if (h == NULL)return;
if (::GetObject(h, sizeof(bmp), &bmp) == 0) return;
size.cx = abs(bmp.bmWidth);
size.cy = abs(bmp.bmHeight);
channels = bmp.bmBitsPixel / 8;
dst_ptr = bmp.bmBits;
if (size.cx != image->width || size.cy != image->height || channels != channels0)
{
changed_size = true;
uchar buffer[sizeof(BITMAPINFO)+255 * sizeof(RGBQUAD)];
BITMAPINFO* binfo = (BITMAPINFO*)buffer;
DeleteObject(SelectObject(hdc, h));
size.cx = image->width;
size.cy = image->height;
channels = channels0;
FillBitmapInfo(binfo, size.cx, size.cy, channels * 8, 1);
HBITMAP hbitmap = CreateDIBSection(hdc, binfo, DIB_RGB_COLORS, &dst_ptr, 0, 0);
h = SelectObject(hdc, hbitmap);
cvInitMatHeader(&dst, size.cy, size.cx, CV_8UC3, dst_ptr, (size.cx * channels + 3) & -4);
cvConvertImage(image, &dst, origin == 0 ? CV_CVTIMG_FLIP : 0);
RECT rect;
GetClientRect(hwnd, &rect);
StretchDIBits(hdc,
0, 0, rect.right, rect.bottom, 0, 0, image->width, image->height,
dst_ptr, binfo, DIB_RGB_COLORS, SRCCOPY);
DeleteObject(hbitmap);
}
InvalidateRect(hwnd, 0, 0);
::ReleaseDC(hwnd, hdc);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment