Dev Catalin
Dev Catalin

Reputation: 1325

How can I cut custom shape from an Image with PIL?

I want to cut a picture, let's say:

enter image description here

Using another picture that has transparent background, like this one:

enter image description here

And get the following result:

enter image description here

How can I achieve this using Python PIL/Pillow? Or any other library, but it has to be in Python.

Upvotes: 5

Views: 1815

Answers (1)

Rutrus
Rutrus

Reputation: 1447

Let's call source.png to the first image, and mask.png to the logo™

Your logo is transparent but in an inverted way, so the transparency is not useful for us. Also, for this case when we delete transparency, the transparent zone becomes almost-white, so we need to threshold it.

from PIL import Image, ImageOps

# Convert to grayscale
mask = Image.open('mask.png').convert('L')

# Threshold and invert the colors (white will be transparent)
mask = mask.point(lambda x: x < 100 and 255)

# The size of the images must match before apply the mask
img = ImageOps.fit(Image.open('source.png'),mask.size)

img.putalpha(mask) # Modifies the original image without return

img.save('result.png')

The picture once cutted

Upvotes: 8

Related Questions