Simone
Simone

Reputation: 4940

Efficiently scan and check pixels in an image

I would like to know which is the most efficient way to check if all pixels in an image have the same value.
The script below checks, by a for cycle, if all pixels have value equal to 0:

black_masks_lst = []

for msk in glob.glob('/content/Maschere/*png')
  msk = Image.open(msk).getdata()
  flag = True
  for pxl in msk:
    if pxl != 0: flag = False
  if flag == True: black_masks_lst.append(msk)

Which could be a more efficient way to implement this code?

Upvotes: 0

Views: 453

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207530

A very simple, and performant way of checking if all pixels are the same, would be to use PIL's getextrema() which tells you the brightest and darkest pixel in an image. So you would just test if they are the same and that would work if testing they were both zero, or any other number. It will be performant because it is implemented in C.

min, max = msk.getextrema()
if min == max:
    ...

If you wanted to use Numpy, in a very similar vein, you could use its np.ptp() which tells you the "peak-to-peak" difference between brightest and darkest pixel:

import numpy as np

# Make Numpy array from image "msk"
na = np.array(msk)
diff = np.ptp(na)
if diff == 0:
    ...

Or, you could test if true that all elements equal the first:

result = np.all(na == na[0])

Upvotes: 1

Сергей Кох
Сергей Кох

Reputation: 1723

  1. Convert image to 3D numpy array enter link description here
  2. Check if all elements of an array are the same enter link description here

Upvotes: 0

Related Questions