【练习4.2】使用鼠标事件获取图片像素值
《学习OpenCV》中文版第4章第2题
题目要求:
点击图片是获取该点的颜色值,并在图像上点击鼠标处用文本将颜色值显示出来。
程序代码:
1 #include "stdafx.h" 2 #include <cv.h> 3 #include <highgui.h> 4 using namespace std; 5 using namespace cv; 6 7 void MouseCallBack(int event, int x, int y, int flags, void *param); 8 9 int _tmain(int argc, _TCHAR* argv[]) 10 { 11 const char * fileName = "D:\\Work\\Work_Programming\\Source\\Image\\lena.jpg"; 12 cvNamedWindow("MouseEvent", CV_WINDOW_AUTOSIZE); 13 IplImage * img = cvLoadImage(fileName,1); 14 assert(img); 15 16 cvSetMouseCallback("MouseEvent", MouseCallBack, img); 17 18 while (true) 19 { 20 cvShowImage("MouseEvent", img); 21 22 if (waitKey(15) == 27) 23 { 24 break; 25 } 26 } 27 28 cvWaitKey(0); 29 30 cvReleaseImage(&img); 31 cvDestroyWindow("MouseEvent"); 32 33 //system("pause"); 34 35 return 0; 36 } 37 38 void MouseCallBack(int event, int x, int y, int flags, void *param) 39 { 40 IplImage * img = (IplImage *)param; 41 42 CvFont font; 43 cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 2, 8); 44 45 CvScalar scl; 46 char * str = (char *)malloc(30 * sizeof(char)); 47 48 if (event == CV_EVENT_LBUTTONDOWN) 49 { 50 scl = cvGet2D(img, x, y); 51 52 double b = scl.val[0]; 53 double g = scl.val[1]; 54 double r = scl.val[2]; 55 56 sprintf(str, "B:%.0f,G:%.0f,R:%.0f", b, g, r); 57 58 cvPutText(img, str, cvPoint(x, y), &font, cvScalar(255, 0, 0)); 59 } 60 61 free(str); 62 }
‖==========钟于原创 乐于分享 宁静致远 毋忆典藏==========‖