Random HSV Color Generator within Specified Range

  • Share this:

Code introduction


This function generates a random color within a specified range in the HSV color space. It first defines the range of the HSV color space, then generates a random color using numpy, and finally scales the color using OpenCV.


Technology Stack : numpy, OpenCV

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_color_hsv(hsv_range):
    """
    Generates a random color in the HSV color space within a specified range.
    """
    import numpy as np
    import cv2

    # Define the range of the HSV color space
    min_hsv = np.array([hsv_range[0], hsv_range[1], hsv_range[2]])
    max_hsv = np.array([hsv_range[3], hsv_range[4], hsv_range[5]])

    # Generate a random color within the range
    random_color = cv2.resize(np.random.uniform(min_hsv, max_hsv, (1, 1, 3)).astype(np.uint8), (0, 0), interpolation=cv2.INTER_AREA)
    return random_color                
              
Tags: