How, given the 2D arrayMatrix array, which contains the “triplets” of RGB values, generates an image?

You see, most of the messages that discuss image creation are related to the 3D matrix [0] [1] [2], which actually contains the necessary information for direct application

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

However, I am stuck in a massive matrix with columns "3n" and "n". As you can see, the “image” is encoded in a way that reminds me of the P3 / P6 formats:

[ 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 aforementioned 2D matrix represents 3x3 "pixels", and using Image.fromarray an image full of holes is created. I thought about splitting it into three (!!!) 2-dimensional arrays, and then using np.dstack , but that sounds terribly inefficient, as the code dynamically generates thousands of large-sized matrixes (700x2100), which should be presented as images.

This is what I am going to do, 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')

Thank!

+4
source share
1 answer

numpy.reshapeshould work for this. It is also important that the color values ​​are 8-bit unsigned:

>>> 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 is similar to what we 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)
+3
source

Source: https://habr.com/ru/post/1660407/


All Articles