简体   繁体   中英

Python: numpy.histogram plot

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?

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM