23.9.12

Get Unique Pixel Values By Channel (RGBA) using Python

The following code sample shows how to extract a list of unique pixel values for each channel in an image using the Python Imaging Library (PIL).

def getUniquePixelValuesByChannel(imagePath, hexBase=True):
    '''
    returns lists of unique pixel value for each channel in image(r,g,b,a)
    '''
    image = Image.open(imagePath)
    histogram = image.histogram()
    channels = [histogram[p : p + 256] for p in range(0, len(histogram), 256)]
    unique_pixels = []
    for c in channels:
        unique_pixels.append([hexBase and hex(p) or p for p in range(len(c)) if c[p] > 0])
    return unique_pixels

This function uses the image.histogram() method to get a list of the frequencies of each pixel value across each color channel (red, green, blue, alpha).  For a 4-band image, the resulting list is 1024 values long (256 for each channel) with the index of each item representing the color value in that channel.  

Below is an example of the function in-action returning the unique values for each channel in either hex or 256:

if __name__ == '__main__':

    imagePath = r'lookAtMyPixelValuesInHex.png'

    pixelValuesInHex = getUniquePixelValuesByChannel(imagePath, True)
    print 'hex result:', pixelValuesInHex
    '''
    hex result: [
        ['0x0', '0x7', '0xf', '0x17', '0x1f', '0x27', '0x37', '0xfd'], 
        ['0x7', '0xf', '0x17', '0x1f', '0x27', '0x2f', '0xfd'], 
        ['0x7', '0xf', '0x17', '0x1f', '0xfd'], 
        ['0x7', '0xf', '0x17', '0x1f', '0x27', '0x2f', '0x37', '0xfd']
    ]

    '''

    pixelValuesIn256 = getUniquePixelValuesByChannel(imagePath, False)
    print '256 color result:', pixelValuesIn256
    '''
    256 color result: [
        [0, 7, 15, 23, 31, 39, 55, 253], 
        [7, 15, 23, 31, 39, 47, 253], 
        [7, 15, 23, 31, 253], 
        [7, 15, 23, 31, 39, 47, 55, 253]
    ]
    '''


No comments:

Post a Comment