题目:(P126)

创建一个程序,使其读入并显示一幅图像。当用户鼠标点击图像时,获取图像对应像素的颜色值(BGR),并在图像上点击鼠标处用文本将颜色值显示出来。

解答:

本题关键是会用cvGet2D获得BGR值,以及会用鼠标点击事件和回调函数,还有显示文本值。

#include<cv.h>
#include<highgui.h>
#include<iostream> using namespace std;
char* str = (char*)malloc(30 * sizeof(char*));
void myMouseCallback(
int event,
int x,
int y,
int flags,
void* param
);
int main(int argc, char* argv[])
{
IplImage* img = cvLoadImage(argv[1]);
cvNamedWindow("获取图像某一点的颜色分量", 1);
cvShowImage("获取图像某一点的颜色分量", img);
while (1)
{
cvSetMouseCallback(
"获取图像某一点的颜色分量",
myMouseCallback,
(void*)img
);
if (cvWaitKey(100) == 27)
break;
}
cvReleaseImage(&img);
cvDestroyWindow("获取图像某一点的颜色分量");
return 0;
}
void myMouseCallback(
int event,
int x,
int y,
int flags,
void* param
) {
IplImage* img = (IplImage*)param;
if (event == CV_EVENT_LBUTTONDOWN)
{
CvScalar s;
s = cvGet2D(img, x, y);//返回(x,y)的RGB值 CvFont cvf;
cvInitFont(&cvf, CV_FONT_HERSHEY_PLAIN, 1, 1, 0, 1, 8);
double r = s.val[0];
double g = s.val[1];
double b = s.val[2];
memset(str, 0, 30);
sprintf(str, "B:%.0f,G:%.0f,R:%.0f", b, g, r);
cout << "B:" << b << ",G:" << g << ",R:" << r << endl;
cvPutText(img,
str,
cvPoint(x, y),
&cvf,
cvScalar(255, 0, 0)
);
cvShowImage("获取图像某一点的颜色分量", img);
}
}
05-11 23:02