加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何在PIL图像中得不到红色像素和黑色像素

发布时间:2020-12-16 22:33:06 所属栏目:Python 来源:网络整理
导读:from PIL import ImageGrabpil_img=ImageGrab.grab([0,1000,1000]) 现在我想在两个单独的变量中没有红色像素和黑色像素.所以我应该如何继续pil_img 最佳答案 如果你不在所有像素上自己编写循环,它会快得多. import os.pathfrom collections import Counterfr

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

现在我想在两个单独的变量中没有红色像素和黑色像素.所以我应该如何继续pil_img

The image look likes this

最佳答案
如果你不在所有像素上自己编写循环,它会快得多.

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): 735408,(248,11): 8700,(245,9,9): 7200,...)
Counter({(0,0): 5992,9): 1639,(3,0): 33,6,0): 23,...)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读