7

I want to create a script that crops an image in a circular way.

I have a server which receives all kind of pictures (all of the same size) and I want the server to crop the received image.

For example, turn this image:

Before

into this:

After

I want to be able to save it as a PNG (with a transparent background).

How can this be done?

Cris Luengo
  • 49,445
  • 7
  • 57
  • 113
Shak
  • 358
  • 1
  • 3
  • 13

1 Answers1

16

Here's one way to do it:

#!/usr/local/bin/python3
import numpy as np
from PIL import Image, ImageDraw

# Open the input image as numpy array, convert to RGB
img=Image.open("dog.jpg").convert("RGB")
npImage=np.array(img)
h,w=img.size

# Create same size alpha layer with circle
alpha = Image.new('L', img.size,0)
draw = ImageDraw.Draw(alpha)
draw.pieslice([0,0,h,w],0,360,fill=255)

# Convert alpha Image to numpy array
npAlpha=np.array(alpha)

# Add alpha layer to RGB
npImage=np.dstack((npImage,npAlpha))

# Save with alpha
Image.fromarray(npImage).save('result.png')

enter image description here

Mark Setchell
  • 169,892
  • 24
  • 238
  • 370