Color histograms

In this section, we will see how to calculate color histograms. The script that performs this functionality is color_histogram.py. In the case of a multi-channel image (for example, a BGR image), the process of calculating the color histogram involves calculating the histogram in each of the channels. In this case, we have created a function to calculate the histogram from a three-channel image:

def hist_color_img(img):
"""Calculates the histogram from a three-channel image"""

histr = []
histr.append(cv2.calcHist([img], [0], None, [256], [0, 256]))
histr.append(cv2.calcHist([img], [1], None, [256], [0, 256]))
histr.append(cv2.calcHist([img], [2], None, [256], [0, 256]))
return histr

It should be noted that we could have created a for loop or a similar approach in order to call the cv2.calcHist() function three times. But, for the sake of simplicity, we have performed the three calls indicating the different channels explicitly. In this case, as we are loading BGR images, the calls are as follows:

Therefore, in order to calculate the color histogram of an image, note the following:

image = cv2.imread('lenna.png')
hist_color = hist_color_img(image)

In this script, we have also made use of cv2.add() and cv2.subtract() to modify the brightness of the loaded BGR image and see how the histogram changes. In this case, 15 has been added/subtracted to every pixel of the original BGR image. This can be seen in the next screenshot corresponding to the output of the color_histogram.py script: