Search code examples
pythonmayapyside2

Detect if all pixels in an image are the same color/value (Maya Python)


Follow-up question from previous question here. This code detects if all pixels in an image (8-bit greyscale jpg) are zero/black, using Pyside:

def all_black_pixels(path):
img = QImage(path)
if img.isNull():
    return False # or whatever you think appropriate

if not img.format() == img.Format_Grayscale8:
    img.convertTo(img.Format_Grayscale8)

# for PySide
return not any(img.constBits())

Would like to adapt this to check if all pixels in a channel are the same value. Solid red or solid grey, a flat constant color.

For example, on a bump map in L8 format (8-bit luminance) the pixels would be 50% grey on the red channel and black on green and blue, RGB[0.5, 0, 0]. On a normal map they would be RGB[0.5, 0.5, 1] (assuming a 0-1 RGB scale).

FWIW this is a height/bump map texture Output from Substance 3D Painter, and the Pyside2 would be running inside of Maya.


Solution

  • That doesn't differ that much from your previous question, as we don't really care about the representation of the image but only about its pixel values: as soon as any value is different from the first one, we know that the image has more than one "color".

    def all_pixels_identical(path):
        img = QImage(path)
        if img.isNull():
            return False # or whatever you think appropriate
    
        if not img.format() == img.Format_Grayscale8:
            img.convertTo(img.Format_Grayscale8)
    
        # for PySide
        it = iter(img.constBits())
        # for PyQt
        it = iter(img.constBits().asarray(img.sizeInBytes()))
    
        first = next(it)
        while True:
            try:
                if first != next(it):
                    return False
            except StopIteration:
                return True
    

    Note: I hadn't had the chance to test the code, so it's possible that it needs some fixing, but the concept is fundamentally correct. OTOH, I'd suggest you to do some research on how raster images are represented as raw data in memory, so that you could better understand such matters in the future.