Search code examples
pythonimagereplacecolorspython-imaging-library

PIL Best Way To Replace Color?


I am trying to remove a certain color from my image however it's not working as well as I'd hoped. I tried to do the same thing as seen here Using PIL to make all white pixels transparent? however the image quality is a bit lossy so it leaves a little ghost of odd colored pixels around where what was removed. I tried doing something like change pixel if all three values are below 100 but because the image was poor quality the surrounding pixels weren't even black.

Does anyone know of a better way with PIL in Python to replace a color and anything surrounding it? This is probably the only sure fire way I can think of to remove the objects completely however I can't think of a way to do this.

The picture has a white background and text that is black. Let's just say I want to remove the text entirely from the image without leaving any artifacts behind.

Would really appreciate someone's help! Thanks


Solution

  • You'll need to represent the image as a 2-dimensional array. This means either making a list of lists of pixels, or viewing the 1-dimensional array as a 2d one with some clever math. Then, for each pixel that is targeted, you'll need to find all surrounding pixels. You could do this with a python generator thus:

    def targets(x,y):
        yield (x,y) # Center
        yield (x+1,y) # Left
        yield (x-1,y) # Right
        yield (x,y+1) # Above
        yield (x,y-1) # Below
        yield (x+1,y+1) # Above and to the right
        yield (x+1,y-1) # Below and to the right
        yield (x-1,y+1) # Above and to the left
        yield (x-1,y-1) # Below and to the left
    

    So, you would use it like this:

    for x in range(width):
        for y in range(height):
            px = pixels[x][y]
            if px[0] == 255 and px[1] == 255 and px[2] == 255:
                for i,j in targets(x,y):
                    newpixels[i][j] = replacementColor