2

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

dcheng
  • 1,827
  • 1
  • 11
  • 20

2 Answers2

3

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')
Community
  • 1
  • 1
jedwards
  • 29,432
  • 3
  • 65
  • 92
  • Is there no way to go from using pure python lists to PNG? – dcheng Mar 20 '15 at 10:58
  • @dcheng there is, there are a list of alternatives on the the other question I linked in my answer. I'll also edit this answer to show you how you could use numpy and pillow to create your PNG file. – jedwards Mar 20 '15 at 11:09
1

With PyPNG's recent release your code now works!

David Jones
  • 4,766
  • 3
  • 32
  • 45