在直接打开图片无法显示图片像素点位置,有时候需要对像素点位置进行编辑,而目前比较多的是python代码实现,故此利用c++实现鼠标点击图片,标记位置显示。
效果图:
实现代码:
#include<opencv2/imgcodecs.hpp>
#include<opencv2/highgui.hpp>
#include<opencv2/imgproc.hpp>
#include<iostream>
using namespace cv;
using namespace std;
获取鼠标点击的坐标 /
string path = "Learn-OpenCV-cpp-in-4-Hours-main\\Resources\\cards.jpg";
static Mat img = imread(path);
// 回调函数:鼠标点击输出点击的坐标
//(事件(鼠标移动、左键、右键),横坐标,纵坐标,组合键,setMouseCallback的userdata用于传参)
void mouse_callback(int event, int x, int y, int flags, void* param) {
// 如果鼠标左键点击,则输出横坐标和纵坐标
if (event == EVENT_LBUTTONDOWN) {
cout << x << " " << y << endl;
//在图像上绘制点
circle(img, Point(x, y), 2, Scalar(0, 69, 255), -1);//厚度10,填满 FILLED
//(图像,文本内容,坐标点,字体类型,字体大小,颜色,字体粗细)
string str = "(" + to_string(x) + "," + to_string(y) + ")";
putText(img, str, Point(x, y), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 2);
imshow("Point Coordinates", img);
}
}
void main() {
// 创建窗口
namedWindow("Point Coordinates");
// 将回调函数绑定到窗口
setMouseCallback("Point Coordinates", mouse_callback);
//显示图像
imshow("Point Coordinates", img);
waitKey(0);
destroyAllWindows();
}