0

I didn't want to ask a question if I can find myself and I thought I was doing something wrong but I'm not...for an RGB/full color image. So code like this will work:

from PIL import Image
import numpy as np

im = Image.open('myimg.png')
indexed = np.array(im)
pixels = im.load()
for i in range(im.size[0]):
    for j in range(im.size[1]):
            if pixels[i,j] == (93, 53, 8):
                pixels[i,j] = (255, 0, 255)
im.save(im.filename)

But not if the image is indexed.. why it doesnt work for indexed if both colors are present in the color map? And how to make it work? I need to replace the mentioned color in the image with Magenta, in the image, not the palette, I have both colors in the palette.

programc7r
  • 63
  • 6
  • Your code works fine!! I think the problem happens because you're using the same filename over and over `im.filename` I suggest try again after changing the new image name – Anwarvic May 25 '20 at 18:02
  • 2
    If you have an indexed image, you only have 1 byte per pixel (rather than 3 bytes of RGB). So if you have an indexed image, you'll never find a pixel equal to (93, 53, 8) will you? – Mark Setchell May 25 '20 at 18:13
  • 1
    For an indexed image, all you need to do is replace the color in the image's color palette — no need to search through all the pixels of the the image looking for it… – martineau May 25 '20 at 18:42
  • I hope my earlier comment didn't come across as unhelpful. I was just trying to explain. If you want your code to work on an indexed image, just convert the indexed image to RGB when you open it. `im = Image.open('myimg.png').convert('RGB')` Explanation here https://stackoverflow.com/a/52307690/2836621 – Mark Setchell May 25 '20 at 19:05

0 Answers0