如何在OpenCV中的图像上临时显示文本?

2024-10-16 20:46:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在鼠标悬停时显示像素值,但在图像上使用putText方法时,它会替换原始图像变量

另外,我想在鼠标悬停时临时显示坐标

因此,当我将鼠标移动到另一个位置时,应该只能显示当前坐标

有人能帮我吗

# importing the libraries
import cv2

# storing the coordinates
points = []

# event function
def click_event(event, x, y, flag, params):

    global points

    if event == cv2.EVENT_LBUTTONDOWN:
        cv2.circle(img, (x,y), 2, (0,0,0), -1)
        points.append((x,y))

        if len(points) == 2:
            cv2.line(img, points[0], points[1], (0,0,0), 2)
            points = []

        cv2.imshow('Scientists', img)

    elif event == cv2.EVENT_MOUSEMOVE:
        coordinates = '('+str(x)+','+str(y)+')'
        cv2.putText(img, coordinates, (x,y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,0))
        cv2.imshow('Scientists', img)

# reading the image
img = cv2.imread('scientists.jpg', -1)

# displaying the image
cv2.imshow('Scientists', img)

# event listener method
cv2.setMouseCallback('Scientists', click_event)

cv2.waitKey(0)
cv2.destroyAllWindows()

Tags: the图像imageeventimgifcv2points