有 python 识别颜色方块数量的第三方库推荐吗?

下图由黄,红,绿,蓝组成,如何获取每种颜色方块的数量?
如果用 python 来实现的话,有相关的库或例子吗,谢谢

图片描述

阅读 3.9k
1 个回答

首先,用Pillow把图片读到变量pic里面

from PIL import Image
img = Image.open("example.png")
pic = img.load()

然后, 得到图片的高度和宽度

w, h = img.width, img.height

然后,做个循环统计各种颜色数

result = {'y': 0, 'r': 0, 'g': 0, 'b': 0}

for i in range(w): 
    for j in range(h): 
        color = pic[i,j] 
        c = '?' 
        if color[0] > 127 and color[1] > 127: 
            c = 'y' 
        elif color[0] > 127: 
            c = 'r' 
        elif color[1] > 127: 
            c = 'g' 
        else: 
            c = 'b' 
        result[c] = result[c] + 1

我的结果是:

print(result)
> {'y': 50803, 'r': 10113, 'g': 45177, 'b': 161107}

# 总数也对的上
sum(result.values()) == w * h
> True
推荐问题