본문 바로가기
Lecture/OpenCV Master with Python (Beginner)

OpenCV + Python Color recognition and drawing using a webcam (practical)

by codingwalks.en 2024. 10. 24.
728x90
반응형

 

 

Hello. This is codingwalks.

The following is a color recognition and drawing exercise using a webcam. This mini-project uses OpenCV and Python to detect colors and create a simple program that draws points at the locations where the colors are detected to create a picture. We will proceed with the project step by step through theoretical explanations and Python code.

 

1. Project Overview

The project we will create is a program that detects a specific color through a webcam and draws a picture by drawing a point at the location of the color. To do this, the following tasks are required.

  • Real-time video acquisition through a webcam: Receiving frames in real time from the webcam.
  • Color detection: Detecting a specific color in an image and tracking its location.
  • Dot drawing: Drawing a picture by drawing a point at the location of the detected color.

This project involves using OpenCV to get an image from a webcam, detecting various colors using the HSV color space, and displaying the results on the screen.

 

2. Color Detection Theory

To recognize colors, we use the HSV (Hue, Saturation, Value) color space instead of the RGB color space. The HSV color space reflects the intuitive color perception of humans, making it easier to define a specific color range.

  • Hue (color): Indicates the type of color, 0° means red, 120° means green, and 240° means blue.
  • Saturation (saturation): Indicates the purity of the color, and the higher the value, the more vivid the color.
  • Value (brightness): Indicates the brightness of the color.

In the HSV color space, we set a range of specific colors and detect the colors in that range by processing them as masks.

 

OpenCV + Python Color space conversion and color detection

Hello. This is codingwalks.In this article, we will learn about color spaces, especially the widely used RGB, CMYK, HSV, YUV, and CIELab color spaces. Additionally, we will introduce a method to detect specific colors in images using the OpenCV library. We

en.codingwalks.com

 

3. Project source code

The following is a Python code written based on the content described above. This code includes the process of detecting colors and marking dots at those locations.

import cv2
import numpy as np
import time

hsv_target_colors = {
    'orange':[5, 107, 0, 19, 255, 255],
    'purple':[133, 56, 0, 159, 156, 255],
    'green':[57, 76, 0, 100, 255, 255],
}
bgr_target_colors = {
    'orange':[51, 153, 255],
    'purple':[255, 0, 255],
    'green':[0, 255, 0],
}

color_trails = {
    'orange':[],
    'purple':[],
    'green':[],
}

# Trajectory disappearance time and trajectory maximum length
trail_lifetime = 2
max_trail_length = 30

cap = cv2.VideoCapture(0)

def find_color(img_hsv, target_colors, trail_list):
    current_time = time.time()
    for key in trail_list:
        lower = np.array(target_colors[key][0:3])
        upper = np.array(target_colors[key][3:6])
        trails = trail_list[key]
        # Create a mask
        mask = cv2.inRange(img_hsv, lower, upper)
        # Color trajectory update
        contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        if contours:
            largest = max(contours, key=cv2.contourArea)
            if cv2.contourArea(largest) > 500:
                perimeter = cv2.arcLength(largest, True)
                approx = cv2.approxPolyDP(largest, 0.02 * perimeter, True)
                x, y, w, h = cv2.boundingRect(approx)
                trails.append(((int(x+w//2), int(y+h//2)), current_time))

        # Remove coordinates older than 5 seconds from trajectory
        trails = [(pos, t) for pos, t in trails if current_time - t < trail_lifetime]
        # List size limit
        trails = trails[-max_trail_length:]
        trail_list[key] = trails
    return trail_list

def draw_on_canvas(canvas_bgr, trail_list, target_colors):
    for key in trail_list:
        for i in range(1, len(trail_list[key])):
            cv2.line(canvas_bgr, trail_list[key][i - 1][0], trail_list[key][i][0], target_colors[key], 2)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    canvas = np.zeros(frame.shape, dtype="uint8")

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    color_trails = find_color(hsv, hsv_target_colors, color_trails)

    draw_on_canvas(canvas, color_trails, bgr_target_colors)

    combined_view = np.hstack((frame, canvas))
    cv2.imshow("Frame | Palette", combined_view)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

webcam test

 

4. Source Code Description

  • Webcam Setup: Get images from the webcam in real time using cv2.VideoCapture(0).
  • HSV Color Range Setup: Define the minimum and maximum HSV values ​​for each color in the hsv_target_colors dictionary.
  • Trails List: color_trails Stores coordinate information and time information for each detected color.
  • Color Detection Function: find_color Detects a given color, finds the location where a specific color is, and returns that location.
  • Drawing on Canvas Function: draw_on_canvas Draws a line using the coordinate information stored in the trails list and displays it on the screen.

 

5. Conclusion

Through this project, we learned how to process images from a webcam in real time using OpenCV and Python, detect a specific color, and draw a picture corresponding to that color. You can extend this code to detect more colors or draw various shapes.

 

If you found this post useful, please like and subscribe below. ^^

Buy me a coffee

 

[Codingwalks]에게 송금하기 - AQR

[Codingwalks]에게 송금하기 - AQR

aq.gy

★ All contents are referenced from the link below. ★

 

OpenCV: OpenCV-Python Tutorials

Core Operations In this section you will learn basic operations on image like pixel editing, geometric transformations, code optimization, some mathematical tools etc.

docs.opencv.org

728x90
반응형