Brandon J
Brandon J

Reputation: 73

Plotting Histogram of Gray image

I am trying to figure out a way to find the histogram of a grayscale image. So first i found the average weight of the image then output it as a grayscale, fine. I'm just baffled by plotting the gray image into a histogram. Can someone help me figure out how to plot the grayscale image into a histogram?

import numpy as np
import matplotlib.pyplot as py
from PIL import Image as im
from scipy import misc


img = misc.imread("Zpicture.jpg")

def weightedAverage(pixel): ## function to calculate
    return 0.299*pixel[0] + 0.587*pixel[1] + 0.114*pixel[2]

grey = np.zeros((img.shape[0], img.shape[1])) # init 2D numpy array
# get row number
for rownum in range(len(img)):
 for colnum in range(len(img[rownum])):
  grey[rownum][colnum] = weightedAverage(img[rownum][colnum])


 py.imshow(grey, cmap = py.matplotlib.cm.Greys_r)
 py.show()

Upvotes: 1

Views: 3786

Answers (4)

Don Feto
Don Feto

Reputation: 1484

You can Use seaborn Library to draw a Histogram of grayscale or RGB channels like that

In case The image RGB Using Seaborn

import seaborn as sns
blue_bricks = cv2.imread('../DATA/bricks.jpg') #incase the image RGB
    show_bricks = cv2.cvtColor(blue_bricks, cv2.COLOR_BGR2RGB)   
     a=show_bricks[:,:,0] #need to be flatten to be showen in histplot 
        z=a.reshape(1,-1) #flatten the image
        sns.histplot(np.squeeze(z))

For GrayScale Image Using Seaborn

blue_bricks = cv2.imread('../DATA/bricks.jpg')
     a=show_bricks[:,:] 
        z=a.reshape(1,-1) #flatten the image
        sns.histplot(np.squeeze(z))

Using OpenCv

 import cv2
    import numpy as np
    import matplotlib.pyplot as plt
    %matplotlib inline
    hist_values = cv2.calcHist([dark_horse],channels=[0],mask=None,histSize=[256],ranges=[0,256])
    plt.plot(hist_values)

Upvotes: 0

Nagabhushan S N
Nagabhushan S N

Reputation: 7267

You can achieve this by using matplotlib.pyplot.hist and numpy.ndarray.ravel()

from matplotlib import pyplot as plt

gray_image = cv2.imread("Zpicture.jpg", cv2.IMREAD_GRAYSCALE)
plt.hist(gray_image .ravel(), bins=255)
plt.show()

Note: I'm using numpy-v1.15

Upvotes: 0

Trekkie
Trekkie

Reputation: 994

Consider using Seaborn. It is a wrapper of Matplotlib that offers a slightly more streamlined API.

import seaborn as sn

sn.distplot(grey, bins=100, kde=False)
sn.plt.show()

Check the documentation for keyword arguments. kde set to True would perform a KDE fit of the histogram.

Upvotes: 0

VBB
VBB

Reputation: 1325

I think you are looking for plt.hist(grey). Note that the usual convention is import matplotlib.pyplot as plt. It is good to stick to commonly used styles!

Lastly, your image conversion code can be simplified as:

grey = 0.299*img[:,:,0] + 0.587*img[:,:,0] + 0.114*img[:,:,0]

Upvotes: 3

Related Questions