VOOZH about

URL: https://www.geeksforgeeks.org/python/detect-the-rgb-color-from-a-webcam-using-python-opencv/

⇱ Detect RGB color from a Webcam using Python - OpenCV - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Detect RGB color from a Webcam using Python - OpenCV

Last Updated : 18 Feb, 2026

Detecting RGB color from a webcam means identifying which color (Red, Green, or Blue) is most dominant in the live camera frame using Python and OpenCV. This is done by capturing video, analyzing color channels, and comparing their average intensity.

Prerequisites

Before starting, to install the required libraries, as they help Python access the webcam and calculate the RGB color values. Install it using below command in command prompt:

pip install opencv-python numpy

  • OpenCV used to open the webcam, capture video frames and display them.
  • NumPy used to calculate the average values of Red, Green and Blue colors from the frame.

Python Implementation

The following code captures live video from the webcam, calculates the average intensity of Red, Green and Blue channels for each frame and displays the name of the dominant color. It also includes error handling to prevent crashes if the webcam fails.

Output

A webcam window opens showing the live video and the dominant color name (Red, Green, or Blue) is printed in the console.

👁 Image
👁 Image

Press q to stop the program.

Explanation:

  • vid = cv2.VideoCapture(0) opens the default webcam.
  • ret, frame = vid.read() captures a frame from the webcam.
  • if not ret: checks if frame capture failed.
  • cv2.imshow("frame", frame) displays the current webcam frame.
  • b = frame[:, :, 0] extracts Blue color values.
  • g = frame[:, :, 1] extracts Green color values.
  • r = frame[:, :, 2] extracts Red color values.
  • np.mean(b), np.mean(g), np.mean(r) calculates average intensity of each color.
  • if condition compares averages to find dominant color.
  • cv2.waitKey(1) waits for key press.
  • vid.release() releases the webcam.
  • cv2.destroyAllWindows() closes all windows safely.
  • try-except block handles errors and prevents program crash.
Comment
Article Tags: