Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 817
bibbly bobbly Avatar asked Aug 24 '26 10:08

bibbly bobbly


1 Answers

You need to set the dtype:

narr = np.asarray(arr,dtype=np.uint8)
like image 158
Padraic Cunningham Avatar answered Aug 26 '26 00:08

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!