# How to plot a Histogram of a grayscale image in 2 ways in Python using OpenCV – 2023 In today’s very short blog we will see that how we can plot a histogram of a grayscale image.

The first way is using NumPy and the second way is using matplotlib. This is going to be a very interesting blog, so without any further due, Let’s do it…

## Step 1 – Import the libraries required for the histogram of a grayscale image.

```import cv2
import matplotlib.pyplot as plt
import numpy as np```

## Step 2 – Let’s read the image.

```imgpath = "4.2.07.tiff"
• Here while reading the image, we passed the second argument as 0 to read the image as a grayscale image.

## Step 3 – Let’s plot the image and the histogram of a grayscale image.

Syntax: numpy.histogram(a, bins=10, range=None, normed=None, weights=None, density=None)

Parameters:

```plt.subplot(1,2,1)
plt.imshow(img,cmap='gray')
plt.title('image')
plt.xticks([])
plt.yticks([])

plt.subplot(1,2,2)
hist,bin = np.histogram(img.ravel(),256,[0,255])
plt.xlim([0,255])
plt.plot(hist)
plt.title('histogram')

plt.show()```
• img.ravel is basically used to flatten the 2-D matrix(grayscale image) to a 1-D array.
• Now we will be having our image as something like [125,113,8,45,63…] with no. of elements as n*m where n is the height of the grayscale image and m is the width of the grayscale image.

## Let’s see the whole code of 1st way using NumPy…

```import cv2
import matplotlib.pyplot as plt
import numpy as np

imgpath = "test.tiff"

plt.subplot(1,2,1)
plt.imshow(img,cmap='gray')
plt.title('image')
plt.xticks([])
plt.yticks([])

plt.subplot(1,2,2)
hist,bin = np.histogram(img.ravel(),256,[0,255])
plt.xlim([0,255])
plt.plot(hist)
plt.title('histogram')
plt.show()```

## Now let’s see the whole code of 2nd way using matplotlib.

```import cv2
import matplotlib.pyplot as plt

imgpath = "test.tiff"

plt.subplot(1,2,1)
plt.imshow(img,cmap='gray')
plt.title('image')
plt.xticks([])
plt.yticks([])

plt.subplot(1,2,2)
plt.hist(img.ravel(),256,[0,255])
plt.title('histogram')

plt.show()```