如何在PIL-imag中不使用红色像素,也不使用黑色像素

2024-04-23 22:54:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

现在我想得到两个独立的红色像素和黑色像素变量。所以{1}该怎么办


Tags: fromimportimgpil像素grab黑色红色
2条回答

如果不在所有像素上自己写一个循环,速度会快得多。在

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

结果是:

^{pr2}$

事实上,你有两个以上的像素值是由于JPG人工制品。您可以编写一些自定义逻辑来查看像素是否更像黑色或红色,并将它们也计算在内。在

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

相关问题 更多 >