python用鼠标获取图像任一点的坐标和像素值

定义获取鼠标像素

import cv2


def get_pixel(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        # 输出像素值和坐标信息到控制台
        print('Pixel value at (', x, ', ', y, ') :', img[y, x])

        # 在图像上绘制坐标和像素值
        font = cv2.FONT_HERSHEY_SIMPLEX
        txt = 'Pixel value: ' + str(img[y, x]) + ' Coord: (' + str(x) + ', ' + str(y) + ')'
        cv2.putText(img, txt, (x, y), font, 0.5, (255, 0, 0), 2)

读取图像

在这里插入图片描述

img = cv2.imread('20230511200757_11189948_1_1.jpg')

显示图像并设置鼠标事件回调函数

cv2.namedWindow('Image')
cv2.setMouseCallback('Image', get_pixel)

while True:
    # 显示图像
    cv2.imshow('Image', img)

    # 等

猜你喜欢

转载自blog.csdn.net/ALiLiLiYa/article/details/131166843