Image Thresholding in HSV Color Space

  • Share this:

Code introduction


This function reads an image file, converts it to the HSV color space, then creates a mask for the color range based on the given lower and upper bounds, and finally applies this mask to the original image, returning the processed image.


Technology Stack : OpenCV, NumPy

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
import cv2
import numpy as np
import random

def threshold_image(image_path, lower_bound, upper_bound):
    # Read the image
    image = cv2.imread(image_path)
    
    # Convert the image to HSV color space
    hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    
    # Create a mask for the color range
    mask = cv2.inRange(hsv_image, lower_bound, upper_bound)
    
    # Apply the mask to the original image
    result = cv2.bitwise_and(image, image, mask=mask)
    
    return result

# Code Information                
              
Tags: