I have a .tif format image in palettised mode, with a maximum of four different colored pixels (background, sea ice, ocean, and pond). I simply want to replace one of the colors (for example, replace all pixels of pond with sea ice instead), and then save the image in another directory. In its simplest form, my code looks like this:
import os
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# im is the image, open it in P mode
im = Image.open(filepath1).convert('P')
# get the palette
p = im.getpalette()
# the image should be in P format (palettised)
# we will convert the image to a numpy array,
# change what we need to, and then convert back to an image
# convert the image to an array
img_array = np.array(im)
# convert all instances of value1 to value2
img_array[img_array == pond_value] = ice_value
# show the final array
plt.matshow(img_array)
# convert back to an image
im2save = Image.fromarray(img_array, mode='P')
im2save.setpalette(p)
im2save.save(filepath2)
I tried to follow the instructions of this post which had me save the palette when opening the original image, and then re-use said palette while saving the image, but unfortunately it results in AttributeError: setpalette
for the im2save.setpalette(p)
line.
Other examples online seem to be fine so I'm not sure what I'm doing wrong. I also note that when I show the array, the array is the correct image, it just seems to be the process of saving the image that gives this error.
Thanks in advance, and let me know if I need to clarify anything.