How to transform network's output images to colored pictures with target is PIL's P mode?
The original value in target images is 20 and 16 at training process with P mode of PIL,so I transform 20 to 1 and 16 to 2 in order to train the segmentation task.
But when I want to get the output images,the pictures aren't colored although I used the code

        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_workspace\0711\run\pascal\{}.png'.format(i))


But the output image is 

I have see the value with PIL.open and transform it to numpy to see the values,the part of things is convert to 16 and 20,the mode is P too.
How can I deal with this problem?

You appear to have managed to change all pixels with index 20 into index 1 and all pixels with index 16 into 2. However, you then need to copy the palette entry 20 to palette entry 1 and palette entry 16 to palette entry 2 in order to make the colours remain the same.

So, you want:

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')

