您不想在图像上运行 for 循环 - 这对狗来说很慢 - 不要不尊重狗。使用 Numpy。
#!/usr/bin/env python3
import numpy as np
import random
# Generate a random image 640x150 with many colours but no black or white
im = np.random.randint(1,255,(150,640,3), dtype=np.uint8)
# Draw a white rectangle 100x100
im[10:110,10:110] = [255,255,255]
# Draw a black rectangle 10x10
im[120:130,200:210] = [0,0,0]
# Count white pixels
sought = [255,255,255]
white = np.count_nonzero(np.all(im==sought,axis=2))
print(f"white: {white}")
# Count black pixels
sought = [0,0,0]
black = np.count_nonzero(np.all(im==sought,axis=2))
print(f"black: {black}")
输出
white: 10000
black: 100
如果您的意思是想要黑色或白色像素的计数,您可以将上面的两个数字相加,或者像这样一次性测试两个数字:
blackorwhite = np.count_nonzero(np.all(im==[255,255,255],axis=2) | np.all(im==[0,0,0],axis=2))
如果您需要百分比,请记住像素总数很容易计算:
total = im.shape[0] * im.shape[1]
关于测试,它与任何软件开发一样——习惯于生成测试数据并使用它:-)