Reputation: 33
I'm using Numpy and Python2.7, and I'm writing a function that counts the amount of times a color appears per column of pixels as I read-in an image (Using PIL):
for i in range(wbmp.size[0]):
bcount = 0
for j in range(wbmp.size[1]):
if wbmp.getpixel((i,j)) == 1:
bcount = bcount + 1
bdict[i] = bcount
The dictionary returns as {Column#: # of times color appears}
, and I'd like to be able to perform a standard deviation on all of the values in the dictionary. Would I need to put them all into a list first? Or is there away to just pull it from the dictionary?
Upvotes: 3
Views: 5512
Reputation: 5522
The list of all values in the dictionary can be obtained with bdict.values()
, so you could use this:
std = np.std(bdict.values())
A faster way to do this would use more numpy:
img = np.array(img)
colour_mask = img == 1 # or whichever colour you want
per_col_count = colour_mask.sum(axis=0)
std = np.std(per_col_count)
colour_mask
is a boolean mask, and summing it along axis 0 adds up all True
values for every column. This is bound to be much faster, and the difference will increase with the size of the image.
Upvotes: 4
Reputation: 46578
Your dictionary already has the list you want,
bdict.values()
So you can call std
on this:
np.std(bdict.values())
But I would recommend converting your image into a numpy array immediately, and doing a histogram along one axis, instead of using your version of counting.
from PIL import Image
i = Image.open('imfile.png')
a = np.array(i)
c = 1 # or whatever color you want
b = 256 # bit depth of image, so histogram bins are 1 color / bin
hists = np.array([ np.histogram(row, bins=b)[0] for row in a ])
s = hists[:,c].std()
Upvotes: 2