Quiero crear una imagen PIL a partir de una matriz NumPy. Aquí está mi intento:
# Create a NumPy array, which has four elements. The top-left should be pure # red, the top-right should be pure blue, the bottom-left should be pure green, # and the bottom-right should be yellow. pixels = np.array([[[255, 0, 0], [0, 255, 0]], [[0, 0, 255], [255, 255, 0]]]) # Create a PIL image from the NumPy array image = Image.fromarray(pixels, 'RGB') # Print out the pixel values print image.getpixel((0, 0)) print image.getpixel((0, 1)) print image.getpixel((1, 0)) print image.getpixel((1, 1)) # Save the image image.save('image.png')Sin embargo, la impresión da lo siguiente:
(255, 0, 0) (0, 0, 0) (0, 0, 0) (0, 0, 0)Y la imagen guardada tiene rojo puro en la parte superior izquierda, pero todos los demás píxeles son negros. ¿Por qué estos otros píxeles no conservan el color que les asigné en la matriz NumPy?
El modo RGB espera valores de 8 bits, por lo que solo lanzar su matriz debería solucionar el problema:
In [25]: image = Image.fromarray(pixels.astype('uint8'), 'RGB') ...: ...: # Print out the pixel values ...: print image.getpixel((0, 0)) ...: print image.getpixel((0, 1)) ...: print image.getpixel((1, 0)) ...: print image.getpixel((1, 1)) ...: (255, 0, 0) (0, 0, 255) (0, 255, 0) (255, 255, 0)Su matriz numpy debe ser de la forma:
[[[248 248 248] # RGB [248 248 248] [249 249 249] ... [ 79 76 45] [ 79 76 45] [ 78 75 44]] [[247 247 247] [247 247 247] [248 248 248] ... [ 80 77 46] [ 79 76 45] [ 79 76 45]] ... [[148 121 92] [149 122 93] [153 126 97] ... [126 117 100] [126 117 100] [125 116 99]]] Suponiendo que tiene su matriz numpy almacenada en np_arr , aquí se explica cómo convertirla en una imagen de almohada:
from PIL import Image import numpy as np new_im = Image.fromarray(np_arr)Para mostrar la nueva imagen, utilice:
new_im.show()