使用PIL有效地从图像中提取前5个像素

时间:2017-05-22 20:06:31

标签: python image python-imaging-library

我有一大包天空的.jpg图像,其中一些是人工白色的;对于每个像素,这些图像被设置为(255,255,255)。我需要选择这些图像。我这样做只看前5个像素。我的代码是:

im = Image.open(imagepath)
imList = list(im.getdata())[:5]
if imList = [(255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255)]:
    return True

然而,这个过程需要花费大量的时间,因为im.getdata()返回整个图像,是否有一个不同的函数可以用来返回更少的数据,或者可能是特定的像素?我需要查看多个像素,因为其他图像可能有一个或两个完全为白色的像素,所以我看了5个像素,以免得到误报。

1 个答案:

答案 0 :(得分:0)

您可以使用Image.getpixel方法:

im = Image.open(imagepath)
if all(im.getpixel((0, x)) == (255, 255, 255) for x in range(5)):
    # Image is saturated

这假设您的图像每行至少有五个像素。

通常情况下,访问单个像素比加载整个图像和使用PixelAccess对象搞乱要慢得多。但是,对于您使用的图像的一小部分,您可能会失去大量时间加载整个图像。

您可以通过load懒惰地返回的子图像上调用crop来加快速度:

im = Image.open(imagepath).crop((0, 0, 5, 1)).load()
if all(x == (255, 255, 255) for x in im):
    # Image is saturated