逐行读取图像像素

2024-09-27 19:27:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在做一个项目,需要我的代码获取图像的像素数据并重建它(以另一种形式),但是当我尝试使用像素数据创建图像时,结果发现所有像素都在同一行上

这是我的密码

pixels = (image.getdata())

img_array = np.array(pixels, dtype=np.uint8)

img = Image.fromarray(img_array)
img.save('testrgb.png')

如何逐行读取图像的像素,并根据它们的行将它们排列在不同的列表中

编辑通过使用以下代码,我能够获得所需的结果

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')

Tags: 数据代码图像imageimgnp像素array
1条回答
网友
1楼 · 发布于 2024-09-27 19:27:22

从关于^{}的文件中:

Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.

如果您想要实际图像的NumPy数组表示,请直接使用image上的np.array

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
                    

相关问题 更多 >

    热门问题