Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在PIL图像中获得红色像素和黑色像素的数量_Python_Python 2.7_Python 3.x_Python Imaging Library_Pillow - Fatal编程技术网

Python 如何在PIL图像中获得红色像素和黑色像素的数量

Python 如何在PIL图像中获得红色像素和黑色像素的数量,python,python-2.7,python-3.x,python-imaging-library,pillow,Python,Python 2.7,Python 3.x,Python Imaging Library,Pillow,现在我想在两个独立的变量中分别得到红色像素和黑色像素的数量。那么我应该如何处理pil_img呢 from PIL import ImageGrab pil_img=ImageGrab.grab([0,0,1000,1000]) 因此: import os.path from collections import Counter from PIL import Image path_to_file = os.path.join('..', '..', 'img', '9BLW9.jpg')

现在我想在两个独立的变量中分别得到红色像素和黑色像素的数量。那么我应该如何处理pil_img呢

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

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

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

如果您对该问题进行投票,将不胜感激。我失去了提问的权限:-(您能告诉我您是如何看到我的问题的吗?最初,它的视图不超过10到15个。我使用标记Python图像库对问题进行过滤,并在向下滚动不太多后在列表中看到您的问题。
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, ...)