How to count the number of pixels of a certain col

2019-03-29 08:42发布

I have a picture of two colours, black and red, and I need to be able to count how many pixels in the picture are red and how many are black.

标签: python jes
3条回答
手持菜刀,她持情操
2楼-- · 2019-03-29 09:24

I corrected code from 0xd3 to actually work:

from PIL import Image
im = Image.open('black.jpg')

black = 0
red = 0

for pixel in im.getdata():
    if pixel == (0, 0, 0): # if your image is RGB (if RGBA, (0, 0, 0, 255) or so
        black += 1
    else:
        red += 1
print('black=' + str(black)+', red='+str(red))
查看更多
在下西门庆
3楼-- · 2019-03-29 09:27

According to http://personal.denison.edu/~bressoud/cs110-f12/Supplements/JESHelp/7_Picture_Functions.html , JES offers simple functions that do all you require, and something like

black = makeColor(0, 0, 0)
red = makeColor(255, 0, 0)
numblacks = numreds = 0
for pixel in getPixels(picture):
    color = getColor(pixel)
    if color == black: numblacks += 1
    elif color == red: numreds += 1

should easily do all you require (after whatever imports may be needed to make the functions available -- I don't have JES, nor have I ever seen or used it before; all I have is that doc which I found with a web search).

However, this seems so trivially easy that I guess there must be more to it -- I can't imagine anybody "stuck on this for three days" (!). But if as I suspect there's more, you have to be the one telling us -- what exactly is wrong with this code (plus whatever imports, def, return, or print, or whatever, your exact assignment requires) that appears to be using JES's functions to trivially solve the problem?! We can't help you unless you help us help you!

查看更多
相关推荐>>
4楼-- · 2019-03-29 09:39

First you need install pillow library.

sudo pip3 install pillow

from PIL import *
im = Image.open("your picture")

for pixel in im.getdata():
    if pixel is (0,0,0):
        black += 1
    else:
        red += 1
print("black = " + black + "red = " + red)
查看更多
登录 后发表回答