【问题标题】:Read Image pixels, row by row逐行读取图像像素
【发布时间】:2020-02-19 05:31:15
【问题描述】:

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

这是我的代码

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

【问题讨论】:

  • 您可以将 img_array 除以图像 wigth
  • 它引发了一个错误,提示我无法编写这样的 png 图像
  • 请参阅下面的答案以获得图像本身的 NumPy 数组表示,而不是扁平像素。您能否提供有关所需列表的更多详细信息?我会在上面添加更多代码。
  • 获取图像的尺寸并遍历它怎么样?

标签: python image numpy python-imaging-library


【解决方案1】:

来自getdata上的文档:

将此图像的内容作为包含像素值的序列对象返回。序列对象被展平,因此第 1 行的值紧跟在第 0 行的值之后,依此类推。

如果您想要实际图像的 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
----------------------------------------

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    相关资源
    最近更新 更多