Color Detection with HSV Color Space in OpenCV

    In image processing, color space refers to a specific representation method used to describe and organize the colors in an image. It provides a structured way to define and manipulate colors, allowing for various color-related operations such as color correction, color enhancement, color segmentation, and object detection. One of the widely used color space is HSV, which stands for Hue, Saturation, and Value. 

    In this tutorial, we'll delve into the fundamentals of the HSV color space and learn how to detect given color in an image by applying HSV method with OpenCV in Python. The tutorial covers:

  1. Understanding HSV
  2. Color detection with HSV
  3. Source code listing

    We'll start by loading the required libraries.


import cv2
from matplotlib import pyplot as plt
import numpy as np

    
Understanding HSV
 
     The HSV (Hue, Saturation, Value) color space has various applications in image processing and computer vision. The HSV color space separates the color information into three components: hue, saturation, and value. The hue component represents the color itself, saturation represents the intensity or purity of the color, and value represents the brightness or lightness of the color.  
    The HSV color space is less affected by variations in lighting conditions compared to the RGB color space and its independent color order provides more consistent and accurate color detection in an image.
     We can transform image into the HSV color space by using cv2.cvtColor() function of OpencCV library. Below code shows how to display RGB and HSV representation of an image.
 
file = "/Users/user/Desktop/tmp/balloon.jpg"

# Load the image
image = cv2.imread(file)
 
# Display the the images
plt.figure(figsize = (10, 5))
plt.subplot(1, 2, 1)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.title('RGB')
plt.subplot(1, 2, 2)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2HSV))
plt.title('HSV')
plt.tight_layout()
plt.show()
  


 
Color detection with HSV
 
    We can detect colors in an image by using HSV color space. Below code shows how how to detect red colors and draw the bounding boxes around the detected color.
    First, we'll convert the image into HSV type and define the lower and upper thresholds for red color range to create mask. Then we apply morphological operations to remove noise in an image. To create bounding boxes we need contours of read areas. Finally we'll draw green bounding boxes around the area and display the final image.
 
 
# Convert the image to the HSV color space
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

# Define the lower and upper color thresholds for red
lower_red = np.array([0, 100, 100])
upper_red = np.array([10, 255, 255])

# Create a mask based on the color thresholds
mask = cv2.inRange(hsv_image, lower_red, upper_red)

# Apply morphological operations to remove noise
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

# Find contours of the red areas
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Draw bounding boxes around the red areas
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 3)


plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.show()
 

    In this tutorial, you've briefly learned about HSV color space and how to perform color detection with HSV method in Python. The full source code is listed below. 

 

Video Tutorial
 

 
Source code listing
 
 
import cv2
from matplotlib import pyplot as plt
import numpy as np
 
 
file = "/Users/user/Desktop/tmp/balloon.jpg"

# Load the image
image = cv2.imread(file)
 
# Display the the images
plt.figure(figsize = (10, 5))
plt.subplot(1, 2, 1)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.title('RGB')
plt.subplot(1, 2, 2)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2HSV))
plt.title('HSV')
plt.tight_layout()
plt.show()
 
 
# Convert the image to the HSV color space
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

# Define the lower and upper color thresholds for red
lower_red = np.array([0, 100, 100])
upper_red = np.array([10, 255, 255])

# Create a mask based on the color thresholds
mask = cv2.inRange(hsv_image, lower_red, upper_red)

# Apply morphological operations to remove noise
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

# Find contours of the red areas
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Draw bounding boxes around the red areas
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 3)


plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.show()
 
 
 

 

1 comment:

  1. hey,
    absolutely didn't expect that this program is great!
    im gonna use it in my face detection app if you let me
    do you?
    but this program worked the first time i try to open it! that's rare for me(lol)

    ReplyDelete