You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OpenCV中实现鼠标悬停显示坐标与RGB值的功能?

OpenCV显示鼠标悬停坐标及RGB值实现方案

1. OpenCV自带该工具栏吗?

OpenCV原生的cv2.imshow()窗口没有自带显示鼠标悬停坐标和RGB值的工具栏,你看到的界面是自定义实现或第三方工具的功能。

2. 实现方法:鼠标回调函数

通过OpenCV的鼠标事件回调机制,就能实时获取鼠标位置并提取对应像素的RGB值,然后将信息绘制到窗口上。

修改后的完整代码

import cv2

def rescale_frame(frame, percent=75):
    # 修正原代码的shape索引错误:frame.shape[1]为宽度,shape[0]为高度
    width = int(frame.shape[1] * percent / 100)
    height = int(frame.shape[0] * percent / 100)
    dim = (width, height)
    return cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)

# 全局变量存储当前鼠标位置和RGB值
current_pos = (-1, -1)
current_rgb = (0, 0, 0)

def mouse_callback(event, x, y, flags, param):
    global current_pos, current_rgb
    frame = param
    # 鼠标移动时更新坐标与RGB值
    if event == cv2.EVENT_MOUSEMOVE:
        current_pos = (x, y)
        # OpenCV读取图像为BGR格式,需转换为RGB
        b, g, r = frame[y, x]
        current_rgb = (r, g, b)

vid = cv2.VideoCapture(0)
vid.set(cv2.CAP_PROP_FRAME_WIDTH, 160)
vid.set(cv2.CAP_PROP_FRAME_HEIGHT, 120)

while True:
    ret, frame = vid.read()
    if not ret:
        break
    
    frame75 = rescale_frame(frame, percent=75)
    # 注册鼠标回调,传入缩放后的帧作为参数
    cv2.setMouseCallback('frame75', mouse_callback, frame75)
    
    # 在窗口绘制坐标与RGB信息
    if current_pos != (-1, -1):
        text = f"X: {current_pos[0]}, Y: {current_pos[1]} | RGB: {current_rgb}"
        cv2.putText(frame75, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
    
    cv2.imshow('frame75', frame75)
    
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

vid.release()
cv2.destroyAllWindows()

关键说明

  • 修正了原代码中rescale_frame的错误:frame.shape[2]是通道数,宽度应使用frame.shape[1]
  • 利用cv2.setMouseCallback()监听鼠标移动事件,实时获取坐标(x,y)
  • OpenCV读取的图像为BGR格式,需转换为RGB后显示
  • 除了绘制在帧上,也可以通过cv2.setWindowTitle('frame75', text)将信息显示在窗口标题栏

内容的提问来源于stack exchange,提问作者bewa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:18:19