首先,用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