Histogram of grayscale values ββin numpy image
I have loaded an image into a numpy array and want to plot its color values ββin a histogram.
import numpy as np from skimage import io from skimage import color img = io.imread('img.jpg') img = color.rgb2gray(img) unq = np.unique(img) unq = np.sort(unq)
When we check the value unq
, we will see something like
array([ 5.65490196e-04, 8.33333333e-04, 1.13098039e-03, ...,
7.07550980e-01, 7.09225490e-01, 7.10073725e-01])
which still has too many values ββfor matplotlib
, so my idea was to iterate over unq
and remove every value that only deviates x
from its predecessor.
dels = []
for i in range(1, len(unq)):
if abs(unq[i]-unq[i-1]) < 0.0003:
dels.append(i)
unq = np.delete(unq, dels)
While this method works, it is very inefficient as it does not use optimized versions of numpy.
Is there a numpy function for me?
Just noticed that my algorithm is losing information on how often the color occurs. Let me try to fix this.
source to share
If you just want to compute the histogram, you can use np.histogram
:
bin_counts, bin_edges = np.histogram(img, bins, ...)
This bins
can be either the number of bins or a vector defining the top and bottom edges of the edges.
If you want to plot a histogram, the simplest way would be to use plt.hist
:
bin_counts, bin_edges, patches = plt.hist(img.ravel(), bins, ...)
Note that I used img.ravel()
to flatten the image array before calculating the histogram. If you pass a 2D array to plt.hist()
, it will treat each row as a separate data series, which is not needed here.
source to share