Python检查图像是灰度还是彩色的最快方法?

问题描述 投票:1回答:2

我想使用Python检查图像是灰度还是彩色。我知道我们可以读取图像并轻松检查,但是,我想知道是否有一种方法可以不读取完整图像吗?

我有大约2亿张图像(200x200),因此就运行时间而言,读取每个图像都是不可行的。

谢谢

python rgb grayscale
2个回答
0
投票

也许您可以放置​​size之类的条件,用两个样本进行测试:

伪造的例子:-'image_color.png'大小= 4000字节-'image_grey.png'大小= 600字节

您必须创建图像名称的集合:

import os
if os.stat('image.png').st_size > 250:
  print('Is Color! :)')

os参数的结果以字节为单位

问候!


0
投票

尽管我不能确定这将是最有效的,但我确信它的性能将比大多数操作更好。

因此请考虑使用ImageStat模块。

from PIL import Image, ImageStat

def is_grayscale(path="image.jpg")
    im = Image.open(path).convert("RGB")
    stat = ImageStat.Stat(im)
    if sum(stat.sum)/3 == stat.sum[0]: #check the avg with any element value
        return True #if grayscale
    else:
        return False #else its colour

stat.sum给出列表视图中所有像素的总和= [R,G,B],例如[568283302.0、565746890.0、559724236.0]。对于灰度图像,列表的所有元素均相等。

© www.soinside.com 2019 - 2024. All rights reserved.