Search code examples
pythonimagepython-imaging-librarycs50paste

Why Image Pasting not working in Python using Image Module


from PIL import Image, ImageOps

import sys

list = ['jpg', 'jpeg', 'png']

before = sys.argv[1]
after = sys.argv[2]

if len(sys.argv) == 3:
    if before[-3:] in list and after[-3:] in list and after[-3:] == before[-3:]:
        try:
            i_file = Image.open(before)
            shirt = Image.open('shirt.png')
            #o_file = Image.open(after)

        except FileNotFoundError:
            print(f"Input does not exist")
            sys.exit(1)

        size = (600, 600)
        #Resizing the before image here
        ImageOps.fit(i_file, size).save(before)


        i_file = Image.open(before)
        #Trying to paste the shirt over i_file(before2.jpg image)
        Image.Image.paste(i_file, shirt, (0, 0))

        i_file.save(after)


    else:
        print('Input and output have different extensions')
        sys.exit(1)




$ python shirt.py before2.jpg after2.jpg 

shirt image with background removed before2.jpg

In the above code I want to paste my shirt.png (a constant image) over the before.jpg (taken form teh commandline) and then save it to after.jpg( also taken form the commandline)

The problem I am facing is this, my after.jpg is coming out like this after.jpg

I have tried things but i think the problem is with my execution of paste method somehow .

PLZ help me out


Solution

  • Use a mask when pasting to respect transparency:

    from PIL import Image
    shirt  = Image.open('shirt.png')
    muppet = Image.open('muppet.png')
    
    muppet.paste(shirt, (0,0), mask=shirt)
    muppet.save('result.png')
    

    enter image description here