【问题标题】:PIL Image constructs weird images from numpy array - why?PIL Image 从 numpy 数组构造奇怪的图像 - 为什么?
【发布时间】:2015-12-18 11:18:39
【问题描述】:

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

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

此代码返回以下 numpy 数组:

[[[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]]]

但是它生成和保存的图像全乱了(它应该只是 3x3,所以我把它放大了,这样你可以看得更清楚):

【问题讨论】:

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


    【解决方案1】:

    你需要设置dtype:

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

    【讨论】:

    • 不用担心,dtype 被推断为int64,除非您明确传递它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多