Chapter 6

  1. An image histogram is a type of histogram that reflects the tonal distribution of the image. It plots the frequency (number of pixels) for each tonal value (commonly in the range of [0-255]).
  2. In OpenCV, we make use of the cv2.calcHist() function to calculate the histogram of images. To calculate the histogram of a grayscale image using 64 bits, the code is as follows:
 hist = cv2.calcHist([gray_image], [0], None, [64], [0, 256])
  1. We first build the image, M, with the same shape as the grayscale image, gray_image, and we set the value, 50, for every pixel of this image. Afterwards, we add both images using cv2.add(). Finally, the histogram is computed using cv2.calcHist():
M = np.ones(gray_image.shape, dtype="uint8") * 50
added_image = cv2.add(gray_image, M)
hist_added_image = cv2.calcHist([added_image], [0], None, [256], [0, 256])
  1. In a BGR image, the red channel is the third channel (index 2):
cv2.calcHist([img], [2], None, [256], [0, 256])

  1. OpenCV provides cv2.calcHist(), numpy provides np.histogram(), and matplotlib provides plt.hist(). As we saw in this chapter, cv2.calcHist() is faster than both np.histogram() and plt.hist().
  2. We have defined a function, get_brightness(), which calculates the brightness of a given grayscale image. This function makes use of the numpy function, np.mean(), which returns the average of the array elements. Therefore, the code for this function is as follows:
def get_brightness(img):
"""Calculates the brightness of the image"""

brightness = np.mean(img)
return brightness

We have computed the brightness of the three images:

brightness_1 = get_brightness(gray_image)
brightness_2 = get_brightness(added_image)
brightness_3 = get_brightness(subtracted_image)

The full code for this example can be seen in the grayscale_histogram_brightness.py script.

  1. First of all, we have to import default_timer:
from timeit import default_timer as timer

Then, we have to measure the execution time of both functions:

start = timer()
gray_image_eq = cv2.equalizeHist(gray_image)
end = timer()
exec_time_equalizeHist = (end - start) * 1000

start = timer()
gray_image_clahe = clahe.apply(gray_image)
end = timer()
exec_time_CLAHE = (end - start) * 1000

 The full code for this example can be seen in the comparing_hist_equalization_clahe_time.py. script.