簡體   English   中英

將numpy數組轉換為RGB圖像

[英]Convert numpy array to rgb image

我有一個數值范圍為0-255numpy數組。 我想將其轉換為3通道RGB圖像。 我使用PIL Image.convert()函數,但是它將其轉換為灰度圖像。

我正在使用Python PIL庫通過以下代碼將numpy數組轉換為圖像:

imge_out = Image.fromarray(img_as_np.astype('uint8'))
img_as_img = imge_out.convert("RGB")

輸出將圖像轉換為3個通道,但顯示為黑白(灰度)圖像。 如果我使用以下代碼

img_as_img = imge_out.convert("R")

表明

error conversion from L to R not supported

如何將numpy數組正確轉換為RGB圖片?

您需要一個適當大小的numpy數組,即具有整數的HxWx3數組。 我用以下代碼和輸入對其進行了測試,似乎可以正常工作。

import os.path
import numpy as np
from PIL import Image


def pil2numpy(img: Image = None) -> np.ndarray:
    """
    Convert an HxW pixels RGB Image into an HxWx3 numpy ndarray
    """

    if img is None:
        img = Image.open('amsterdam_190x150.jpg'))

    np_array = np.asarray(img)
    return np_array


def numpy2pil(np_array: np.ndarray) -> Image:
    """
    Convert an HxWx3 numpy array into an RGB Image
    """

    assert_msg = 'Input shall be a HxWx3 ndarray'
    assert isinstance(np_array, np.ndarray), assert_msg
    assert len(np_array.shape) == 3, assert_msg
    assert np_array.shape[2] == 3, assert_msg

    img = Image.fromarray(np_array, 'RGB')
    return img


if __name__ == '__main__':
    data = pil2numpy()
    img = numpy2pil(data)
    img.show()

amsterdam_190x150.jpg

我在用:

  • Python 3.6.3
  • numpy的1.14.2
  • 枕頭4.3.0

暫無
暫無

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

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