如何计算python中某种颜色的像素数? [英] How to count the number of pixels of a certain color in python?

查看:976
本文介绍了如何计算python中某种颜色的像素数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张黑色和红色两种颜色的图片,我需要能够计算图片中有多少像素是红色和多少像素是黑色的.

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.

推荐答案

我已将代码从0xd3更正为实际可用:

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

这篇关于如何计算python中某种颜色的像素数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆