簡體   English   中英

如何從Python3中的像素值列表創建圖像?

[英]How to create image from a list of pixel values in Python3?

如果我有以下格式的圖像像素行列表,如何獲取圖像?

[
   [(54, 54, 54), (232, 23, 93), (71, 71, 71), (168, 167, 167)],
   [(204, 82, 122), (54, 54, 54), (168, 167, 167), (232, 23, 93)],
   [(71, 71, 71), (168, 167, 167), (54, 54, 54), (204, 82, 122)],
   [(168, 167, 167), (204, 82, 122), (232, 23, 93), (54, 54, 54)]
]

PILnumpy是你的朋友:

from PIL import Image
import numpy as np


pixels = [
   [(54, 54, 54), (232, 23, 93), (71, 71, 71), (168, 167, 167)],
   [(204, 82, 122), (54, 54, 54), (168, 167, 167), (232, 23, 93)],
   [(71, 71, 71), (168, 167, 167), (54, 54, 54), (204, 82, 122)],
   [(168, 167, 167), (204, 82, 122), (232, 23, 93), (54, 54, 54)]
]

# Convert the pixels into an array using numpy
array = np.array(pixels, dtype=np.uint8)

# Use PIL to create an image from the new array of pixels
new_image = Image.fromarray(array)
new_image.save('new.png')

編輯:

使用numpy制作隨機像素圖像有點樂趣:

from PIL import Image
import numpy as np

def random_img(output, width, height):

    array = np.random.random_integers(0,255, (height,width,3))  

    array = np.array(array, dtype=np.uint8)
    img = Image.fromarray(array)
    img.save(output)


random_img('random.png', 100, 50)

我自己沒有使用PIL,但最好的方法是使用PIL打開一個實際的圖像文件。 然后探索打開所述圖像所涉及的API和對象,並查看像素值如何存儲在與API相關的特定對象中。

然后,您可以使用提取的RGB值構造有效的PIL圖像對象。

編輯:請參閱以下帖子: 如何使用RGB元組列表在PIL中創建圖像?

另外,訪問PIL中的像素值: https//pillow.readthedocs.io/en/4.3.x/reference/PixelAccess.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM