⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ct1dlg.cpp

📁 detect rectangle by open cv.
💻 CPP
字号:
// ct1Dlg.cpp : implementation file
//

#include "stdafx.h"
#include "ct1.h"
#include "ct1Dlg.h"


#include "stdio.h"
#include "cv.h"
#include"highgui.h"
#include"cxtypes.h"
#include"math.h"
#include"string.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


int thresh=50;

double angle(CvPoint* pt1,CvPoint* pt2,CvPoint* pt0);
void drawSquares(IplImage*img,CvSeq*squares);
IplImage* img = 0;
IplImage* img0 = 0;
CvMemStorage* storage = 0;
CvPoint pt[4];
const char* wndname = "Square Detection Demo";

// helper function:
// finds a cosine of angle between vectors
// from pt0->pt1 and from pt0->pt2 

/////////////////////////////////////////////////////////////////////////////
// CCt1Dlg dialog

CCt1Dlg::CCt1Dlg(CWnd* pParent /*=NULL*/)
	: CDialog(CCt1Dlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CCt1Dlg)
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CCt1Dlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CCt1Dlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CCt1Dlg, CDialog)
	//{{AFX_MSG_MAP(CCt1Dlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON2, OnButton2)
	ON_BN_CLICKED(IDC_BUTTON3, OnButton3)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CCt1Dlg message handlers

BOOL CCt1Dlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CCt1Dlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CCt1Dlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

//void main( char *argv )
void CCt1Dlg::OnButton2() 
{
	
    IplImage* img = cvLoadImage( "anh1.jpg" );
    cvNamedWindow( "Example1", CV_WINDOW_AUTOSIZE );
	cvShowImage( "Example1", img );
//	cvShowImage( "Example2", gray );
	cvWaitKey(0);
	cvReleaseImage( &img );
	cvDestroyWindow( "Example1" );
}

/*void CCt1Dlg::OnButton2() 
{
	main("anh1.jpg");
	
}*/	

//tinh goc giua cac diem giao bang ham angle


double angle(CvPoint* pt1,CvPoint* pt2,CvPoint* pt0)
{
	double dx1=pt1->x-pt0->x;
	double dy1=pt1->y-pt0->y;
	double dx2=pt2->x-pt0->x;
	double dy2=pt2->y-pt0->y;
	return(dx1*dx2+dy1*dy2)/sqrt((dx1*dx1+dy1*dy1)*(dx2*dx2+dy2*dy2)+1e-10);
}


void drawSquares( IplImage* img, CvSeq* squares )
{
    CvSeqReader reader;
    IplImage* cpy = cvCloneImage( img );
    int i;
    
    // initialize reader of the sequence
    cvStartReadSeq( squares, &reader, 0 );
    
    // read 4 sequence elements at a time (all
//vertices of a square)
    for( i = 0; i < squares->total; i += 4 )
    {
        CvPoint* rect = pt;
        int count = 4;
        
        // read 4 vertices
        memcpy( pt, reader.ptr, squares->elem_size );
        CV_NEXT_SEQ_ELEM( squares->elem_size, reader);
        memcpy( pt + 1, reader.ptr, squares->elem_size);
        CV_NEXT_SEQ_ELEM( squares->elem_size, reader);
        memcpy( pt + 2, reader.ptr, squares->elem_size);
        CV_NEXT_SEQ_ELEM( squares->elem_size, reader);
        memcpy( pt + 3, reader.ptr, squares->elem_size);
        CV_NEXT_SEQ_ELEM( squares->elem_size, reader);
        
        //printf("value of the rect is %d\n",*squares);
// draw the square as a closed polyline
/*//%%%%%%%%%%%%%%%%%changed portion of code%%%%%%%%%%%%%%%%%%%%%%%%%% */
	cvSetImageROI(cpy, cvRect(pt[1].x, pt[1].y,abs(pt[0].x-pt[1].x), abs(pt[3].y-pt[0].y))); 
	cvShowImage(wndname, cpy);
	cvWaitKey(0);
	cvSaveImage("test.jpg", cpy);
	cvResetImageROI(cpy);
	cvReleaseImage( &cpy );
	}
// show the resultant image
	cvShowImage( wndname, cpy );
	cvReleaseImage( &cpy );
}

CvSeq*findSquares(IplImage*img,CvMemStorage*storage)
{
	CvSeq*contours;
	int i,c,l,N=11;
	CvSize sz=cvSize(img->width& -2,img->height& -2);
	IplImage* timg=cvCloneImage(img);//tao 1 anh giong img
	IplImage* gray=cvCreateImage(sz,8,1);
	IplImage* pyr=cvCreateImage(cvSize(sz.width/2,sz.height/2),8,3);
	IplImage* tgray;
	CvSeq* result;
	double s,t;
	CvSeq* squares=cvCreateSeq(0,sizeof(CvSeq),sizeof(CvPoint),storage);
		cvSetImageROI(timg,cvRect(0,0,sz.width,sz.height));//Using ImageROI to increment all of the pixels in a region (continued)
		cvPyrDown(timg,pyr,7);
		cvPyrUp(pyr,timg,7);
		tgray=cvCreateImage(sz,8,1);
		for(c=0;c<3;c++)
		{
			cvSetImageCOI(timg,c+1);
			cvCopy(timg,tgray,0);
				for(l=0;l<N;l++)
				{
					if(l==0)
					{
						cvCanny(tgray,gray,0,thresh,5);//loc nhieu
						cvDilate(gray,gray,0,1);

					}
					else
					{
						cvThreshold(tgray,gray,(l+1)*255/N,255,CV_THRESH_BINARY);
					}//Tim tat ca cac duong vien
			cvFindContours(gray,storage,&contours,sizeof(CvContour),CV_RETR_LIST,CV_CHAIN_APPROX_SIMPLE,cvPoint(0,0));
		while(contours)
		{
			result=cvApproxPoly(contours,sizeof(CvContour),storage,CV_POLY_APPROX_DP,cvContourPerimeter(contours)*0.02,0);

			if(result->total==4&& fabs(cvContourArea(result,CV_WHOLE_SEQ))>1000&& cvCheckContourConvexity(result))
			{
				s=0;
				for(i=0;i<5;i++)
				{
					if(i>=2)
					{
						t=fabs(angle((CvPoint*)cvGetSeqElem(result,i),(CvPoint*)cvGetSeqElem(result,i-2),
						(CvPoint*)cvGetSeqElem(result,i-1)));
						s=s>t?s:t;
					}
				}
			
				if(s<0.3)
					for(i=0;i<4;i++)
					cvSeqPush(squares,(CvPoint*)cvGetSeqElem(result,i));
			}
			contours=contours->h_next;
			}
		}
	  }
	  
		//cvResetImageROI(timg);
		cvReleaseImage(&gray);
		cvReleaseImage(&pyr);
		cvReleaseImage(&tgray);
		cvReleaseImage(&timg);
	  return squares;
	  }

//void main1( char *argv )
void CCt1Dlg::OnButton3() 
{

//	int i, c;
	
//	 CvSeq*squares;
	 

//	IplImage* cannyImg; // gray image for the canny edge detection
	
//	IplImage* temp1;
    IplImage* img = cvLoadImage( "anh1.jpg");// original image
	CvMemStorage* storage = cvCreateMemStorage();
/*	for( i = 0; names[i] != 0; i++ )
	{
		img0 = cvLoadImage( names[i], 1 );
		if( !img0 )
		{
			printf("Couldn't load %s\n", names[i] );
			continue;
		}

		img = cvCloneImage( img0 );


    cvNamedWindow( "Example2", CV_WINDOW_AUTOSIZE );
//	cvShowImage( "Example2", img );
//	IplImage* gray = cvCreateImage(cvGetSize(img),8,1);// gray image for the conversion of the original image
*/
	drawSquares( img, findSquares( img,storage ));
	//storage = cvCreateMemStorage(0);

//	cvCvtColor(img,gray,CV_BGR2GRAY);
//	cvConvertImage(img,gray,CV_CVTIMG_FLIP);//quay 180 do dao nguoc anh

	//cannyImg = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1);//tao 1 bien chua anh canny
	// canny edge detection
	//cvCanny(gray, cannyImg, 50, 150, 3);//chuyen anh canny tu anh xam 




	
//	drawSquares(img1,storageThuy);

	//cvShowImage( "Example2", img);//hien anh ra khung Example2

//	cvSaveImage("temp.bmp", cannyImg);
	cvWaitKey(0);
	cvReleaseImage( &img);	
	cvClearMemStorage( storage );
	//cvDestroyWindow( "Example2" );
}


//void CCt1Dlg::OnButton3() 
//{
	// TODO: Add your control notification handler code here
	
//	main1("anh1.jpg");
	
//	void drawSquares(temp,CvSeq*squares);
//}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -