首页 > 解决方案 > Python OpenCV - 添加状态栏以显示鼠标位置和颜色 RGB

问题描述

当使用“imread”命令加载图像或视频时,我想在状态栏上显示鼠标位置的坐标和 RGB 颜色。我正在使用 Windows 10 Python 3.7.4 Opencv 4.2.0.34

例子:

import cv2

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    if not ret:
        exit()
    cv2.imshow('example', frame)    
    k = cv2.waitKey(1)
    if k == ord('q'): 
        exit()

cap.release()
cv2.destroyAllWindows()

标签: pythonopencvstatusbar

解决方案


要在状态栏上显示值,您必须按照此处所述构建您的OpenCVwith ,现在为了在图像顶部展示值,您可以执行以下操作:QtR, G, B

import cv2

"""
Reference:
https://www.geeksforgeeks.org/displaying-the-coordinates-of-the-points-clicked-on-the-image-using-python-opencv/
"""

# function to display the coordinates of
# of the points clicked on the image 
def move_event(event, x, y, flags, params):
    imgk = img.copy()
    # checking for right mouse clicks     
    if event==cv2.EVENT_MOUSEMOVE:
  
        # displaying the coordinates
        # on the Shell
        # print(x, ' ', y)
  
        # displaying the coordinates
        # on the image window
        font = cv2.FONT_HERSHEY_SIMPLEX
        org = (x, y)
        B = imgk[y, x, 0]
        G = imgk[y, x, 1]
        R = imgk[y, x, 2]

    cv2.putText(imgk, '(x, y)=({}, {})'.format(x, y), org, font, 1, (255, 255, 255), 1, cv2.LINE_8)
    cv2.putText(imgk, '                  ,R={}'.format(R), org, font, 1, (0, 0, 255), 1, cv2.LINE_8)
    cv2.putText(imgk, '                         ,G={}'.format(G), org, font, 1, (0, 255, 0), 1, cv2.LINE_8)
    cv2.putText(imgk, '                                 ,B={}'.format(B), org, font, 1, (255, 0, 0), 1, cv2.LINE_8)
    cv2.imshow('image', imgk)

# reading the image
img = cv2.imread('image.jpg')

# displaying the image
cv2.namedWindow("image", cv2.WINDOW_NORMAL)
cv2.imshow('image', img)

# setting mouse hadler for the image
# and calling the click_event() function
cv2.setMouseCallback('image', move_event)

# wait for a key to be pressed to exit
cv2.waitKey(0)

# close the window
cv2.destroyAllWindows()

推荐阅读