1

I want to measure pixel intensities in a 16 bit image. Therefore I did a numpy histogram that shows the number of Pixels against the grayscale value from 0 to 65535 (16 bit). I did it with

hist= numpy.histogram(grayscaleimage.ravel(), 65536, [0, 65536])

After that I measure the whole intensity of my image with (that means the sum of : number of pixels * pixel value for each):

Intensity = 0
for i in range(len(hist[0])):
    Intensity += hist[0][i]*hist[1][i]
print(Intesity)

Now I want to see my histogram. I don't know how to plot hist, although I have my needed values. Can someone help me with this?

2
  • 1
    Check out matplotlib? numpy.histogram documentation has an example right at the bottom.
    – Pam
    Feb 20, 2018 at 8:11
  • Yes I checked that example and tried bins = range (0, 65536) plt.hist (hist[0][i], bins) plt.show() but nothing happens. Either a shown plot nor an error?
    – Anja
    Feb 20, 2018 at 8:19

1 Answer 1

2

You can use matplotlib directly for this:

import matplotlib.pyplot as plt
plt.hist(grayscaleimage.ravel(), bins=np.linspace(0, 65536, 1000))
plt.show()   

Or use numpy like you already did and plot a barplot. However, you will have to set the width of the bars correctly by yourself and also skip the last bin entry so that it has the same dimension as the histogram:

import numpy as np
import matplotlib.pyplot as plt

hist, bin_edges = np.histogram(grayscaleimage.ravel(), bins = np.linspace(0, 65536, 1000))
plt.bar(bin_edges[:-1], hist, width=65536./1000)
plt.show()

I used only 1000 bins here, but you can also choose more, depending on the size of your image.

PS: If you want the total intensity, you do not have to iterate over all bins. You will get a more accurate result by just summing up all pixel values in your image np.sum(grayscaleimage).

1
  • It works for me but it takes a lot of time even when I use a 100x100 image. You could try to increase the 1000 bins stepwise and chose a suitable value for your image.
    – a.smiet
    Feb 20, 2018 at 8:59

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.