使用PIL有效地从图像中提取前5个像素 [英] efficiently extract first 5 pixels from image using PIL
问题描述
我有一大包.jpg的天空图片,其中有些是人为的白色.对于每个像素,这些图像均设置为(255,255,255).我需要挑选这些图像.通过仅查看前5个像素来做到这一点.我的代码是:
I have a large package of .jpg images of the sky, some of which are artificially white; these images are set to (255, 255, 255) for every pixel. I need to pick these images out. I do so by only looking at the first 5 pixels. my code is :
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个像素,以免出现误报.
However, this process takes a large amount of time because im.getdata() returns the whole image, is there a different function I can use to return less data, or perhaps specific pixels? I need to look at multiple pixels because other images may have one or two pixels that are completely white, so I look at 5 pixels in order to not get false positives.
推荐答案
You can use the Image.getpixel
method:
im = Image.open(imagepath)
if all(im.getpixel((0, x)) == (255, 255, 255) for x in range(5)):
# Image is saturated
这假设您的图片每行至少有五个像素.
This assumes that your image has at least five pixels in each row.
通常,访问单个像素比加载整个图像并弄乱 PixelAccess
对象.但是,对于所用图像的一小部分,加载整个图像可能会浪费很多时间.
Normally, accessing individual pixels is much slower than loading the whole image and messing around with a PixelAccess
object. However, for the tiny fraction of the image you are using, you will probably lose a lot of time loading the entire thing.
您可以通过调用load
.Image.crop"rel =" nofollow noreferrer> crop
:
You may be able to speed things up by calling load
on a sub-image returned lazily by crop
:
im = Image.open(imagepath).crop((0, 0, 5, 1)).load()
if all(x == (255, 255, 255) for x in im):
# Image is saturated
这篇关于使用PIL有效地从图像中提取前5个像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!