10

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
  • 55,762
  • 10
  • 62
  • 120
Shak
  • 418
  • 1
  • 4
  • 14

1 Answers1

20

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
  • 191,897
  • 31
  • 273
  • 432
  • 1
    Give me an error `Cannot handle this data type: (1, 1, 5), |u1` in the line `Image.fromarray(npImage).save('result.png')` and the line`draw.pieslice([0,0,h,w],0,360,fill=255)` I had to update by `draw.pieslice(((0, 0), (h, w)), 0, 360, fill=255)` – alambertt Aug 10 '22 at 00:41