A histogram is a type of graph that displays the frequency of each element. It is used to represent the frequency distribution. In the case of an image, a histogram can be a graph between the color intensity and its frequency.
Let’s run the following code to see the image and its histogram:
import cv2 # importing opencv librariesfrom matplotlib import pyplot as plt # importing plotting libraryimage = cv2.imread('/images/img5.png') # reading an imageplt.subplot(2, 1, 1) # creating subplot to display imageplt.title("Image") # allocating title to the plotplt.imshow(image) # diplaying imageplt.subplot(2, 1, 2) # selecting second subplotplt.hist(image.ravel(),256,[0,256]) # histogram plottingplt.title("Histogram", x=0.9, y =0.8) # allocating the title to the plotplt.show() # displaying the plot
Histogram sliding is a technique to shift the frequency distribution to the left or the right. In the case of an image, this shifting causes a change in the brightness of each pixel.
We can perform histogram sliding by adding or subtracting from each pixel value of the image. Let’s run the following code to see the histogram sliding:
import cv2 # importing opencv librariesfrom matplotlib import pyplot as plt # importing plotting libraryimport numpy as np #importing numpy librarydef histogram_sliding(img, shift):fill = np.ones(img.shape, np.uint8) * abs(shift)if shift > 0:return cv2.add(img, fill)else:return cv2.subtract(img, fill)image = cv2.imread('/images/img5.png') # reading an imageimage1 = histogram_sliding(image, -30) # shifiting histogram to leftwardsplt.subplot(3, 2, 1) # creating subplot to display imageplt.title("Image") # allocating title to the plotplt.imshow(image1) # diplaying imageplt.subplot(3, 2, 2) # selecting second subplotplt.hist(image1.ravel(),256,[0,256]) # histogram plottingplt.title("Histogram") # allocating the title to the plotplt.show() # displaying the plotplt.subplot(3, 2, 3) # creating subplot to display imageplt.imshow(image) # diplaying original imageplt.subplot(3, 2, 4) # selecting second subplotplt.hist(image.ravel(),256,[0,256]) # histogram plottingplt.show() # displaying the plotimage2 = histogram_sliding(image, 30) # shifiting histogram to rightwardsplt.subplot(3, 2, 5) # creating subplot to display imageplt.imshow(image2) # diplaying imageplt.subplot(3, 2, 6) # selecting second subplotplt.hist(image2.ravel(),256,[0,256]) # histogram plottingplt.show() # displaying the plot
histogram_sliding()
function. We create an np array and add/subtract it from the image.imread()
function of OpenCV.30
.30
.Free Resources