A
A
AlexaAioGram2021-10-02 15:34:53
Python
AlexaAioGram, 2021-10-02 15:34:53

How to overlay a photo on a greenscreen in Python?

Let's say I send a photo to a program with a green area, and then the program prompts me to send another photo to take the place of the green area. Is it possible to do so? I heard that this can be done through pil, but I did not find any information on this, help who knows

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
o5a, 2021-10-03
@AlexaAioGram

It is possible so for example. Given the specified color of green, we replace it throughout the greenscreen with a transparent one, then we mix in the second image, taking into account this mask.
Perhaps there are more efficient ways, but this also works.

from PIL import Image

# заменяет указанный цвет на прозрачный
def make_transparent(image, color):
    new = []
    for item in image.getdata():
        if item[:3] == color:
            new.append((255, 255, 255, 0))
        else:
            new.append(item)
    image.putdata(new)

GREEN = (x, y, z) # указываем цвет нашего зеленого на "гринскрине"
img_filename = "images/image.png"
screen_filename = "images/green.png"

img = Image.open(img_filename).convert('RGBA')
screen = Image.open(screen_filename).convert('RGBA')

make_transparent(screen, GREEN)

new = Image.alpha_composite(img, screen)
new.save('new_image.png')

Another option is to iterate over both images in the same way and use the pixels of the first / second depending on the color of the greenscreen pixel.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question