Detect the RGB color from a webcam using Python – OpenCV
Prerequisites: Python NumPy, Python OpenCV
Every image is represented by 3 colors that are Red, Green and Blue. Let us see how to find the most dominant color captured by the webcam using Python.
Approach:
- Import the cv2 and NumPy modules
- Capture the webcam video using the cv2.VideoCapture(0) method.
- Display the current frame using the cv2.imshow() method.
- Run a while loop and take the current frame using the read() method.
- Take the red, blue and green elements and store them in a list.
- Compute the average of each list.
- Whichever average has the greatest value, display that color.
Python3
import cv2
import numpy as np
vid = cv2.VideoCapture( 0 )
while True :
_, frame = vid.read()
cv2.imshow( "frame" , frame)
b = frame[:, :, : 1 ]
g = frame[:, :, 1 : 2 ]
r = frame[:, :, 2 :]
b_mean = np.mean(b)
g_mean = np.mean(g)
r_mean = np.mean(r)
if (b_mean > g_mean and b_mean > r_mean):
print ( "Blue" )
if (g_mean > r_mean and g_mean > b_mean):
print ( "Green" )
else :
print ( "Red" )
|
Output:
Last Updated :
03 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...