Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cropping an image in a circular way, using python [duplicate]

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?

like image 424
Shak Avatar asked Jul 23 '18 19:07

Shak


People also ask

Can you crop a picture in the shape of a circle?

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.

How do I crop an image using a pillow in Python?

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.

How do you crop an image in Python cv2?

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!


1 Answers

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

like image 126
Mark Setchell Avatar answered Sep 20 '22 00:09

Mark Setchell