2015-06-19 38 views
5

我可以從現有的圖像文件使用如下的程序生成的像素值的列表:如何從Python中的像素值列表中創建PNG圖像文件?

from PIL import Image 
image = Image.open("test.png") 
pixels = list(image.getdata()) 
width, height = image.size 
pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)] 

我怎麼能轉換的像素值回圖像文件的這個名單?

回答

7

快速修復

首先,你需要讓你的像素元組在一個單一的非嵌套列表:

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

你行你開羅。挺容易。

#!/usr/bin/python 

# Extracting pixels from an image ------ 
from PIL import Image 
image = Image.open("test.png") 
pixels = list(image.getdata()) 
width, height = image.size 
pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)] 


# Putting pixels back to an image ------ 

import cairo 

Width=len(pixels[0]) 
Height=len(pixels) 

surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, Width, Height) 
context = cairo.Context (surface) 

y=0 
for row in pixels: 
    x=0 
    for rgb in row: 
     r=rgb[0] /255.0 
     g=rgb[1] /255.0 
     b=rgb[2] /255.0 
     context.set_source_rgb(r, g, b) 
     context.rectangle(x, y, 1, 1) 
     context.fill() 
     x+=1 
    y+=1 

surface.write_to_png ("out.png") # Output to PNG 
+1

這是一個整潔的想法,但如果您已經在使用PIL,則會矯枉過正。 – rjonnal

+1

OP沒有指定他正在使用的內容。他問:「我如何從Python中的像素值列表創建PNG圖像文件?」我給了一個答案。也許,他想以後重用這些數據?不允許或者什麼? –

+1

開羅當然*允許*。我不確定它與數據重用有什麼關係。 OP確實說明他/她正在使用PIL。 – rjonnal