The gaps in the histogram are due to a poor choice of bin size. If you call hist(..., bins=255)
, numpy will create 256 bins from the min-value to the max-value of your array. In other words, the bins will have non-integer width (in my tests: [ 24. , 24.86666667, 25.73333333, 26.6 , ....]
).
Because you are dealing with an image with 255 levels, you should create 255 bins of width 1:
plt.hist(a, bins=range(256))
We have to write 256
because we need to include the right-most edge of the bins, otherwise points with a value of 255 would not be included.
As for the color, follow the examples in the question linked in the comments
from PIL import Image
im=Image.open("lena.pgm")
a = np.array(im.getdata())
fig, ax = plt.subplots(figsize=(10,4))
n,bins,patches = ax.hist(a, bins=range(256), edgecolor='none')
ax.set_title("histogram")
ax.set_xlim(0,255)
cm = plt.cm.get_cmap('cool')
norm = matplotlib.colors.Normalize(vmin=bins.min(), vmax=bins.max())
for b,p in zip(bins,patches):
p.set_facecolor(cm(norm(b)))
plt.show()
