简体   繁体   中英

Counting black pixels using Python

I am in my first programming class so very new. I'm trying to count the black pixels in a picture and I'm stuck. This is what I have so far:

def main():
#create a 10x10 black picture
 newPict = makeEmptyPicture(10, 10)
 show(newPict)
 setAllPixelsToAColor(newPict,black)
 #Display the picture
 show(newPict)
 #Initialize variabl countBlack to 0 
 countZero = 0
 for p in getPixels(newPict):
     r = getRed(p)
     b = getBlue(p)
     g = getGreen(p)
     if (r,g,b) == (0,0,0):
        countZero = countZero + 100
     return countZero

How it was pointed by kedar and deets , your return is INSIDE the for, so, in the first pixel it will return the value of countZero, instead of looping over all the image, just fixing the indention should be fine :

 for p in getPixels(newPict):
     r = getRed(p)
     b = getBlue(p)
     g = getGreen(p)
     if (r,g,b) == (0,0,0):
        countZero = countZero + 1
 return countZero

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