How to count the number of pixels of a certain color in python?

前提是你 提交于 2019-12-09 06:14:30

问题


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.


回答1:


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))



回答2:


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!




回答3:


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)


来源:https://stackoverflow.com/questions/28576203/how-to-count-the-number-of-pixels-of-a-certain-color-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!