繁体   English   中英

如何才能在PIL图像中获得红色像素和黑色像素

[英]how can i get no of red pixels and no of black pixels in PIL image

from PIL import ImageGrab
pil_img=ImageGrab.grab([0,0,1000,1000])

现在我想要在两个单独的变量中没有红色像素和黑色像素。所以我应该如何继续使用pil_img 图像看起来像这样

使用pil_img.getpixel((x, y))pil_img[x, y]

如果你不在所有像素上自己编写循环,它会快得多。

import os.path
from collections import Counter

from PIL import Image

path_to_file = os.path.join('..', '..', 'img', '9BLW9.jpg')

# Count the number of occurrences per pixel value for the entire image
img = Image.open(path_to_file)
pixels = img.getdata()
print(Counter(pixels))

# Count the number of occurrences per pixel value for a subimage in the image
img = img.crop((100, 100, 200, 200))
pixels = img.getdata()
print(Counter(pixels))

因此:

Counter({(248, 8, 9): 1002251, (0, 0, 0): 735408, (248, 8, 11): 8700, (245, 9, 9): 7200, ...)
Counter({(0, 0, 0): 5992, (248, 8, 9): 1639, (3, 0, 0): 33, (0, 6, 0): 23, ...)

您有两个以上像素值的事实是由JPG伪影造成的。 您可以编写一些自定义逻辑来查看像素是否更像黑色或红色,并将它们计算为那些。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM