Home > Net >  Remove green screen from a image and make it transparent
Remove green screen from a image and make it transparent

Time:10-17

I found a solution to this but the background is not transparent, it's black and I don't know how I should make it transparent.

Here's my code:

from PIL import Image

image = Image.open('pic.jpg')
image.show()
image_data = image.load()
height,width = image.size
for loop1 in range(height):
    for loop2 in range(width):
        r,g,b = image_data[loop1,loop2]
        image_data[loop1,loop2] = r,0,b
image.save('changed.png')

CodePudding user response:

If your background consists of one color, then you can replace it with transparent in the following way:

from PIL import Image

img = Image.open('pic.png')
rgba = img.convert('RGBA')
data = rgba.getdata()
green_rgb = (0, 128, 0)  # change it to your exact bg color

new_data = [item if item[:-1] != green_rgb else (255, 255, 255, 0) for item in data]

rgba.putdata(new_data)
rgba.save('changed.png', 'PNG')

However, if your background is of different shades, then you will have to write additional checks and determine the boundaries of acceptable shades of green.

  • Related