0

I am trying to paste an image onto another one. I am actually using the second answer by Joseph here because I am trying to do something very similar: resize my foregroud to the background image, and then copy only the black pixels in the foreground onto the background. My foreground is a color image with black contours, and I want only the contours to be pasted on the background. The line

mask = pixel_filter(mask, (0, 0, 0), (0, 0, 0, 255), (0, 0, 0, 0))

returns the error "image index out of range".

When I don't do this filtering process to see if pasting at least works, I get a "bad mask transparency error". I have set the background and foreground to RGB and RGBA both to see if any combination solves the problem, it doesn't.

What am I doing wrong in the mask() line, and what am I missing about the paste process? Thanks for any help.

Community
  • 1
  • 1
AstroLorraine
  • 27
  • 1
  • 4

1 Answers1

0

The pixel filter function you are referencing has a slight bug it seems. It's trying to convert a 1 dimensional list index into a 2d index backwards. It should be (x,y) => (index/height, index%height) (see here). Below is the function (full attribution to the original author) rewritten.

def pixel_filter(image, condition, true_colour, false_colour):
    filtered = Image.new("RGBA", image.size)
    pixels = list(image.getdata())
    for index, colour in enumerate(pixels):
        if colour == condition:
            filtered.putpixel((index/image.size[1],index%image.size[1]), true_colour)
        else:
            filtered.putpixel((index/image.size[1],index%image.size[1]), false_colour)
    return filtered
Community
  • 1
  • 1
Gil
  • 370
  • 2
  • 11