使用PIL保存损坏的图像 [英] Corrupted image is being saved with PIL

查看:474
本文介绍了使用PIL保存损坏的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个问题,即操纵图像像素会导致图像被损坏...

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

所以,我用PIL打开图像,然后转换它到一个NumPy数组:

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)

然后,我转置图片,从转换它[x] [y] [频道] [频道] [x] [y]

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

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

如果我然后将此图像转换回 [x] [y] [channel] ,请从此数组创建PIL图像,然后保存图片:

If I then 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')

然后保存的图像与myimage.png相同。

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

但是,如果不是上面的代码,我首先指定像素到el在一系列图像中:

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

images = np.zeros([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')

然后image4 .png已损坏。它显示如下:

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

而myimage .png实际上是:

Whereas "myimage.png" is actually:

< img src =https://i.stack.imgur.com/NsK4T.pngalt =在此处输入图像说明>

那么为什么如果我直接转置像素时保存图像,保存的图像是预期的,但是当我设置像素到数组 images 中的第一个元素,然后转置此图像,保存的图像已损坏?

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?

谢谢!

推荐答案

numpy.zeros 创建的默认数据类型是浮点数,所以

The default data type created by numpy.zeros is floating point, so

images = np.zeros([10, 3, 50, 50])

创建一个浮点数组。然后在作业中

creates a floating point array. Then in the assignment

images[0] = pixels

像素中的值被转换为浮点数,以便将它们存储在 images ,所以 image3 是一个浮点数组。这会影响保存相应图像时存储在PNG文件中的值。我不知道PIL / Pillow在给定浮点数组时遵循的规则,但显然这不是期望的行为。

the values in pixels are cast to floating point in order to store them in images, so image3 is a floating point array. This affects the values that are stored in the PNG file when the corresponding image is saved. I don't know the rules that PIL/Pillow follow when given a floating point array, but apparently it is not the desired behavior here.

要解决此问题,请创建 images 使用与 np_image 相同的数据类型(很可能是 numpy.uint8 ):

To fix this, create images using the same data type as np_image (most likely this is numpy.uint8):

images = np.zeros([10, 3, 50, 50], dtype=np_image.dtype)

这篇关于使用PIL保存损坏的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆