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:
into this:
I want to be able to save it as a PNG (with a transparent background).
How can this be done?
If you want to change the outline of a picture and make it a shape (like a circle or a star), use the cropping tools on the PICTURE TOOLS FORMAT tab. Select the picture (or pictures) that you want to crop. On the PICTURE TOOLS FORMAT tab, click Crop > Crop to Shape, and then pick the shape you want.
The crop() function of the image class in Pillow requires the portion to be cropped as rectangle. The rectangle portion to be cropped from an image is specified as a four-element tuple and returns the rectangle portion of the image that has been cropped as an image Object.
There is no specific function for cropping using OpenCV, NumPy array slicing is what does the job. Every image that is read in, gets stored in a 2D array (for each color channel). Simply specify the height and width (in pixels) of the area to be cropped. And it's done!
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With