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:

  1. Import the cv2 and NumPy modules
  2. Capture the webcam video using the cv2.VideoCapture(0) method.
  3. Display the current frame using the cv2.imshow() method.
  4. Run a while loop and take the current frame using the read() method.
  5. Take the red, blue and green elements and store them in a list.
  6. Compute the average of each list.
  7. Whichever average has the greatest value, display that color.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing required libraries
import cv2
import numpy as np
  
# taking the input from webcam
vid = cv2.VideoCapture(0)
  
# running while loop just to make sure that
# our program keep running untill we stop it
while True:
  
    # capturing the current frame
    _, frame = vid.read()
  
    # displaying the current frame
    cv2.imshow("frame", frame) 
  
    # setting values for base colors
    b = frame[:, :, :1]
    g = frame[:, :, 1:2]
    r = frame[:, :, 2:]
  
    # computing the mean
    b_mean = np.mean(b)
    g_mean = np.mean(g)
    r_mean = np.mean(r)
  
    # displaying the most prominent color
    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")

chevron_right


Output:

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.