我一直在开发一个项目,该项目需要我的代码获取图像的像素数据并重建它(以另一种形式),但是当我尝试使用像素数据创建图像时,结果发现所有像素都在同一行。
这是我的代码
pixels = (image.getdata())
img_array = np.array(pixels, dtype=np.uint8)
img = Image.fromarray(img_array)
img.save('testrgb.png')
如何逐行读取图像的像素并根据行将它们排列在不同的列表中?
EDIT我能够通过使用以下代码达到预期的结果
pixels = list(image.getdata())
print(pixels[0][0])
pixels2 = []
for i in range(0, height):
pixels2.append(pixels[i * width:(i + 1) * width])
#for pixel_value in pixels:
#print(pixel_value)
img_array = array = np.array(pixels2, dtype=np.uint8)
img = Image.fromarray(array)
img.save('maps/testrgb.png')
从文档上getdata:
将此图像的内容作为包含像素值的序列对象返回。序列对象被展平,因此第一行的值直接跟在零行的值之后,依此类推。
如果您想要实际图像的 NumPy 数组表示,请使用np.array
on image
直接地:
import numpy as np
from PIL import Image
# Open image with Pillow
image = Image.open('path/to/your/image.png')
# Convert Pillow image to NumPy array
img_array = np.array(image, dtype=np.uint8)
# ... do some operation on NumPy array (copy rows to lists, etc.) ...
# Convert NumPy array back to Pillow image
img = Image.fromarray(img_array)
# Save image with Pillow
img.save('testrgb.png')
希望有帮助!
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.8.1
NumPy: 1.18.1
Pillow: 7.0.0
----------------------------------------
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)