Custom visualizations of histograms

In order to visualize histograms, we have made use of the plt.plot() function. If we want to visualize a histogram by using only OpenCV capabilities, there is no OpenCV function to draw histograms. In this case, we have to make use of OpenCV primitives (for example, cv2.polylines() and cv2.rectangle(), among others) to create some (basic) functionality for plotting histograms. In the histogram_custom_visualization.py script, we have created the plot_hist() function, which performs this functionality. This function creates a BGR color image, plotting the histogram in it. The code for this function is as follows:

def plot_hist(hist_items, color):
"""Plots the histogram of a image"""

# For visualization purposes we add some offset:
offset_down = 10
offset_up = 10

# This will be used for creating the points to visualize (x-coordinates):
x_values = np.arange(256).reshape(256, 1)

canvas = np.ones((300, 256, 3), dtype="uint8") * 255
for hist_item, col in zip(hist_items, color):
# Normalize in the range for proper visualization:
cv2.normalize(hist_item, hist_item, 0 + offset_down, 300 - offset_up, cv2.NORM_MINMAX)
# Round the normalized values of the histogram:
around = np.around(hist_item)
# Cast the values to int:
hist = np.int32(around)
# Create the points using the histogram and the x-coordinates:
pts = np.column_stack((x_values, hist))
# Draw the points:
cv2.polylines(canvas, [pts], False, col, 2)
# Draw a rectangle:
cv2.rectangle(canvas, (0, 0), (255, 298), (0, 0, 0), 1)

# Flip the image in the up/down direction:
res = np.flipud(canvas)

return res

This function receives the histogram and builds the (x, y) points, pts for every element of the histogram, where the y value represents the frequency of the x element of the histogram. These points, pts, are drawn by using the cv2.polylines() function, which we have seen in Chapter 4, Constructing Basic Shapes in OpenCV. This function draws a polygonal curve based on the pts array. Finally, the image is flipped vertically because the y values are upside down. In the next screenshot, we can compare the visualization using plt.plot() and our custom function: