简体   繁体   中英

how to find occurrences of elements in a list of list in python

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

You can use sum .

def pixel_frequency(value, image):
    return (image == value).sum()

pixel_frequency(255, pixelmatrix)
# 137 (or something)
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.

假设您正在谈论列表的实际列表(您的帖子中缺少一些逗号,这就是我这么说的原因),然后尝试:

numOccurrences = sum([row.count(255) for row in pixelmatrix])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM