Search code examples
pythonimage-processingpython-imaging-libraryrgbgrayscale

Python: grayscale image to RGB image with provided palette


I am stuck with a problem.

I want to convert many greyscale images to RGBA with my dictionary palette where greyScale value = (r,g,b) (adding transparency 0 where the pixel is 0).

I wrote some code but it takes ~0.3sec to end one transformation. Is there some faster way to get better performance?

Thanks <3

My code

My Dict:


Solution

  • The performance depends on your image resolution. But you can use Numpy like this for the case.

    import numpy as np
    from PIL import Image
    
    def grayscale_to_rgba_optimized(image, palette):
        """Converts a grayscale image to RGBA using a dictionary palette efficiently.
    
        Args:
            image: A 2D grayscale image array.
            palette: A dictionary mapping grayscale values to RGBA tuples.
    
        Returns:
            A 3D RGBA image array.
        """
    
        lookup_array = np.array([palette.get(i, (0, 0, 0, 0)) for i in range(256)])
        rgba_image = lookup_array[image]
        return rgba_image
    
    colors = {
        -35: (243, 243, 243),
        -30: (207, 207, 207),
        ......
        90: (77, 77, 77)
    }
    
    gray_img = Image.open('Your_Image_Path.png').convert('L')
    gray_array = np.array(gray_img)
    
    rgba_image = grayscale_to_rgba_optimized(gray_array, colors)
    
    # Save the result as a PNG image (transparency will be preserved)
    result_image = Image.fromarray(rgba_image, 'RGBA')
    result_image.save("output_image.png")