PIL Image构造来自numpy数组的怪异图像 - 为什么?

时间:2015-09-21 16:53:09

标签: python image numpy python-imaging-library pep3118

我想要一种方法来生成红色,绿色或蓝色的小RGB方形图像。它应该产生坚固的色块,但PIL输出的图像非常奇怪。为什么呢?

<html>
<script>  
  var wrapperFn = function(){
    this.bam = function(){};
    console.log(this === window);  //true
  };

  wrapperFn.apply(window);
  window.bam() //runs bam
</script>
</html>

此代码返回以下numpy数组:

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

但是它产生和保存的图像都搞砸了(它应该是3x3,所以我把它放大了所以你可以看得更清楚):

scaled up copy of output image

1 个答案:

答案 0 :(得分:5)

您需要设置dtype:

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