用setmousecallback在圖片上畫矩形框--鼠標事件

// substr.cpp : 定義控制檯應用程序的入口點。
//

#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>
#include <OpenCV245.h>

using namespace std;
using namespace cv;

Rect select;
bool select_flag = false;
Mat img,showImg,selectImg;

void onMouse(int event,int x,int y,int flags,void*param)
{
	Point p1,p2;
	if(event==CV_EVENT_LBUTTONDOWN)
	{
		select.x = x;
		select.y = y;
		select_flag = true;
	}
	else if(select_flag &&event == CV_EVENT_MOUSEMOVE)
	{
		img.copyTo(showImg);
		p1 = Point(select.x,select.y);
		p2 = Point(x,y);	
    	rectangle(showImg,p1,p2,Scalar(0,255,0),2);
		imshow("img",showImg);
	}
	else if(select_flag && event == CV_EVENT_LBUTTONUP)
	{
		//顯示框出的圖
		Rect roi = Rect(Point(select.x,select.y),Point(x,y));
		if(roi.width && roi.height)//點一下時會報錯
		{
			Mat roiImg = img(roi);
			imshow("roi",roiImg);
			//waitKey(0);
		}
		select_flag = false;		
	}	
}

//框圖超過畫面時會報錯
int _tmain(int argc, _TCHAR* argv[])
{
    img = imread("C:\\Users\\Ma Ruihuan\\Desktop\\Lena.jpg",1);
	showImg = img.clone();
	//showImg = img;
	select.x=select.y = 0;
	namedWindow("img");
	imshow("img",showImg);
	setMouseCallback("img",onMouse,0);
	waitKey(0);
	system("pause");
	return 0;
}


setMouseCallback()的用法見http://blog.csdn.net/maryhuan/article/details/13017697

本文參考自http://blog.csdn.net/yangtrees/article/details/7573919

http://blog.csdn.net/skeeee/article/details/16844937

發佈了28 篇原創文章 · 獲贊 11 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章