【问题标题】:Python OpenCV - Add status bar for show mouse position and color RGBPython OpenCV - 添加状态栏以显示鼠标位置和颜色 RGB
【发布时间】:2026-01-31 09:35:02
【问题描述】:

当使用“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()

【问题讨论】:

  • 做一些研究。在问这样的问题之前,请搜索谷歌和这个论坛。有很多基于鼠标的颜色选择器的例子。我所知道的 cv2.imshow() 中没有内置任何东西可以做到这一点。你必须自己编写代码。阅读有关使用鼠标的 OpenCV 文档。然后尝试编写自己的代码。如果您有问题,请针对该问题提出具体问题。请参加 tour (*.com/tour) 并阅读帮助中心 (*.com/help),尤其是“如何提出一个好问题”(*.com/help/how-to-ask)
  • 如果OpenCV的highgui模块是用Qt构建的,imshow窗口确实有状态栏。

标签: python opencv statusbar


【解决方案1】:

要在状态栏上显示值,您必须使用Qt 构建您的OpenCV,如here 所述,现在用于在图像顶部展示R, 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()

【讨论】: