如何将网络的输出图像转换为目标为PIL的P模式的彩色图片?
How to transform network's output images to colored pictures with target is PIL's P mode?
在PIL的P模式训练过程中目标图像的原始值为20和16,因此我将20转换为1,将16转换为2以训练分割任务。
但是当我想得到输出图像时,尽管我使用了代码
,但图片没有着色
pred=pred.reshape([512,512]).astype('uint8')
(x, y) = pred.shape
for xx in range(x):
for yy in range(y):
if pred[xx, yy] == 2:
pred[xx, yy] = 16
elif pred[xx, yy] == 1:
pred[xx, yy] = 20
pp = Image.fromarray(pred).convert('P')
pp.save(r'E:\python_workspace11\run\pascal\{}.png'.format(i))
但是输出图像是
我已经看到 PIL.open 的值并将其转换为 numpy 以查看值,部分内容转换为 16 和 20,模式也是 P。
我该如何处理这个问题?
您似乎已经设法将索引为 20 的所有像素更改为索引 1,将索引为 16 的所有像素更改为索引 2。但是,您随后需要将调色板条目 20 复制到调色板条目 1,将调色板条目 16 复制到调色板entry 2 为了让颜色保持不变。
那么,你想要:
import numpy as np
from PIL import Image
# Load image
im = Image.open('R0T9R.png')
# Get palette and make into Numpy array of 256 entries of 3 RGB colours
palette = np.array(im.getpalette(),dtype=np.uint8).reshape((256,3))
# Set palette entry 1 the same as entry 20, and 2 the same as 16
palette[1] = palette[20]
palette[2] = palette[16]
# Change pixels too - this replaces your slow "for" loops
npim = np.array(im)
npim[npim==16] = 2
npim[npim==20] = 1
# Make Numpy array back into image
res = Image.fromarray(npim)
# Apply our modified palette and save
res.putpalette(palette.ravel().tolist())
res.save('result.png')
在PIL的P模式训练过程中目标图像的原始值为20和16,因此我将20转换为1,将16转换为2以训练分割任务。
pred=pred.reshape([512,512]).astype('uint8')
(x, y) = pred.shape
for xx in range(x):
for yy in range(y):
if pred[xx, yy] == 2:
pred[xx, yy] = 16
elif pred[xx, yy] == 1:
pred[xx, yy] = 20
pp = Image.fromarray(pred).convert('P')
pp.save(r'E:\python_workspace11\run\pascal\{}.png'.format(i))
但是输出图像是
您似乎已经设法将索引为 20 的所有像素更改为索引 1,将索引为 16 的所有像素更改为索引 2。但是,您随后需要将调色板条目 20 复制到调色板条目 1,将调色板条目 16 复制到调色板entry 2 为了让颜色保持不变。
那么,你想要:
import numpy as np
from PIL import Image
# Load image
im = Image.open('R0T9R.png')
# Get palette and make into Numpy array of 256 entries of 3 RGB colours
palette = np.array(im.getpalette(),dtype=np.uint8).reshape((256,3))
# Set palette entry 1 the same as entry 20, and 2 the same as 16
palette[1] = palette[20]
palette[2] = palette[16]
# Change pixels too - this replaces your slow "for" loops
npim = np.array(im)
npim[npim==16] = 2
npim[npim==20] = 1
# Make Numpy array back into image
res = Image.fromarray(npim)
# Apply our modified palette and save
res.putpalette(palette.ravel().tolist())
res.save('result.png')