🐶
Machine Vision

OpenCV Python: Thresholding for Green Object Detection

By Jan on 03/04/2025

Learn how to use Python and OpenCV to set a threshold value for isolating and detecting only green colored objects within any image.

OpenCV Python: Thresholding for Green Object Detection

Table of Contents

Introduction

This article provides a step-by-step guide on how to detect green objects in an image using OpenCV in Python. We'll cover loading the image, converting it to the HSV color space, defining color ranges, creating a mask, finding contours, and drawing bounding boxes around the detected objects.

Step-by-Step Guide

  1. Import necessary libraries:
import cv2
import numpy as np
  1. Load the image:
image = cv2.imread('image.jpg')
  1. Convert the image from BGR to HSV color space:
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

HSV is often preferred for color detection as it separates color information (Hue) from saturation and value, making it less sensitive to lighting variations.

  1. Define the lower and upper bounds for green color in HSV:
lower_green = np.array([30, 50, 50])
upper_green = np.array([90, 255, 255])

These values can be adjusted based on the specific shade of green you want to detect. You can use tools like color pickers or online HSV calculators to find appropriate ranges.

  1. Create a mask for green color by thresholding the HSV image:
mask = cv2.inRange(hsv, lower_green, upper_green)

cv2.inRange() creates a binary mask where pixels within the specified HSV range are white (255) and others are black (0).

  1. Find contours in the mask:
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

This step identifies the outlines of the detected green regions.

  1. Iterate through the contours and draw bounding boxes around them:
for contour in contours:
    if cv2.contourArea(contour) > 100:  # Filter out small contours
        x, y, w, h = cv2.boundingRect(contour)
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

This loop draws a green rectangle around each detected green object in the original image. The cv2.contourArea() check helps to ignore small, potentially noisy detections.

  1. Display the result:
cv2.imshow('Green Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

This will show the image with green objects highlighted.

Code Example

The Python code detects green objects in an image. It loads the image, converts it to HSV color space, and creates a mask to isolate green areas. Then, it finds contours in the mask and draws bounding boxes around large enough contours, effectively highlighting the detected green objects in the original image. Finally, it displays the image with the detected green objects.

import cv2
import numpy as np

# Load the image
image = cv2.imread('image.jpg')

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

# Define the lower and upper bounds for green color in HSV
lower_green = np.array([30, 50, 50])
upper_green = np.array([90, 255, 255])

# Create a mask for green color by thresholding the HSV image
mask = cv2.inRange(hsv, lower_green, upper_green)

# Find contours in the mask
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Iterate through the contours and draw bounding boxes around them
for contour in contours:
    if cv2.contourArea(contour) > 100:  # Filter out small contours
        x, y, w, h = cv2.boundingRect(contour)
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

# Display the result
cv2.imshow('Green Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Explanation:

  1. Import necessary libraries: This line imports the OpenCV (cv2) library for image processing and the NumPy library for numerical operations.
  2. Load the image: This line loads the image named 'image.jpg' using cv2.imread(). Make sure to replace 'image.jpg' with the actual path to your image file.
  3. Convert to HSV: This line converts the image from the default BGR color space to HSV using cv2.cvtColor().
  4. Define green color range: These lines define the lower and upper bounds of the green color range in HSV. You can adjust these values to detect different shades of green.
  5. Create a mask: This line creates a mask by thresholding the HSV image based on the defined green color range using cv2.inRange(). The mask will have white pixels where the image falls within the green range and black pixels elsewhere.
  6. Find contours: This line finds the contours (outlines) of the white regions in the mask using cv2.findContours().
  7. Draw bounding boxes: This loop iterates through the found contours. For each contour, it calculates its area using cv2.contourArea(). If the area is larger than 100 pixels (to filter out small noise), it calculates the bounding rectangle of the contour using cv2.boundingRect() and draws a green rectangle on the original image using cv2.rectangle().
  8. Display the result: These lines display the final image with the detected green objects highlighted by green rectangles.

This code provides a basic example of green object detection using OpenCV in Python. You can modify and extend it further based on your specific requirements, such as detecting different colors, tracking objects, or performing more advanced image analysis.

Additional Notes

  • Adjusting Color Sensitivity: The lower_green and upper_green arrays define the range of HSV values considered "green." You can fine-tune these values to detect specific shades of green more accurately. Experiment with different ranges to suit your target color.

  • HSV Color Space: Converting the image to HSV (Hue, Saturation, Value) is crucial. HSV represents colors in a way that aligns better with human perception. Hue represents the pure color, Saturation indicates the color's intensity, and Value represents its brightness. This separation makes color detection less sensitive to lighting variations compared to using the RGB color space directly.

  • Contour Filtering: The code includes if cv2.contourArea(contour) > 100: to discard small contours. This helps eliminate noise and focus on detecting significant green regions. Adjust the threshold (100 in this case) based on the expected size of the green objects in your images.

  • Real-World Applications: This green object detection technique has various practical uses, including:

    • Object Tracking: Track the movement of green objects in video streams.
    • Robotics: Guide robots to interact with green objects.
    • Image Segmentation: Isolate green regions for further analysis.
    • Plant Analysis: Identify and measure green areas in images of plants.
  • Morphological Operations: Consider using morphological operations like erosion and dilation to refine the mask and remove small holes or gaps in the detected green regions. This can improve the accuracy of contour detection.

  • Alternative Contour Retrieval Modes: The code uses cv2.RETR_EXTERNAL to find only the outermost contours. Explore other retrieval modes like cv2.RETR_LIST or cv2.RETR_TREE if you need to analyze the hierarchy of contours (e.g., objects within objects).

  • Performance Optimization: For real-time applications, optimize your code by:

    • Resizing the input image to a smaller size before processing.
    • Using efficient data structures and algorithms.
    • Leveraging OpenCV's GPU acceleration capabilities if available.

Summary

This code snippet demonstrates how to detect and highlight green objects within an image using OpenCV in Python.

Here's a breakdown of the process:

  1. Setup: Import necessary libraries (cv2 for image processing, numpy for numerical operations).
  2. Image Loading: Load the target image using cv2.imread().
  3. Color Space Conversion: Convert the image from BGR (default OpenCV format) to HSV color space using cv2.cvtColor(). HSV is preferred for color detection due to its better separation of color information.
  4. Defining Green Color Range: Define the lower and upper bounds of the green color range in HSV using np.array(). These values can be adjusted to target specific shades of green.
  5. Creating a Mask: Create a binary mask highlighting the green regions in the image. This is achieved by thresholding the HSV image based on the defined green color range using cv2.inRange().
  6. Finding Contours: Identify the outlines of the detected green regions (from the mask) using cv2.findContours().
  7. Drawing Bounding Boxes: Iterate through the detected contours and draw a green rectangle around each significant contour (filtering out small ones based on area) using cv2.rectangle().
  8. Displaying the Result: Display the final image with highlighted green objects using cv2.imshow().

In essence, this code leverages color thresholding in HSV space and contour detection to locate and highlight green objects within an image.

Conclusion

This code effectively isolates and highlights green objects within an image using a combination of color space transformations, thresholding, and contour detection techniques provided by OpenCV. By converting the image to HSV, defining a suitable green color range, and leveraging OpenCV's functions for masking, contour finding, and drawing, the code accurately identifies and marks green objects with bounding boxes. This approach is adaptable for different shades of green and can serve as a foundation for more complex applications like object tracking or image segmentation in various fields.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait