Jim*_*ane 18 python python-imaging-library
使用Python Imaging Library PIL如何检测某个图像的所有像素是黑色还是白色?
〜〜更新
条件:不迭代每个像素!
kin*_*all 28
if not img.getbbox():
Run Code Online (Sandbox Code Playgroud)
...将测试图像是否完全是黑色.(Image.getbbox()返回falsy None如果有在图像中没有非黑色像素,否则返回点的元组,其是truthy.)要测试的图像是否完全是白色的,第一反转它:
if not ImageChops.invert(img).getbbox():
Run Code Online (Sandbox Code Playgroud)
你也可以使用img.getextrema().这将告诉您图像中的最高和最低值.为了最容易地使用它,您应该首先将图像转换为灰度模式(否则极值可能是RGB或RGBA元组,或单个灰度值或索引,您必须处理所有这些).
extrema = img.convert("L").getextrema()
if extrema == (0, 0):
# all black
elif extrema == (1, 1):
# all white
Run Code Online (Sandbox Code Playgroud)
后一种方法可能会更快,但在大多数应用程序中你都不会注意到(两者都会非常快).
以上技术的单行版本,可测试黑色或白色:
if sum(img.convert("L").getextrema()) in (0, 2):
# either all black or all white
Run Code Online (Sandbox Code Playgroud)
扩展到Kindall:如果你看一个名为img的图像:
extrema = img.convert("L").getextrema()
Run Code Online (Sandbox Code Playgroud)
它为您提供了图像中的一系列值.因此全黑图像将是(0,0)并且全白图像是(255,255).所以你可以看看:
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
Run Code Online (Sandbox Code Playgroud)
当我从一些数据创建缩略图并希望确保它正确读取时对我很有用.
from PIL import Image
img = Image.open("test.png")
clrs = img.getcolors()
Run Code Online (Sandbox Code Playgroud)
clrs 包含 [("num of occurences","color"),...]
通过检查len(clrs) == 1可以验证图像是否仅包含一种颜色,并且通过查看其中的第一个元组的第二个元素clrs可以推断出颜色。
如果图像包含多种颜色,那么如果99%的像素共享相同的颜色,那么通过考虑出现的次数,您还可以处理几乎完全单色的图像。
| 归档时间: |
|
| 查看次数: |
14086 次 |
| 最近记录: |