Search code examples
pythonimagenumpypython-imaging-librarypep3118

PIL Image constructs weird images from numpy array - why?


I want a method to generate small RGB square images, of either red, green or blue colour. It should produce solid blocks of colour, but the image output from PIL is very strange. Why?

import numpy as np
from PIL import Image

class MakeSquares():
    def __init__(self):

        self.num_rows = 3
        self.num_cols = 3

        self.colourmap = {'red': [255, 0, 0],
                      'green': [0, 255, 0],
                      'blue': [0, 0, 255]}

    def generateExample(self, label):
        arr = []
        colour = label
        colour_array = self.colourmap[colour]
        for i in range(0, self.num_rows):
            sarr = []
                for j in range(0, self.num_cols):
                    sarr.append(colour_array)
            arr.append(sarr)
        narr = np.asarray(arr)
        return narr

test = MakeSquares()
t = test.generateExample("red")
print t
testimage = Image.fromarray(t, "RGB")
testimage.save("testimage.jpg")

This code returns the following numpy array:

[[[255   0   0]
  [255   0   0]
  [255   0   0]]

 [[255   0   0]
  [255   0   0]
  [255   0   0]]

 [[255   0   0]
  [255   0   0]
  [255   0   0]]]

But the image it produces and saves is all messed up (it's only supposed to be 3x3 so I've scaled it up so you can see better):

scaled up copy of output image


Solution

  • You need to set the dtype:

    narr = np.asarray(arr,dtype=np.uint8)