[英]PIL image to numpy
我有一個 NumPy 圖像(二維),其中每個像素范圍以千為單位。 我想將其轉換為 RGB 圖像(3 維),范圍從 0 到 255。所以我做了以下操作:
from PIL import Image
import numpy as np
image = Image.fromarray(input_image,'RGB')
new_image = np.asarray(image)
但是,當我使用matplotlib
顯示input_image
(2-dim) 和new_image
(3-dim) 時,它們看起來完全不同:
from matplotlib import pyplot as plt
plt.figure()
plt.imshow(input_image)
plt.figure()
plt.imshow(new_image)
所謂的“原始圖像”具有“viridis”顏色圖的錯誤 colors。
Viridis 顏色圖是 matplotlib 的默認顏色matplotlib
。
使用image = Image.fromarray(input_image,'RGB')
不會將圖像轉換為假 colors - 它將值重新解釋為 RGB,結果看起來像隨機噪聲。
為了獲得與matplotlib
"viridis" 顏色圖相同的 colors 作為 RGB 值,我們可以使用以下階段:
matplotlib
),並將其轉換為查找表。input_image
)傳遞給0
,將最大值( input_image
)傳遞給255
,其他值進行線性變換。img
通過 Viridis 顏色圖查找表。我們可能會 select 其他類型的顏色圖(Viridis 只是一個例子)。
代碼示例:
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image
# Build arbitrary image for testing
################################################################################
cols, rows = 320, 256
x, y = np.meshgrid(np.arange(cols), np.arange(rows))
input_image = (x*y % 10000).astype(np.uint16)
#image = Image.fromarray(input_image)
#plt.figure()
#plt.imshow(image)
#plt.show(block=True)
################################################################################
# Get viridis colormap, and convert it to look up table:
cmap = plt.get_cmap('viridis')
cmaplist = [cmap(i) for i in range(cmap.N)] # https://stackoverflow.com/q/43384448/4926757
lut = np.array(cmaplist) # The look up table is given in RGBA color space (256 entries).
lut = np.round(lut[:, 0:3]*255).astype(np.uint8) # Convert from RGBA to RGB (get only first 3 elements) and convert to uint8
# Convert input image to uint8 (range [0, 255]) using linear transformation:
minval = input_image.min()
maxval = input_image.max()
img = ((input_image.astype(float) - minval)*(255.0/(maxval-minval)))
img = np.round(img).astype(np.uint8)
# Pads img through viridis colormap look up table
colored_img = lut[img]
plt.figure()
plt.imshow(colored_img)
plt.show(block=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.