<span style="font-size:12px;">/* License:
Oct. 3, 2008
Right to use this code in any way you want without warrenty, support or any guarentee of it working.BOOK: It would be nice if you cited it:
Learning OpenCV: Computer Vision with the OpenCV Library
by Gary Bradski and Adrian Kaehler
Published by O'Reilly Media, October 3, 2008
*/
#include <cv.h>
#include <highgui.h>// 定義初始化鼠標事件的回調函數.
void my_mouse_callback(int event, int x, int y, int flags, void* param);CvRect box;
bool drawing_box = false;// 在一個圖像上畫一個框的子程序
void draw_box(IplImage* img, CvRect rect) {? //? cvRectangle? 函數功能: 通過對角線上的兩個頂點繪制簡單、指定粗細或者帶填充的矩形cvRectangle(img,cvPoint(box.x, box.y),cvPoint(box.x + box.width, box.y + box.height),cvScalar(0xff, 0x00, 0x00)??? /* red */);}int main(int argc, char* argv[])
{box = cvRect(-1, -1, 0, 0);IplImage* image = cvCreateImage(cvSize(700, 700),IPL_DEPTH_8U,3);cvZero(image);IplImage* temp = cvCloneImage(image);cvNamedWindow("Box Example");// 在OPENCV中通過 cvSetMouseCallback 函數注冊回調函數 ,指定鼠標事件的回調函數。// 鼠標回調函數的參數,必須滿足一定的格式要求: void cvmousecallback( int event, int x, int y, int flags, void* param);// 第一個參數為鼠標事件類型,第二個第三個參數為事件發生時鼠標位置坐標,值得指出的是這些坐標是相對于像素位置的坐標,與窗口大小無關。cvSetMouseCallback("Box Example",my_mouse_callback,(void*)image);while (1) {cvCopyImage(image, temp);// cvcopy : 拷貝一個數組給另一個數組 if (drawing_box) draw_box(temp, box);cvShowImage("Box Example", temp);if (cvWaitKey(15) == 27) break;}// 退出程序時,釋放資源cvReleaseImage(&image);cvReleaseImage(&temp);cvDestroyWindow("Box Example");
}// 這是我們鼠標的回調函數定義。如果用戶按下鼠標左按鈕,則開始畫一個方框,當用戶釋放該按鈕時,
//然后我們添加方框到當前圖像。當鼠標被拖動時(同時按鈕按下)調整框大小。void my_mouse_callback(int event, int x, int y, int flags, void* param){
// 鼠標回調函數的參數,必須滿足一定的格式要求: void cvmousecallback( int event, int x, int y, int flags, void* param);
// 第一個參數為鼠標事件類型,第二個第三個參數為事件發生時鼠標位置坐標,值得指出的是這些坐標是相對于像素位置的坐標,與窗口大小無關。IplImage* image = (IplImage*)param;switch (event) {case CV_EVENT_MOUSEMOVE: {if (drawing_box) {box.width = x - box.x;box.height = y - box.y;}}break;case CV_EVENT_LBUTTONDOWN: {drawing_box = true;box = cvRect(x, y, 0, 0);}break;case CV_EVENT_LBUTTONUP: {drawing_box = false;if (box.width<0) {box.x += box.width;box.width *= -1;}if (box.height<0) {box.y += box.height;box.height *= -1;}draw_box(image, box);}break;}
}
</span>