- opencv获取鼠标点击像素坐标主要通过setMouseCallback函数实现
setMouseCallback(windowName, onMouse, param=None): # real signature unknown; restored from __doc__
""" setMouseCallback(windowName, onMouse [, param]) -> None """
import cv2
# 回调函数:鼠标点击输出点击的坐标
# param作为图像传去
def mouse_callback(event, x, y, flags, param):
# 如果鼠标左键点击,则输出横坐标和纵坐标
if event == cv2.EVENT_LBUTTONDOWN:
print(f'({x}, {y})')
# 在图像上绘制点
cv2.circle(param, (x, y), 3, (0, 0, 255), -1)
# 在图像上添加坐标文本
cv2.putText(param, f'({x},{y})', (x, y),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
if __name__ == '__main__':
img = cv2.imread('test.jpg')
# 创建窗口
cv2.namedWindow('Point Coordinates')
# 将回调函数绑定到窗口
cv2.setMouseCallback('Point Coordinates', mouse_callback, img)
# 显示图像
while True:
cv2.imshow('Point Coordinates', img)
k = cv2.waitKey(1) & 0xFF
# 按esc键退出
if k == 27:
break
cv2.destroyAllWindows()
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
//将图像作为void指针传入
void onMouse(int event, int cols, int rows, int flags, void* param)
{
//Mat* im = reinterpret_cast<Mat*>(param);
Mat* im = (Mat*)param;
switch (event)
{
case EVENT_LBUTTONDOWN://左键按下显示像素值
string point = "<" + to_string(cols) + " " + to_string(rows) + ">";
cv::putText(*im, point, cv::Point(cols, rows), 1, 1, cv::Scalar(0, 0, 255), 1);
}
}
int main()
{
Mat img = imread("../test.jpg");
cv::namedWindow("image");
setMouseCallback("image", onMouse, (void*)&img);//鼠标响应函数
while (true)
{
imshow("image", img);
int k = waitKey(1);
if (k == 27)
{
break;
}
}
return 0;
}
https://blog.csdn.net/qq_38473254/article/details/134082649