简体   繁体   English

如何使用 PIL 将 go 从数组到列表再返回?

[英]How to go from array to list and back again using PIL?

I am trying to put my image in list form in order to insert pixels to the image.我试图将我的图像以列表形式放置,以便将像素插入到图像中。 However, I'm running into issues on converting back to an image once I've done the list manipulation.但是,完成列表操作后,我在转换回图像时遇到了问题。 Turns out just going from image -> array -> list -> array -> image messes up the image pretty good.原来只是从图像 -> 数组 -> 列表 -> 数组 -> 图像把图像搞得一团糟。

However, going from image -> array -> image seems to work just fine.但是,从 image -> array -> image 开始似乎工作得很好。 It's that extra step of going to a list that's causing issues.这是进入导致问题的列表的额外步骤。

Below is the python3 code I'm running.下面是我正在运行的 python3 代码。 Can anyone tell me what I'm doing wrong and how to get the 3D list converted back into an RGB image that is identical to the original?谁能告诉我我做错了什么以及如何将 3D 列表转换回与原始图像相同的 RGB 图像? Both the original and final arrays appear to be the same so not sure what PIL doesn't like...原始的和最终的 arrays 看起来是一样的所以不确定 PIL 不喜欢什么......

import numpy as np
from PIL import Image              

img = Image.open('1.jpg') 
array = np.array(img)              

list1 = array.tolist()             
arrayF = np.array(list1)                                                

img2 = Image.fromarray(arrayF,"RGB")
img2.save('trial.jpg')

print(array)
print(arrayF)

If you inspect the dtype of your arrays, with print(array.dtype) , you will see that array is 8-bit and arrayF is 64-bit... which is unacceptable to PIL for an RGB image.如果您使用print(array.dtype)检查dtype的 dtype,您将看到array是 8 位而arrayF是 64 位...对于 RGB 图像,PIL 是不可接受的。

Make arrayF back into 8-bit with:使用以下命令使arrayF回 8 位:

arrayF = arrayF.astype(np.uint8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM