Search code examples
pythonpypng

How to make 2d images with PyPNG with 2D Python Lists


So reading the readme, I expected the following code:

import png
R = 10
G = 255
B = 0
color = [[ (R,G,B), (R,G,B), (R,G,B) ],
         [ (R,G,B), (R,G,B), (R,G,B) ]]

png.from_array(color, 'RGB').save("small_smiley.png")

to output a 2x3 image.

However, I get assertion errors (no description provided).

Is there something I'm doing wrong? Is there a way to convert a 2D python list into an image file that's easier than messing with PyPNG?

Thanks


Solution

  • PyPNG's from_array doesn't support 3 dimensional matrices.

    From the source comment for from_array:

    The use of the term 3-dimensional is for marketing purposes only. It doesn't actually work. Please bear with us. Meanwhile enjoy the complimentary snacks (on request) and please use a 2-dimensional array.

    Instead, consider the Numpy/PIL/OpenCV approaches described here.


    Edit: The following code works, using numpy and Pillow:

    from PIL import Image  # Pillow
    import numpy as np     # numpy
    
    R = 10
    G = 255
    B = 0
    color = [[ (R,G,B), (R,G,B), (R,G,B) ],
             [ (R,G,B), (R,G,B), (R,G,B) ]]
    
    img = Image.fromarray(np.asarray(color, dtype=np.uint8))
    img.save('small_smiley.png')