pythonarrayspython-imaging-librarysave-image

How to reconstruct an image object from a list?


I have been attempting to break an image (.png) into a list, edit the list, and then save the edited image as a file.

After editing the image, and restoring it into an array, mpl.imshow(image) correctly displays the new image, however attempting to save it as a file results in a blank image.

I believe that the flaw lies in the line marked # <-- Estimated point of failure, but I have researched the command and can find no solution to the problem. I have examined the reconstructed array using print(), and nothing seems unusual.

Any ideas on how I could correctly save my edited image in file form would be greatly appreciated.

Thank you for your help, Lochlann F.

import numpy as np
import matplotlib.pyplot as mpl
from PIL import Image

# Desconstruct the image into an editable list
img = Image.open('mini.png')
my_dot_array = np.asarray(img)
my_dot_list = my_dot_array.tolist()
my_dot_list[0][0] = [30, 220, 90, 255] # <-- Attemp a small edit to a pixel in the image

# Reconstuct the image into a saved .png file
my_dot_array = np.asarray(my_dot_list)
img = Image.fromarray(my_dot_array, mode='RGBA') # <-- Estimated point of failure
img = img.save('updated_mini.png')

# Display the resulting image
mpl.imshow(my_dot_array)
mpl.show()


#print(my_dot_array)

Solution

  • I think you are one line out. The line above needs a second parameter dtype=np.uint8:

    my_dot_array = np.asarray(my_dot_list, dtype=np.uint8)