周星星 阅读(6258) 评论(2)

找了好久,没找到相应函数,于是参照cv::imshow的源代码,搞出来一份。
(OpenCV不简洁明了,学习的成本大于2天我就觉得太不值得了,下周准备试试CxImage)

#include "highgui.h"

#ifdef _DEBUG
     #pragma comment( lib, "opencv_core220d.lib" )
     #pragma comment( lib, "opencv_highgui220d.lib" )
#else
     #pragma comment( lib, "opencv_core220.lib" )
     #pragma comment( lib, "opencv_highgui220.lib" )
#endif

 

// 此代码是从OpenCV-2.2.0 中一点点扣出来的

bool MyShowImage( const cv::Mat& img, HDC hdc, const RECT& rect )

{

     CvMat _img = img;

     const CvArr* arr = &_img;

 

     CvMat stub;

     CvMat* image = cvGetMat( arr, &stub );

 

     // 构造BITMAPINFO

     SIZE size = { image->width, image->height };

     int channels = 3;

     BITMAPINFO binfo;

     memset( &binfo, 0, sizeof(binfo));

     BITMAPINFOHEADER& bmih = binfo.bmiHeader;

     bmih.biSize = sizeof(BITMAPINFOHEADER);

     bmih.biWidth = size.cx;

     bmih.biHeight = abs(size.cy);

     bmih.biPlanes = 1;

     bmih.biBitCount = (unsigned short)(channels*8);

     bmih.biCompression = BI_RGB;

 

     void* dst_ptr = 0;

     HBITMAP hb = CreateDIBSection( hdc, &binfo, DIB_RGB_COLORS, &dst_ptr, 0, 0 );

 

     HDC windowdc = ::CreateCompatibleDC( hdc );

     SelectObject( windowdc, hb );

 

     CvMat dst;

     cvInitMatHeader( &dst, size.cy, size.cx, CV_8UC3, dst_ptr, (size.cx*channels + 3)&-4 );

 

     int origin = ((IplImage*)arr)->origin;

     cvConvertImage( image, &dst, origin==0 ? CV_CVTIMG_FLIP : 0 );

 

     // 显示

     SetStretchBltMode( hdc, COLORONCOLOR );

     //BitBlt( hdc, 0, 0, size.cx, size.cy, windowdc, 0, 0, SRCCOPY );

     StretchBlt( hdc, 0, 0, rect.right-rect.left, rect.bottom-rect.top, windowdc, 0, 0, size.cx, size.cy, SRCCOPY );

 

     return 0;

}

 

int main()

{

     const char* imagename = "1.tif";

 

     cv::Mat img = cv::imread( imagename );

     if( img.empty() || !img.data )

     {

        fprintf(stderr, "Can not load image %s\n", imagename);

        return -1;

     }

 

     //cv::namedWindow("image", CV_WINDOW_AUTOSIZE);

     //cv::imshow("image", img);

     //cv::waitKey();

 

     // 随便弄个窗体,然后显示上去

     HWND hwnd = ::GetConsoleWindow();

     RECT rect;

     GetWindowRect( hwnd, &rect );

     MyShowImage( img, ::GetWindowDC(hwnd), rect );

 

     return 0;

}


评论列表
nillwei
re: 用OpenCV显示一幅图像到指定的窗体
这段代码很有用,谢谢

发表评论
切换编辑模式