Python & Opencv : 点击鼠标实时获取RGB值

Python & Opencv : Realtime Get RGB Values When Mouse Is Clicked

我写了一个代码,当你用鼠标点击屏幕时,它会读取图像并获取带有点击像素坐标的 rgb 值。工作代码如下;

import cv2
import numpy as np


def mouseRGB(event,x,y,flags,param):
    if event == cv2.EVENT_LBUTTONDOWN: #checks mouse left button down condition
        colorsB = image[y,x,0]
        colorsG = image[y,x,1]
        colorsR = image[y,x,2]
        colors = image[y,x]
        print("Red: ",colorsR)
        print("Green: ",colorsG)
        print("Blue: ",colorsB)
        print("BRG Format: ",colors)
        print("Coordinates of pixel: X: ",x,"Y: ",y)

# Read an image, a window and bind the function to window
image = cv2.imread("image.jpg")
cv2.namedWindow('mouseRGB')
cv2.setMouseCallback('mouseRGB',mouseRGB)

#Do until esc pressed
while(1):
    cv2.imshow('mouseRGB',image)
    if cv2.waitKey(20) & 0xFF == 27:
        break
#if esc pressed, finish.
cv2.destroyAllWindows()

但我想要的是;我不想读取图像,我想在屏幕上看到实时摄像头流;当我点击某处时,我想随时查看点击像素的 rgb 值和坐标。

如何编辑我的代码?

要捕获视频,请添加捕获对象

capture = cv2.VideoCapture(0)

0 是我的网络摄像头的摄像头编号,但如果你有第二个 USB 摄像头,那么它可能是 1

然后在您的 while 循环中通过添加

从视频流中读取一帧
ret, frame = capture.read()

您可以像对待任何图像一样对待 frame

最后不要忘记在完成后释放捕获对象,

capture.release()
cv2.destroyAllWindows()

完整代码清单,

import cv2
import numpy as np


def mouseRGB(event,x,y,flags,param):
    if event == cv2.EVENT_LBUTTONDOWN: #checks mouse left button down condition
        colorsB = frame[y,x,0]
        colorsG = frame[y,x,1]
        colorsR = frame[y,x,2]
        colors = frame[y,x]
        print("Red: ",colorsR)
        print("Green: ",colorsG)
        print("Blue: ",colorsB)
        print("BRG Format: ",colors)
        print("Coordinates of pixel: X: ",x,"Y: ",y)


cv2.namedWindow('mouseRGB')
cv2.setMouseCallback('mouseRGB',mouseRGB)

capture = cv2.VideoCapture(0)

while(True):

    ret, frame = capture.read()

    cv2.imshow('mouseRGB', frame)

    if cv2.waitKey(1) == 27:
        break

capture.release()
cv2.destroyAllWindows()