cropping an image in a circular way ang paste on another image, using python

image 1 i want to crop this image in circular way, like next image[image 2]

image 2 this is the cropped image

image 3 this is a fresh new image, I want to paste cropped image on this image

image 4 output will be looked like this

how can I do it in python? please help me, I’m stuck at my project!

Answer

from PIL import Image, ImageDraw, ImageFilter


im1 = Image.open('rocket.jpg')
im2 = Image.open('lena.jpg')

#height, width, channels = im1.shape
width, height = im1.size
print(height, width)


# ![rocket_pillow_paste_out](data/dst/rocket_pillow_paste_out.jpg)

mask_im = Image.new("L", im2.size, 0)
draw = ImageDraw.Draw(mask_im)
draw.ellipse((140, 50, 260, 170), fill=255)
mask_im.save('mask_circle.jpg', quality=95)

back_im = im1.copy()
back_im.paste(im2, (0, 0), mask_im)
back_im.save('rocket_pillow_paste_mask_circle.jpg', quality=95)

# ![rocket_pillow_paste_mask_circle](data/dst/rocket_pillow_paste_mask_circle.jpg)

mask_im_blur = mask_im.filter(ImageFilter.GaussianBlur(10))
mask_im_blur.save('mask_circle_blur.jpg', quality=95)

back_im = im1.copy()
back_im.paste(im2, (0, 0), mask_im_blur)
back_im.save('rocket_pillow_paste_mask_circle_blur.jpg', quality=95)

# ![rocket_pillow_paste_mask_circle_blur](data/dst/rocket_pillow_paste_mask_circle_blur.jpg)