简体   繁体   English

将原始的RGB数组转换为png图像。

[英]Convert a raw RGB array into a png image.

I am trying to read a image file using PIL and then obtaining the raw pixel values in form of numpy array and then i am trying to put together the values to form a copy of original image. 我试图使用PIL读取图像文件,然后以numpy数组的形式获取原始像素值,然后试图将这些值放在一起以形成原始图像的副本。 The code does not produce any runtime error but the image formed ("my.png") is unreadable. 该代码不会产生任何运行时错误,但是形成的图像(“ my.png”)不可读。

from PIL import Image

import numpy as np

img_filename = "image.png"
img = Image.open(img_filename)
img = img.convert("RGB")
img.show()
aa  = np.array(img.getdata())
alpha = Image.fromarray(aa,"RGB")
alpha.save('my.png')
alpha.show()


np.array(img.getdata()) gives a 2D array of shape (X, 3) , where X depends on the dimensions of the original image. np.array(img.getdata())给出形状为(X, 3)的2D数组,其中X取决于原始图像的尺寸。

Just change the relevant line of code to: 只需将相关代码行更改为:

aa  = np.array(img)

This will assign a 3D array to aa , and thus solve your problem. 这会将3D数组分配给aa ,从而解决您的问题。

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

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