0

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.

gram_schmidt
  • 117
  • 8
  • Could you upload the image so we can reproduce the problem? – Anwarvic Sep 28 '21 at 17:52
  • 1
    Surely you would do better to swap two entries in your palette, i.e. 3 bytes of RGB palette with 3 other bytes of palette than moving megabytes of pixels around? See https://stackoverflow.com/a/57202093/2836621 – Mark Setchell Sep 28 '21 at 18:38
  • @MarkSetchell - this is a great solution, something I haven't thought of (I'm new to image processing in general), so I'm going to try it out - thanks! – gram_schmidt Sep 28 '21 at 19:44

0 Answers0