[OpenCV study Note 3] development environment of MFC + OpenCV Based on OpenCV GUI

Source: Internet
Author: User
Tags exit in

Single-document program VC6.0 + OpenCV1.0

SkySeraph Jun.25th 2010 HQU

Zgzhaobo@gmail.com 452728574

Steps:

1. Create an sdi mfc project and a single document. It is best to choose use MFC As a static library (to prevent the use of opencv Memory leakage in MFC)

2. added the OpenCV library to support [header files and library files]: Add cxcore to the menu Project> Settings> Link> Input> Object/library modules. lib cv. lib ml. lib cvaux. lib highgui. lib cvcam. lib

3. Add the header file of HighGui. h at the beginning of the Doc class, and add a variable CImage m_image. [In the definition, we recommend that you use public or VC]

4. Add two virtual functions to open and save files: OnOpenDocument and OnSaveDocument are as follows:

Bool csdi OpenCVDoc: OnOpenDocument (LPCTSTR lpszPathName ){
If (! CDocument: OnOpenDocument (lpszPathName) return FALSE;
// TODO: Add your specialized creation code here
M_image.Load (lpszPathName );
Return TRUE;
}

Bool csdi OpenCVDoc: OnSaveDocument (LPCTSTR lpszPathName ){
// TODO: Add your specialized code here and/or call the base class
M_image.Save (lpszPathName );
Return TRUE;

// Return CDocument: OnSaveDocument (lpszPathName); // cause: the size of the saved image changes to 0.
}

5. Add a display function to the View class

Void CSDI_OpenCVView: OnDraw (CDC * pDC)
{
CSDI_OpenCVDoc * pDoc = GetDocument ();
ASSERT_VALID (pDoc );
// TODO: add draw code for native data here
CImage & img = pDoc-> m_image; // The CImage class is actually the CvvImage class and can be directly replaced

CRect r;
GetClientRect (& r );
Img. DrawToHDC (pDC-> GetSafeHdc (), r );
}

6. Add a menu to enable the system to use the "quick" command.

① Modify m_image.Load (lpszPathName) to m_image.Load (lpszPathName, 0). // forcibly convert and read the image to an 8-bit depth grayscale image.

② Add the ImageProcessing menu and the sub-menu 'ecec'. In the Doc class, add the COMMAND Message response function whose ID number is idm_'ec'. The Code is as follows:

Void CSDI_OpenCVDoc: OnCanny () // menu processing function

{

// TODO: Add your command handler code here

IplImage * img;

Img = m_image.GetImage (); // A IplImage * pointer is returned by the CImage class because: IplImage * GetImage () {return m_img ;};

Cvkan (img, img, 50,150, 3 );

UpdateAllViews (NULL );

}

Description

  1. [Original] Quick OpenCV application tutorial in MFC
  2. The picture is too large to be placed in the view. For more information, see feixiaolin's post opencv data read/write operations + image noise + OpenCV source code under MFC and how to insert a scroll bar.
  3. A brief explanation of the OpenCV plotting function DrawToHDC
  4. In the opencv1.0 version, the system uses the previously introduced method of "kan", and there is an error that the single-channel image cannot be opened. for specific reasons, see here. This is mainly caused by a bug in opencv1.0. Cause
  5. If it is used in opencv 1.1, the MFC program may not exit. For the solution, check that the program cannot exit normally.Solution: If you cannot exit in 1.1, You Need To comment out the # define HAVE_VIDEOINPUT 1 Statement in _ highgui. h In 1.1, recompile the Highgui project of OpenCv, and generate Highgui. lib again.
  6. Note that the CImage is actually the CvvImage which can be directly replaced.
  7. For details about the OLE error dialog box, refer to the Forum on how to solve the OLE problem.

References

Rapid Application of OpenCV in http://www.opencv.org.cn/index.php/MFC%E4%B8%AD%E5%BF% AB %E9%80%9F%E5%BA%94%E7%94%A8OpenCV MFC

Http://www.opencv.org.cn/forum/viewtopic.php? F = 1 & t = 4932 & p = 18215 # p18136 related questions

Dialog Box program VC6.0 + OpenCV1.0

SkySeraph Oct.28th 2010 HQU

Zgzhaobo@gmail.com 452728574

Latest Modified Date: Oct.29th 2010 HQU

Steps:

1. Create a project: MFC_OpenCV_Dlg dialog box

2. added the OpenCV library to support [header files and library files]

Choose Project> Settings> Link> Input> Object/library modules and add cxcore. lib cv. lib ml. lib cvaux. lib highgui. lib cvcam. lib.

3. Add header files and global macros.

Add the following code under # include "resource. h" starting with CMFC_OpenCV_Dlg.h

# Include "cv. h"

# Include "HighGUI. h"

# Define IMAGE_WIDTH 512 // assume that the image read and displayed is a 512*512 (pixel) color image. You can modify the image on your own.

# Define IMAGE_HEIGHT 512

# Define IMAGE_CHANNELS 3

4. Add the IplImage * variable and initialize the variable and release the memory.

Right-click CMFC_OpenCV_DlgDlg and add an IplImage * type variable TheImage,

Double-click OnInitDialog under the class and Add TheImage initialization code under "// TODO: Add extra initialization here:

CvSize ImgSize;
ImgSize. height = IMAGE_HEIGHT;
ImgSize. width = IMAGE_WIDTH;
TheImage = cvCreateImage (ImgSize, IPL_DEPTH_8U, IMAGE_CHANNELS );

Double-click InitInstance in the member list under CMFC_OpenCV_DlgApp,

In the two "// TODO: Place code here to handle when the dialog is ..." Add the following:

CvReleaseImage (& dlg. TheImage); // release the memory

When you press "OK" or "Cancel", the memory occupied by TheImage is released. // Press OK or Cancel to call InitInstance and check the source code.

5. redraw windows

In CMFC_OpenCV_DlgDlg, double-click OnPaint in if (IsIconic ())... Add the following code to the else to redraw the window:

CDialog: OnPaint (); // redraw dialog box
CDialog: UpdateWindow (); // update the windows window. If you do not call this operation, the image is displayed with a problem.
ShowImage (TheImage, IDC_ImgShowCtrl); // repeated plot Function

6. add controls and member functions

1 Edit

Associated variable m_Path

1 picture

ID: IDC_ImgShowCtrl

 

 

Four buttons

ID: IDC_ChooseFile is used to select an image and save it to m_Path.

ID: IDC_ShowImage: used to display the image in the m_Path path

ID: IDC_EdgeDetect edge detection test

ID: IDC_Test extension/custom

Message response function: OnChooseFile ()

Message response function: OnShowImage ()

Message response function: OnEdgeDetect ()

Message response function: OnTest ()

Let's just see

In CMFC_OpenCV_DlgDlg, add two member functions void ShowImage (IplImage * img, uint id) and void ResizeImage (IplImage * img). The Code is as follows:

Void CMFC_OpenCV_DlgDlg: ShowImage (IplImage * img, uint id) // ID is the ID of the Picture Control.

{

// Obtain the DC of the display control

CDC * pDC = GetDlgItem (ID)-> GetDC ();

// Obtain the HDC (device handle) for plotting

HDC hDC = pDC-> GetSafeHdc ();

CRect rect;

GetDlgItem (ID)-> GetClientRect (& rect );

/*

CBrush brush (RGB (255,255,255 ));

PDC-> FillRect (& rect, & brush );

*/

// Obtain the width and height of the image control.

Int rw = rect. right-rect. left;

Int rh = rect. bottom-rect. top;

// Read the width and height of the image

Int iw = img-> width;

Int ih = img-> height;

// Make the image display position right in the middle of the control

Int tx = (int) (rw-iw)/2;

Int ty = (int) (rh-ih)/2;

SetRect (rect, tx, ty, tx + iw, ty + ih );//

// Copy the image

CvvImage cimg;

Cimg. CopyOf (img );

// Draw the image to the specified area of the display control

Cimg. DrawToHDC (hDC, & rect );

ReleaseDC (pDC );

}

Void CMFC_OpenCV_DlgDlg: ResizeImage (IplImage * img)

{

// Image size

Int width = (int) IMAGE_WIDTH; // width

Int height = (int) IMAGE_HEIGHT; // height

Float max_w_h = (float) (IMAGE_WIDTH> IMAGE_HEIGHT )? IMAGE_WIDTH: IMAGE_HEIGHT;

// Read the width and height of the image

Int w = img-> width;

Int h = img-> height; // find out who is better at width and high school.

Int max = (w> h )? W: h;

// Calculate the proportional factor required to scale the image to the TheImage area.

// Float scale = (float) max/512.0f );

Float scale = (float) max/max_w_h );

// The width and height of the scaled Image

Int nw = (int) (w/scale );

Int nh = (int) (h/scale );

// To save the scaled image to the center of TheImage, calculate the expected coordinate value of the image in the upper left corner of TheImage.

Int tlx = (nw> nh )? 0: (int) (width-nw)/2;

Int tly = (nw> nh )? (Int) (height-nh)/2: 0;

/* // Ensure that the image is a 3-channel image

IplImage * temp = 0; // defines the transit image pointer

Temp = cvCreateImage (cvGetSize (img), img-> depth, 3 );

If (1 = img-> nChannels) // if it is a single-channel image, convert it to a 3-Channel

{

CvConvertImage (img, temp, CV_CVTIMG_SWAP_RB); // P70

// CV_CVTIMG_FLIP (flip vertically) CV_CVTIMG_SWAP_RB (swap the R and B channels)

}

Else if (3 = img-> nChannels)

{

Temp = cvCloneImage (img );

}

Else AfxMessageBox (_ T ("channel wrong on function show picture! "));

*/

// Set the ROI of TheImage to save the image to img.

CvSetImageROI (TheImage, cvRect (tlx, tly, nw, nh); // P87

// Scale the image img and add it to TheImage

CvResize (img, TheImage, CV_INTER_AREA); // P255

// Reset TheImage's ROI to read the next image

CvResetImageROI (TheImage );

// CvReleaseImage (& temp); // release the intermediate image pointer

}

Void CMFC_OpenCV_DlgDlg: OnChooseFile ()

{

// TODO: Add your control notification handler code here

CFileDialog dlg (

TRUE, NULL, NULL,

OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY,

_ T ("All Files (*. *) | *. * |"), AfxGetMainWnd ()

); // Option image conventions

Dlg. m_ofn.lpstrTitle = _ T ("Open Image"); // name of the title in the Open file dialog box

If (dlg. DoModal ()! = IDOK) // determine whether to obtain the image

Return;

M_Path.SetWindowText (dlg. GetPathName (); // obtain the image path

}

Void CMFC_OpenCV_DlgDlg: OnShowImage ()

{

// TODO: Add your control notification handler code here

CString mPath;

M_Path.GetWindowText (mPath );

If (mPath = "")

{

AfxMessageBox (_ T ("file path is empty, please choose file! "));

Return;

}

IplImage * ipl = cvLoadImage (mPath, CV_LOAD_IMAGE_COLOR); // read the image and cache it to a local variable ipl.

If (! Ipl) // determine whether the image is loaded successfully

Return;

If (TheImage) // clears the data of the previous image.

CvZero (TheImage );

ResizeImage (ipl); // scale the image to make it equal to 512 in width or height, and then copy it to TheImage.

ShowImage (TheImage, IDC_ImgShowCtrl); // call the image display function

CvReleaseImage (& ipl); // release the memory occupied by ipl

}

Void CMFC_OpenCV_DlgDlg: OnEdgeDetect ()

{

// TODO: Add your control notification handler code here

CString mPath;

M_Path.GetWindowText (mPath );

IplImage * gray = 0, * edge = 0;

Gray = cvCreateImage (cvSize (IMAGE_WIDTH, IMAGE_HEIGHT), IPL_DEPTH_8U, 1 );

Edge = cvCreateImage (cvSize (IMAGE_WIDTH, IMAGE_HEIGHT), IPL_DEPTH_8U, 1 );

CvCvtColor (TheImage, gray, CV_BGR2GRAY );

CvCanny (gray, edge, 30,100, 3 );

CvCvtColor (edge, TheImage, CV_GRAY2BGR );

If (! TheImage)

{

AfxMessageBox (_ T ("PictureCtrl is empty, please choose Pictrue! "));

Return;

}

ShowImage (TheImage, IDC_ImgShowCtrl); // call the image display function

CvReleaseImage (& gray );

CvReleaseImage (& edge );

}

Effect:

You can't get the video clip... Who told me how to insert a video clip? % >_< % ^_^

References

Book: OpenCV tutorial-Basics

Http://blog.csdn.net/chenyusiyuan/archive/2009/10/29/4744097.aspx morning Yu Si Yuan OpenCV learning notes 9

Http://www.site.uottawa.ca /~ Laganier/tutorial/opencv + directshow/cvision.htm A step-by-step guide to the use of Microsoft Visual C ++ and the Intel OpenCV library

Author: SKySeraph

Email/GTalk: zgzhaobo@gmail.com QQ: 452728574

From: http://www.cnblogs.com/skyseraph/

The copyright of this article is shared by the author and the blog. You are welcome to repost this article. However, you must keep this statement without the author's consent and provide the original article connection clearly on the article page. Please respect the author's Labor achievements.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.