0

I would like to present a histogram from an image in Python. Doing some research, I found a way of doing it using matplotlib. So, I just do this:

im = plt.array(Image.open('Mean.png').convert('L'))
plt.figure()
plt.hist(im, facecolor='green', alpha=0.75)
plt.savefig("Histogram.png")

But I didn't like what I got:

Histogram

The bars are not green, and it's kind of complicated to read the histogram. I could not even figure out if the x axis is the number of points and y axis the rgb color or the inverse... :S I would like to know if somebody knows how could I turn this histogram more readable.

Thanks in advance.

pceccon
  • 9,379
  • 26
  • 82
  • 158

1 Answers1

1

To get the histogram you have to flatten your image:

img = np.asarray(Image.open('your_image').convert('L'))
plt.hist(img.flatten(), facecolor='green', alpha=0.75)

Since you converted the image to grayscale with convert('L') the x axis is the grayscale level from 0-255 and the y axis is the number of pixels.

You can also control the number of bins using the bins parameter:

plt.hist(img.flatten(), bins=100, facecolor='green', alpha=0.75)
Viktor Kerkez
  • 45,070
  • 12
  • 104
  • 85
  • Do you know how could I do this passing an list of list? In this case, I can't use the flatten method, but doing this _plt.hist(self.data, bins=10, facecolor='green', alpha=0.5)_, I got something like the image that I posted before. I don't get it. :S – pceccon Sep 15 '13 at 23:50
  • @pceccon You have to pass in a one dimensional structure. If you have a list of lists you have to flatten in somehow... Many possible solutions [here](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python). The easiest, but not the fastest would be just to do `plt.hist(sum(self.data), ...)` – Viktor Kerkez Sep 16 '13 at 00:04