Python PIL 检测图像是全黑还是全白 [英] Python PIL Detect if an image is completely black or white

查看:92
本文介绍了Python PIL 检测图像是全黑还是全白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Python 成像库 PIL 如何检测图像的所有像素是黑色还是白色?

Using the Python Imaging Library PIL how can someone detect if an image has all it's pixels black or white?

~更新~

条件:遍历每个像素!

推荐答案

if not img.getbbox():

... 将测试图像是否全黑.(如果图像中没有非黑色像素,Image.getbbox() 返回虚假的 None,否则它返回一个点元组,这是真的.)测试一张图片是否全白,先反转:

... will test to see whether an image is completely black. (Image.getbbox() returns the falsy None if there are no non-black pixels in the image, otherwise it returns a tuple of points, which is truthy.) To test whether an image is completely white, invert it first:

if not ImageChops.invert(img).getbbox():

您也可以使用 img.getextrema().这将告诉您图像中的最高值和最低值.要最轻松地使用它,您应该首先将图像转换为灰度模式(否则极值可能是 RGB 或 RGBA 元组,单个灰度值,索引,你必须处理所有这些).

You can also use img.getextrema(). This will tell you the highest and lowest values within the image. To work with this most easily you should probably convert the image to grayscale mode first (otherwise the extrema might be an RGB or RGBA tuple, or a single grayscale value, or an index, and you have to deal with all those).

extrema = img.convert("L").getextrema()
if extrema == (0, 0):
    # all black
elif extrema == (1, 1):
    # all white

后一种方法可能会更快,但在大多数应用程序中您不会注意到(两者都非常快).

The latter method will likely be faster, but not so you'd notice in most applications (both will be quite fast).

上述技术的单行版本,用于测试黑色或白色:

A one-line version of the above technique that tests for either black or white:

if sum(img.convert("L").getextrema()) in (0, 2):
    # either all black or all white

这篇关于Python PIL 检测图像是全黑还是全白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆