dcheng
dcheng

Reputation: 1847

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

Upvotes: 2

Views: 1872

Answers (2)

David Jones
David Jones

Reputation: 5159

With PyPNG's recent release your code now works!

Upvotes: 1

jedwards
jedwards

Reputation: 30210

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')

Upvotes: 3

Related Questions