4

I 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 inspect the value of 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 has still too much values for matplotlib so my idea was to loop over unq and remove every value which deviates only x from it's 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)

Though this method works it is very inefficient as it does not uses numpy's optimized implementations.

Is there a numpy feature would could do this for me?

Just noticed that my algorithm looses information about how often a color occurs. Let me try to fix this.

2

1 Answer 1

13

If you just want to compute the histogram, you can use np.histogram:

bin_counts, bin_edges = np.histogram(img, bins, ...)

Here, bins could either be the number of bins, or a vector specifying the upper and lower bin edges.

If you want to plot the histogram, the easiest 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 out the image array before computing the histogram. If you pass a 2D array to plt.hist(), it will treat each row as a separate data series, which is not what you want here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the great tipp with plt.hist(img.ravel())! How can I read the gray value from the histogram (scale only goes from 0 to 0.8)?
Not sure what you mean. The x-axis represents gray values, and the y-axis represents frequency. If the x scale runs from 0 to 0.8 then all of your gray values lie between 0 and 0.8, which looks consistent with the values you show in unq.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.