Brandon J
Brandon J

Reputation: 73

how to find the histogram of an input image using python?

i am trying to find the histogram of an input image. But instead of seeing a histogram, the code runs then stops without showing anything. Can someone point out to me why this is happening?

import pylab as plt
import matplotlib.image as mpimg
import numpy as np

img = np.uint8(mpimg.imread('jack.jpg'))
# convert to grayscale
# do for individual channels R, G, B, A for nongrayscale images

img = np.uint8((0.2126* img[:,:,0]) + \
    np.uint8(0.7152 * img[:,:,1]) +\
         np.uint8(0.0722 * img[:,:,2]))


plt.histogram(img,10)
plt.show()

Upvotes: 1

Views: 668

Answers (1)

berna1111
berna1111

Reputation: 1861

You are confusing histogram with hist. And yes, plt.histogram is a call to numpy.histogram.

Try this:

import pylab as plt
import matplotlib.image as mpimg
import numpy as np

img = np.uint8(mpimg.imread('jack.jpg'))
# convert to grayscale
# do for individual channels R, G, B, A for nongrayscale images

img = np.uint8(0.2126 * img[:,:,0]) +\
      np.uint8(0.7152 * img[:,:,1]) +\
      np.uint8(0.0722 * img[:,:,2])

plt.hist(img,10)
plt.show()

[edit to answer comment]

According to the documentation (links above on the functions names), np.histogram will Compute the histogram of a set of data, returning:

  • hist : array The values of the histogram. [...]
  • bin_edges : array of dtype float Return the bin edges (length(hist)+1).

And plt.hist will Compute and draw the histogram of x, returning a tuple (n, bins, patches).

Upvotes: 2

Related Questions