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

Viewed 10199

I wrote a code that reads an image and get rgb values with coordinates of clicked pixel while you are clicking to screen with mouse. The working code is below;

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

But what I want is; I don't want to read image, I want to see realtime camera stream in screen; and when I click somewhere, I want to see clicked pixel's rgb values and coordinates in anytime.

How can I edit my code?

1 Answers

To capture video add a capture object

capture = cv2.VideoCapture(0)

0 is the camera number for my webcam but if you have a 2nd usb camera then it'll probably be 1

Then in your while loop read a frame from the video stream by adding

ret, frame = capture.read()

You can treat frame in exactly the same way as you treat any image.

Finally dont forget to release the capture object when you finish,

capture.release()
cv2.destroyAllWindows()

Full code listing,

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