[英]Convert 1D Numpy Array into a 1D image using PIL
將一維 numpy 數組轉換為 PIL 圖像 object 時,PIL 返回IndexError: tuple index out of range
。
我正在嘗試使用 PIL 將長度為 2048 且值介於 0 和 255 之間的一維 Numpy 數組轉換為圖像。 我認為這是我的陣列是一維的問題。 我還嘗試將隨機一維數組 integer 轉換為圖像,我得到了同樣的錯誤。
隨機 integer 示例:
from PIL import Image
import numpy as np
arr = np.random.randint(255, size=(2048))
arr = arr.astype('uint8')
img = Image.fromarray(arr, 'L')
img.show()
我希望代碼能夠顯示具有不同灰度的單行像素的圖像。
輸入數組必須是二維的,即使一維是1
。 您只需要決定是否希望圖像是水平或垂直的像素行,並在創建數組時添加一個維度。
arr = np.random.randint(255, size=(2048, 1)) # vertical image
arr = np.random.randint(255, size=(2048, 1)) # horizontal image
當我嘗試運行您的代碼時,問題只是您的數組是一維數組。 所以試試:
arr2d = arr.reshape(-1,1)
Image.fromarray(arr2d,'L').show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.