我正在嘗試將單色 PNG 檔案加載到 numpy 陣列中。對于大多數 PNG 檔案,下面的代碼作業正常。但是,如果 PNG 檔案僅包含一種顏色,則 numpy 陣列中每個像素的 RGBA 值[0, 0, 0, 255]會導致影像為黑色。在顏色“紅色”的情況下,如何訪問正確的 RGBA 值?例如[255, 0, 0, 255]
from PIL import image
import numpy as np
red_image = Image.open("red.png")
arr = np.asarray(red_image)
呼叫時red_image.getBands(),我希望("R",)根據檔案看到一個 元組。相反,我看到了("P",). 我還不知道什么是“P”頻道,但我認為這與我的問題有關。
uj5u.com熱心網友回復:
“P”表示 PIL 模式處于“調色板”。這里有更多資訊:PIL 中“P”和“L”模式下的影像有什么區別?.
從“P”轉換為“RGBA”解決了我的問題。
from PIL import image
import numpy as np
red_image = Image.open("red.png")
red_image = red_image.convert("RGBA") # added this line
arr = np.asarray(red_image)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/355044.html
