读取图片,并通过鼠标交互,在图片上选择一块矩形区域,然后把这个矩形区域的子图像显示出来

// ROI.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "cv.h"
#include "cvaux.h"
#include "highgui.h"

IplImage* srcImg;
CvRect ROI_rect;
bool flag = false;//true表示鼠标按下状态
CvScalar color = CV_RGB(255, 0, 0);
void on_mouse(int event, int x, int y, int flags, void* param)
{
	switch (event)
	{
	case CV_EVENT_LBUTTONDOWN:
		ROI_rect.x = x;
		ROI_rect.y = y;
		cvDestroyWindow("wnd2");
		flag = true;
		break;
	case CV_EVENT_MOUSEMOVE:
		if (flag){
			ROI_rect.width = abs(ROI_rect.x - x);
			ROI_rect.height = abs(ROI_rect.y - y);
			IplImage* temp = cvCloneImage(srcImg);
			cvRectangle(temp, cvPoint(ROI_rect.x, ROI_rect.y), cvPoint(x, y), color);
			cvShowImage("wnd1", temp);
			cvReleaseImage(&temp);
		}
		break;
	case CV_EVENT_LBUTTONUP:
		if (ROI_rect.x != x && ROI_rect.y != y){
			int xx = MIN(ROI_rect.x, x);
			int yy = MIN(ROI_rect.y, y);
			cvSetImageROI(srcImg, cvRect(xx, yy, ROI_rect.width, ROI_rect.height));
			cvNamedWindow("wnd2", 1);
			cvShowImage("wnd2", srcImg);
			cvResetImageROI(srcImg);
		}
		
		flag = false;
		break;
	default:
		break;
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	srcImg = cvLoadImage("src.bmp", -1);
	cvNamedWindow("wnd1",1);
	cvShowImage("wnd1", srcImg);
	cvSetMouseCallback("wnd1", on_mouse,0);
	cvWaitKey(0);
	cvReleaseImage(&srcImg);
	cvDestroyWindow("wnd1");
	return 0;
}



你可能感兴趣的:(OpenCV)