efficiently extract first 5 pixels from image usin

2019-08-04 06:13发布

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

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.

1条回答
Animai°情兽
2楼-- · 2019-08-04 07:05

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.

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.

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
查看更多
登录 后发表回答