Random Histogram Generation from Image

  • Share this:

Code introduction


This function reads an image from a specified path, converts it to grayscale, and randomly generates a specified number of histograms to display. Each histogram randomly selects a color channel and plots it with a randomly generated color.


Technology Stack : OpenCV, NumPy, Matplotlib

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
def random_histogram(image_path):
    import cv2
    import numpy as np
    import random

    # Load an image
    image = cv2.imread(image_path)
    if image is None:
        raise ValueError("Image not found or path is incorrect")

    # Convert the image to grayscale
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Generate a random number of histograms to plot
    num_histograms = random.randint(1, 5)

    # Calculate histogram for each channel of the grayscale image
    for i in range(num_histograms):
        # Generate a random channel (0 for blue, 1 for green, 2 for red)
        channel = random.randint(0, 2)
        hist = cv2.calcHist([gray_image], [channel], None, [256], [0, 256])
        cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX)

        # Generate a random color for the histogram plot
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

        # Plot the histogram
        plt.figure()
        plt.title(f'Channel {channel} Histogram')
        plt.xlabel('Pixel Value')
        plt.ylabel('Frequency')
        plt.plot(hist, color=color)
        plt.xlim([0, 256])
        plt.show()

    return None