Reputation: 37
I have just started learning python.
I converted an image into a matrix of gray pixels (0=black, 255=white)
from PIL import Image
import numpy
import array
im = Image.open("elephant.jpg")
grayim = im.convert('L')
pixelmatrix = numpy.asarray(grayim)
If I
print pixelmatrix
I get something like:
pixelmatrix = [154 154 154 ..., 169 169 169]
[153 153 153 ..., 166 166 166]
[153 153 153 ..., 161 161 161]
...,
[151 130 107 ..., 51 85 75]
[130 133 111 ..., 86 92 56]
[ 91 127 119 ..., 102 139 66]]
That is what I'm looking for. Ok
What I want to do is evaluate the occurrence of one value, let's say 255.
I tried for cycles and .count method.
for x in range(0, lastrow):
for y in range(0, lastcolumn):
print sum(pixelmatrix[x,y]
They don't work and I cannot understand why. Could you help me?
Thanks a lot Ciao
Giacomo
Upvotes: 1
Views: 201
Reputation: 8633
from PIL import Image
import numpy
import array
im = Image.open("elephant.jpg")
grayim = im.convert('L')
pixelmatrix = numpy.asarray(grayim)
no_occurrences = numpy.sum(pixelmatrix==255)
print(no_occurrences)
EDIT: removed redundant step in the code snippet and added print statement.
Upvotes: 2
Reputation: 8829
You can use sum
.
def pixel_frequency(value, image):
return (image == value).sum()
pixel_frequency(255, pixelmatrix)
# 137 (or something)
Upvotes: 3
Reputation: 1116
Assuming you're talking about an actual list of lists (there are some commas missing in your post which is why I'm saying this), then try:
numOccurrences = sum([row.count(255) for row in pixelmatrix])
Upvotes: 1