简体   繁体   English

Python PIL检测图像是完全黑色还是白色

[英]Python PIL Detect if an image is completely black or white

Using the Python Imaging Library PIL how can someone detect if an image has all it's pixels black or white? 使用Python Imaging Library PIL如何检测图像的所有像素是黑色还是白色?

~Update~ 〜〜更新

Condition: Not iterate through each pixel! 条件: 迭代每个像素!

if not img.getbbox():

... 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: (如果图像中没有非黑色像素,则Image.getbbox()返回虚假的None ,否则返回一个点元组,这是真实的。)要测试图像是否完全是白色,请先将其反转:

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

You can also use img.getextrema() . 您也可以使用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). 为了最容易地解决这个问题,您应该首先将图像转换为灰度模式(否则极值可能是RGB或RGBA元组, 单个灰度值索引,您必须处理所有这些)。

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

Expanding on Kindall: if you look at an image called img with: 扩展到Kindall:如果你看一个名为img的图像:

extrema = img.convert("L").getextrema()

It gives you a range of the values in the images. 它为您提供了图像中的一系列值。 So an all black image would be (0,0) and an all white image is (255,255). 因此全黑图像将是(0,0)并且全白图像是(255,255)。 So you can look at: 所以你可以看看:

if extrema[0] == extrema[1]:
    return("This image is one solid color, so I won't use it")
else:
    # do something with the image img
    pass

Useful to me when I was creating a thumbnail from some data and wanted to make sure it was reading correctly. 当我从一些数据创建缩略图并希望确保它正确读取时对我很有用。

from PIL import Image
img = Image.open("test.png")
clrs = img.getcolors()

clrs contains [("num of occurences","color"),...] clrs包含[("num of occurences","color"),...]

By checking for len(clrs) == 1 you can verify if the image contains only one color and by looking at the second element of the first tuple in clrs you can infer the color. 通过检查len(clrs) == 1您可以验证图像是否只包含一种颜色,并通过查看clrs中第一个元组的第二个元素,您可以推断出颜色。

In case the image contains multiple colors, then by taking the number of occurences into account you can also handle almost-completly-single-colored images if 99% of the pixles share the same color. 如果图像包含多种颜色,那么通过考虑出现的次数,如果99%的像素共享相同的颜色,您还可以处理几乎完全单色的图像。

I tried the Kindall solution ImageChops.invert(img).getbbox() without success, my test images failed. 我尝试了Kindall解决方案ImageChops.invert(img).getbbox()但没有成功,我的测试图像失败了。

I had noticed a problem, white should be 255 BUT I have found white images where numeric extrema are (0,0).. why? 我注意到了一个问题,白色应该是255 但是我发现了数字极值为(0,0)的白色图像..为什么? See the update below. 请参阅下面的更新。

I have changed Kindall second solution (getextrema), that works right, in a way that doesn't need image conversion, I wrote a function and verified that works with Grayscale and RGB images both: 我已经改变了Kindall第二个解决方案(getextrema),它运行正常,不需要图像转换,我编写了一个函数并验证了它可以与灰度和RGB图像一起使用:

def is_monochromatic_image(img):
    extr = img.getextrema()
    a = 0
    for i in extr:
        if isinstance(i, tuple):
            a += abs(i[0] - i[1])
        else:
            a = abs(extr[0] - extr[1])
            break
    return a == 0

The img argument is a PIL Image object. img参数是PIL Image对象。 You can also check, with small modifications, if images are black or white.. but you have to decide if "white" is 0 or 255, perhaps you have the definitive answer, I have not. 如果图像是黑色或白色,你也可以通过小的修改检查..但是你必须决定“白色”是0还是255,也许你有明确的答案,我没有。 :-) Hope useful :-)希望有用

UPDATE : I suppose that white images with zeros inside.. may be PNG or other image format with transparency. 更新 :我认为内部带有零的白色图像可能是PNG或其他具有透明度的图像格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM