Randomly Colored Histogram of HSV Image

  • Share this:

Code introduction


This code uses OpenCV to read an image, convert it to the HSV color space, and calculate its color histogram. Then, it uses Matplotlib to plot the histogram, with each bar's color randomly generated.


Technology Stack : OpenCV, NumPy, Matplotlib

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
def random_histogram_color(arg1, arg2):
    import cv2
    import numpy as np
    
    # Read the image
    image = cv2.imread(arg1)
    
    # Convert the image to HSV color space
    hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    
    # Calculate the histogram of the HSV image
    hist = cv2.calcHist([hsv_image], [0], None, [256], [0, 256])
    
    # Normalize the histogram
    cv2.normalize(hist, hist, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX)
    
    # Create a figure and axis
    fig, ax = plt.subplots()
    
    # Plot the histogram
    ax.bar(range(256), hist, color=np.random.rand(256, 3), edgecolor='black')
    
    # Set the title and labels
    ax.set_title('Histogram of HSV Image')
    ax.set_xlabel('HSV Value')
    ax.set_ylabel('Frequency')
    
    # Show the plot
    plt.show()