學習OpenCV-例程實踐(持續更新)
阿新 • • 發佈:2019-01-03
例4-1:用滑鼠在視窗中畫方形的程式
#include"pch.h"//看情況加 #include <cv.h> #include <highgui.h> CvRect box; //定義繪製的矩形 bool drawing_box = false; //狀態-滑鼠正在移動 void draw_box(IplImage* img, CvRect rect){ //繪製矩形 cvRectangle( img, cvPoint(rect.x, rect.y), cvPoint(rect.x+ rect.width, rect.y+ rect.height), cvScalar(0xff,0xf0,0x0f)); } //滑鼠響應函式-回撥函式 void my_mouse_callback( int event, int x, int y, int flags, void* param) { IplImage* img = (IplImage*)param; switch (event) { case CV_EVENT_MOUSEMOVE: //mouse move if (drawing_box) { box.width = x - box.x; box.height = y - box.y; } break; case CV_EVENT_LBUTTONDOWN: //left button be pressed drawing_box = true; //drawing flag set 1 box = cvRect(x, y, 0, 0); break; case CV_EVENT_LBUTTONUP: //left button be released drawing_box = false; // redefine the left position of box if (box.width < 0) { box.x += box.width; box.width *= -1; } if (box.height < 0) { box.y += box.height; box.height *= -1; } draw_box(img, box); // draw the box ,the img is a inside var break; } } int main(int argc, char** argv[]) { box = cvRect(-1, -1, 0, 0);//設定一個矩形,被隱藏 IplImage *img = cvCreateImage(cvSize(2000, 2000), IPL_DEPTH_8U, 3);//建立一個影象 cvZero(img);//資料設定為0 IplImage* temp = cvCloneImage(img); //copy image,copy the struction cvNamedWindow("Box Example"); //build a windown with box example //set mouse callback function cvSetMouseCallback( "Box Example", my_mouse_callback,//the second para. only need pointer address (void*)img); while (1){ cvCopy(img, temp);//copy image from imag to temp if (drawing_box) draw_box(temp, box); cvShowImage("Box Example", temp); if (cvWaitKey(15) == 27) break; } cvReleaseImage( &img ); cvReleaseImage( &temp ); cvDestroyWindow("Box Example"); }