快速修復
首先,你需要讓你的像素元組在一個單一的非嵌套列表:
pixels_out = []
for row in pixels:
for tup in row:
pixels_out.append(tup)
接着,建立新的圖像對象,使用輸入圖像的特性,以及把數據放入其中:
image_out = Image.new(image.mode,image.size)
image_out.putdata(pixels_out)
最後,保存:
image_out.save('test_out.png')
根本問題
你的列表解析生成一個列表的列表,通過切片(i*width:(i+1)*width
)產生的後者。你的理解可以更容易:pixels = [pixel for pixel in pixels]
。顯然,這會輸出相同的列表pixels
,但您可以使用該想法對像素執行操作,例如pixels = [operation(pixel) for pixel in pixels]
。
真的,你推翻了它。您不必管理圖像尺寸。獲取列表中的像素,然後將它們放入與putdata
相同大小的圖像中,可以保持這種順序,因爲它們通過PIL以相同方式線性化。
總之,這是你原來的片段應該是:
from PIL import Image
image = Image.open("test.png")
image_out = Image.new(image.mode,image.size)
pixels = list(image.getdata())
image_out.putdata(pixels)
image_out.save('test_out.png')
這是一個整潔的想法,但如果您已經在使用PIL,則會矯枉過正。 – rjonnal
OP沒有指定他正在使用的內容。他問:「我如何從Python中的像素值列表創建PNG圖像文件?」我給了一個答案。也許,他想以後重用這些數據?不允許或者什麼? –
開羅當然*允許*。我不確定它與數據重用有什麼關係。 OP確實說明他/她正在使用PIL。 – rjonnal