Skip to content

Learning journal calvin

Issue 301

As a new student diving into Python programming and intrigued by the world of computer vision, my goal is to understand how to use OpenCV, a powerful library in Python, to create a program capable of recognizing various colors through a live camera.

To achieve this, I've set up an approach to learning that involves multiple steps. First, I aim to grasp the fundamentals of Python programming - understanding variables, loops, functions, and basic data types. This foundational knowledge will provide me with the groundwork needed to explore OpenCV effectively.

Once I've gained a solid understanding of Python, my next step is to delve into OpenCV. I want to learn how this library operates within Python and comprehend its functionalities related to image processing, color manipulation, and object detection. This exploration phase will equip me with the necessary knowledge to start building my color detection program.

Following this, I plan to create a simple Python script using OpenCV. This script will tap into the live camera feed and use basic color detection techniques to identify a specific color, such as white. Experimentation will be key here I'll tweak different parameters in the script to observe how they impact the accuracy of color detection.

As I gain familiarity with the initial color detection script, Our team aims to expand its capabilities. We'll be able to modify the code to detect additional colors beyond white. By adjusting various parameters.

Ultimately, my goal is to develop a robust understanding of Python, OpenCV, and their combined application in color detection. By breaking down this learning process into manageable steps, I aim to build a foundation that will enable me to explore more complex concepts and applications in the field of computer vision.

Explanation of the code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import cv2
import numpy as np

# Function to detect various shades of white in the live camera feed
def detect_white_shades(camera):
    # Open the camera
    camera = cv2.VideoCapture(camera)

    while True:
        # Capture frame-by-frame
        ret, frame = camera.read()

        # Convert the frame to HSV color space
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

        # Define lower and upper thresholds for different shades of white in HSV
        lower_white = np.array([0, 0, 150])  # Adjust these values to encompass less bright white colors
        upper_white = np.array([180, 100, 255])  # Adjust these values to encompass brighter white colors

        # Threshold the HSV image to get different shades of white
        mask = cv2.inRange(hsv, lower_white, upper_white)

        # Perform morphological operations to refine the mask
        kernel = np.ones((5, 5), np.uint8)
        mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
        mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

        # Find contours
        contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        # Draw contours around different shades of white and display coordinates
        for contour in contours:
            # Calculate coordinates for the bounding rectangle
            x, y, w, h = cv2.boundingRect(contour)

            # Draw contours around different shades of white
            cv2.drawContours(frame, [contour], -1, (0, 255, 0), 2)

            # Calculate centroid of contour
            M = cv2.moments(contour)
            if M["m00"] != 0:
                cX = int(M["m10"] / M["m00"])
                cY = int(M["m01"] / M["m00"])
                # Draw a center point
                cv2.circle(frame, (cX, cY), 5, (255, 0, 0), -1)
                # Display coordinates as text on the frame
                cv2.putText(frame, f'Center: ({cX}, {cY})', (cX, cY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

        # Display the frame with different shades of white, contours, and center points
        cv2.imshow('Different Shades of White Detection', frame)

        # Press 'q' to exit the loop
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # Release the camera and close all OpenCV windows
    camera.release()
    cv2.destroyAllWindows()

# Call the function with the camera index (usually 0 for default camera)
detect_white_shades(0)

#end of code

Breakdown of the script's functionality:

  1. Importing Libraries: import cv2: Imports the OpenCV library, which provides various computer vision functionalities. import numpy as np: Imports NumPy, a library used for numerical computations in Python.

  2. Function for Detecting White Shades: detect_white_shades(camera): This function detects different shades of white in the live camera feed. cv2.VideoCapture(camera): Initializes the camera to capture the video feed. Inside the while True loop, the script continuously captures frames from the camera. It converts each frame from the default BGR color space to HSV (Hue, Saturation, Value) color space using cv2.cvtColor().

  3. Thresholding for White Detection: Defines the lower and upper threshold values in the HSV color space to isolate different shades of white. cv2.inRange() is used to create a mask based on the defined lower and upper threshold values. Morphological operations (cv2.morphologyEx()) are applied to refine the mask and remove noise from the image.

  4. Contour Detection and Drawing: cv2.findContours() identifies contours (boundaries) of detected white areas. The script then draws contours around these areas on the original frame using cv2.drawContours(). Calculates centroids for each contour to find the center coordinates and displays them on the frame.

  5. Displaying the Processed Frame: The script displays the live camera feed with contours drawn around different shades of white and center points marked.

  6. Exiting the Script: The loop continues until the user presses 'q' on the keyboard, at which point it releases the camera and closes all OpenCV windows.

Setup Guide:

To run this code, follow these steps:

Install Required Libraries:

Ensure you have Python installed on your system. Install OpenCV and NumPy using pip:

1
2
pip install opencv-python
pip install numpy

Set up the Camera:

Connect a webcam or use the default camera on your device.

Copy and Run the Code:

Copy the provided Python code into a Python (.py) file on your system. Run the script in your preferred Python environment.

Interacting with the Script:

The script will open a window displaying the live camera feed. Objects or surfaces with shades of white will be outlined with contours and display their detected centroids.

Exiting the Script:

Press the 'q' key on your keyboard to exit the script and close the camera window.

By following these steps, you'll be able to run the provided code, observe the color detection process, and experiment with detecting different shades of white through your camera feed.