【问题标题】:Python & Opencv : Realtime Get RGB Values When Mouse Is ClickedPython和Opencv:单击鼠标时实时获取RGB值
【发布时间】:2019-06-27 09:27:35
【问题描述】:

我编写了一个代码,当您用鼠标点击屏幕时,它会读取图像并获取带有点击像素坐标的 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 值和坐标。

如何编辑我的代码?

【问题讨论】:

标签: python python-3.x opencv rgb


【解决方案1】:

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

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    相关资源
    最近更新 更多