How to display a picture from an array

In order to manipulate images later by swapping pixels (“photobooth transformation”), I started by writing a script to create an array of dimension n x n , from a “photo. png” of n x n pixels. But when I want to check if the table is really the same as the picture, it doesn’t work
Here is the script:

from PIL import Image
import numpy as np
#the image is 50x50 pixels in gray mode
im “c:\user…\ photo.png)
print(“size=”,im.size,” “,‘mode=’, im.mode,” ", “format=”,im.format)

Image → numpy array

T= np.array(im)

array formatting …there are 50 rows like this one

for i in range(0,50):

Then I copy the table in a text file and save it in the format “photo.pgm” :
49 49

18 17 16 12 11 10 11 13 … .
19 20 17 14 13 13 13 12 …

The script works well, but when I open the file “photo.pgm”, the pixels are mixed up and I can’t find the initial photo
thank you for your help

I found an explanation for my problem
In fact in the 50x50 array the indexes are counted between 0 and 49
while in the photo application (GIMP or Photoshop) pixels are counted between 1 and 50
I made the mistake to define the pgm file with the specifications
P2 49 49 255
instead of
P2 50 50 256
So the problem is solved

python show image from numpy array

from PIL import Image
import numpy as np

w, h = 512, 512
data = np.zeros((h, w, 3), dtype=np.uint8)
data[0:256, 0:256] = [255, 0, 0] # red patch in upper left
img = Image.fromarray(data, 'RGB')'my.png')