Friday, December 1, 2023

OpenCV and Image Processing - Histogram for colored Images

The histogram is created on a channel-by-channel basis, a color image has blue, green and red channels. To plot the histogram for color images, the image should be split into blue, green and red channels, and plot the histogram one by one. With matplotlib library we can put the three histograms in one plot. 

Below is the code to generate histogram for color image:

1 def show_histogram_color(image):

2 blue, green, red = cv2.split(image)

3 # cv2.imshow("blue", blue)

4 # cv2.imshow("green", green)

5 # cv2.imshow("red", red)

6 fig = plt.figure(figsize=(6, 4))

7 fig.suptitle('Histogram', fontsize=18)

8 plt.hist(blue.ravel(), 256, [0, 256])

9 plt.hist(green.ravel(), 256, [0, 256])

10 plt.hist(red.ravel(), 256, [0, 256])

11 plt.show()

Explanations:

Line 2 Split the color image into blue, green and red channels

Line 3 - 5 Optionally show the blue, green and red channels.

Line 6 - 7 Create a plot, set the title.

Line 8 - 10 Add the histograms for blue, green and red to the plot

Line 11 Show the histogram plot.

In summary, the shape of the histogram can provide information about the overall color distributions, as well as valuable insights into the overall brightness and contrast of an image. If the histogram is skewed towards the higher intensity levels, the image will be brighter, while a skew towards lower intensity levels indicates a darker image. A bell-shaped histogram indicates a well-balanced contrast.

Histogram equalization is a common technique used to enhance the contrast of an image by redistributing the pixel intensities across a wider range. This technique can be used to improve the visual quality of images for various applications, such as medical imaging, satellite imaging, and digital photography.


Share: