Programming/OpenCV

DC -> IplImage로 전환

매직블럭 2013. 8. 8. 13:49


화면에 무언갈 띄운다던가. 선을그리고 텍스트를 그리고


사각형을 그리고 원을그리고 이미지를 올리고 뭐 등등 이러한 여러가지 작업들을


DC 에 벌려 놓은 다음 그 DC를 파일로 저장 한다거나 IplImage로 혹은 cv::Mat 으로 


가져와서 다른 작업을 하고싶다거나.. 할때 변환을 해주는 함수.


해당 DC의 CDC 를 파라미터로 넘겨주면 해당 DC를 IplImage로 반환 해준다.




이렇게 사각형 박스안에 그림을 그리고 나서 


DCtoIplImage 함수를 불러주면 



뿅 하고 IplImage를 반환 해준다.


이를 확인하기 위해 NamedWindow를 통해 화면에 나타낸 것.



이런 작업을 위한 함수.



IplImage* CtestDlg::DCtoIplImage(CDC* pDC)

{

CRect rect;

    pDC->GetWindow()->GetClientRect(rect);

    int cx = rect.right - rect.left;

    int cy = rect.bottom - rect.top;

    if(cx <= 0 || cy <= 0) return NULL;

    HDC hMemDC;

    hMemDC = CreateCompatibleDC(pDC->m_hDC);

    BITMAPINFO    bmi;

    BITMAPINFOHEADER* bmih = &(bmi.bmiHeader);

    LPVOID        pBits;

    HBITMAP        hBitmap;

    ZeroMemory(bmih, sizeof(BITMAPINFOHEADER));

    bmih->biSize        = sizeof(BITMAPINFOHEADER);

    bmih->biBitCount    = 24;

    bmih->biWidth        = cx;

    bmih->biHeight        = cy;

    bmih->biPlanes        = 1;

    hBitmap = CreateDIBSection(pDC->m_hDC, &bmi, DIB_RGB_COLORS, (LPVOID*)&pBits, NULL, 0);

    SelectObject(hMemDC, hBitmap);

    BitBlt(hMemDC, 0, 0, cx, cy, pDC->m_hDC, rect.left, rect.top, SRCCOPY);

    DeleteDC(hMemDC);

   

    hMemDC = NULL;

    bool bMustRelease = false;

    const int nDepth = IPL_DEPTH_8U;

    const int nChannels = 3;

    

    if(hMemDC == NULL)

    {

        hMemDC = ::GetDC(NULL);

        bMustRelease = true;

    }

    IplImage* img = NULL;

    if(GetDIBits(hMemDC, hBitmap, 0, 0, NULL, &bmi, DIB_RGB_COLORS))

    {

        int nHeight = (bmih->biHeight > 0) ? bmih->biHeight : -bmih->biHeight;

        img = cvCreateImage(cvSize(bmih->biWidth, nHeight), nDepth, nChannels);

        img->origin = (bmih->biHeight > 0);

        bmih->biBitCount = (WORD)(img->nChannels * 8);

        bmih->biCompression = BI_RGB;

        GetDIBits(hMemDC, hBitmap, 0, nHeight, img->imageData, &bmi, DIB_RGB_COLORS);

    }

    if(bMustRelease) ::ReleaseDC(NULL, hMemDC);


    DeleteObject(hBitmap);

    return img;

}