简体   繁体   English

给定一个包含RGB值“三元组”的2D numpy arrayMatrix,如何生成图像?

[英]How to, given a 2D numpy arrayMatrix that contains “triplets” of RGB values generate an image?

You see, most of the posts that discuss image creation deal with a 3D Matrix[0][1][2] that effectively contains the necessary info to apply directly 您会看到,大多数讨论图像创建的帖子都涉及3D矩阵[0] [1] [2],该矩阵有效包含直接应用的必要信息

img = Image.fromarray(Matrix, 'RGB')

However, I'm stuck with a massive matrix that has "3n" columns and "n" rows. 但是,我坚持使用具有“ 3n”列和“ n”行的大型矩阵。 As you might see, the "image" is coded in a fashion reminding me of P3/P6 formats: 如您所见,“图像”的编码方式使我想起了P3 / P6格式:

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

The above 2D matrix represents 3x3 "pixels", and using Image.fromarray produces an image full of holes. 上面的2D矩阵表示3x3“像素”,并使用Image.fromarray生成充满孔的图像。 I've thinking of splitting it into three (!!!) 2 dimensional arrays and then using np.dstack but that sounds terribly inefficient as the code is dinamically generating thousands of matrices with large dimensions (700x2100) that need to be presented as images. 我想它分裂为三个(!)2个维数组,然后使用np.dstack但声音非常低效的代码生成dinamically数千矩阵的大尺寸(700x2100)需要被呈现为图像。

This is what I'm thinking of doing, btw: 我正在想做的是,顺便说一句:

R = np.zeros((Y, X), dtype = np.uint8) # Same for G & B
    for Row in range(Y):
        for Column in range(3*X):
            if Column % 3 == 0: # With Column-1 for G and -2 for B
                R[Row][Column/3] = 2DMatrix[Row][Column]
#After populating R, G, B
RGB0 = np.dstack([R, G, B])
img = Image.fromarray(RGB0, 'RGB')

Thanks! 谢谢!

numpy.reshape should work for this. numpy.reshape应该适用于此。 It's also important that the color values are 8-bit unsigned: 颜色值必须是8位无符号的,这一点也很重要:

>>> import numpy as np

>>> a = [[0, 0, 0, 255, 255, 255, 0, 0, 0],
...      [0, 0, 0, 255, 255, 255, 0, 0, 0],
...      [255, 255, 255, 0, 0, 0, 255, 255, 255]]
>>> a = np.array(a)
>>> a.astype('u1').reshape((3,3,3))

array([[[  0,   0,   0],
        [255, 255, 255],
        [  0,   0,   0]],

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

       [[255, 255, 255],
        [  0,   0,   0],
        [255, 255, 255]]], dtype=uint8)

>>> import PIL.Image
>>> i = PIL.Image.fromarray(a.astype('u1').reshape((3,3,3)), 'RGB')

This seems to work the way we would expect: 这似乎按照我们期望的方式工作:

>>> i.size
(3, 3)
>>> i.getpixel((0,0))
(0, 0, 0)
>>> i.getpixel((1,0))
(255, 255, 255)
>>> i.getpixel((2,0))
(0, 0, 0)
>>> i.getpixel((0,1))
(0, 0, 0)
>>> i.getpixel((1,1))
(255, 255, 255)
>>> i.getpixel((2,1))
(0, 0, 0)
>>> i.getpixel((0,2))
(255, 255, 255)
>>> i.getpixel((1,2))
(0, 0, 0)
>>> i.getpixel((2,2))
(255, 255, 255)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM