opencv c 小练习9-1
/*

用鼠标读取图像颜色值。

编写程序读取并显示一张图片。

当用户鼠标点击图片时,读取当前鼠标对应位置的像素值(注意像素存储顺序是BGR),

以文本的形式在鼠标所在位置的左上角显示出来(显示当前坐标值和像素值)。当鼠标移动时,旧的文本框消失。

本代码:不能做到当鼠标移动时,旧的文本框消失。
*/ #include <iostream> #include <opencv.hpp> #include <opencv2/imgproc/types_c.h> #pragma comment(lib, "opencv_world420d.lib") using namespace cv; Mat img, temp; int move; //鼠标的callback定义 void my_mouse_callback(int event, int x, int y, int flags, void* param) { Mat& img = *(Mat*)param; int B, G, R, X, Y; String s; switch (event) { case EVENT_LBUTTONDOWN: { move = 0; CvPoint pt = cvPoint(x, y); X = pt.x; Y = pt.y; B = img.at<Vec3b>(x, y)[0]; G = img.at<Vec3b>(x, y)[1]; R = img.at<Vec3b>(x, y)[2]; s = std::to_string(X) + " " + std::to_string(Y) + ";" + std::to_string(B) + " " + std::to_string(G) + " " + std::to_string(R); int font_face = FONT_HERSHEY_COMPLEX; double font_scale = 0.5; int thickness = 0.5; int baseline; Size s_size = getTextSize(s, font_face, font_scale, thickness, &baseline); Point origin; origin.x = pt.x - s_size.width; origin.y = pt.y; putText(img, s, origin, FONT_HERSHEY_DUPLEX, 0.5, Scalar(0, 0, 0)); } break; case EVENT_MOUSEMOVE: { move = 1; } break; } } int main() { img = imread("D:\\opencvcx\\work1\\fruits.png"); img.copyTo(temp); move = 0; while (1) { if (move != 1) { setMouseCallback("fruit", my_mouse_callback, (void*)&temp); imshow("fruit", temp); } else img.copyTo(temp); if (waitKey(100) == 27) break; } return 0; }

  

posted on 2022-06-05 20:49  ting-1112  阅读(38)  评论(0编辑  收藏  举报