mardi 7 février 2017

Corrupted image is being saved with PIL

Vote count: 0

I am having an issue whereby manipulating image pixels is causing a corrupted image to be saved...

So, I open an image using PIL, and then convert it to a NumPy array:

image = Image.open("myimage.png")
np_image = np.asarray(image)

Then, I transpose the image, to convert it from [x][y][channel] to [channel][x][y]:

pixels = np.transpose(np_image, (2, 0, 1))

If I then set this transpose this image back to [x][y][channel], create a PIL image from this array, and then save the image:

image1 = np.transpose(pixels, (1, 2, 0))
image2 = Image.fromarray(image1, 'RGB')
image2.save('image2.png')

Then the image saved is identical to "myimage.png".

However, if instead of the above code, I first assign pixels to an element in an array of images:

images = np.array([10, 3, 50, 50]) # The images are 50x50 with 3 channels
images[0] = pixels
image3 = np.transpose(images[0], (1, 2, 0))
image4 = Image.fromarray(image3, 'RGB')
image4.save('image4.png')

Then "image4.png" is corrupted. It appears as follows:

enter image description here

Whereas "myimage.png" is actually:

enter image description here

So why is it that if I save the image when I directly transpose pixels, the image saved is as expected, but when I set pixels to the first element in the array images, and then transpose this image, the saved image is corrupted?

Thanks!

asked 23 secs ago

Let's block ads! (Why?)



Corrupted image is being saved with PIL

Aucun commentaire:

Enregistrer un commentaire