How to crop an image with rounded circle shape in Python

Hello programmers, in this tutorial we will see how to crop an image in a rounded circle shape in Python.

People often like to have a rounded image of various images they can utilize as their profile pictures. In this scenario, there can be various possibilities of cropping the image with a round circle shape using multiple software. In this tutorial, we will see this task done using Python.

Installation

Before running the program, the following two libraries have to be installed through the command prompt of the system.

pip install numpy
pip install pillow

Crop an image in circle shape using pillow in Python

For cropping the image to a rounded shape, we utilize the pillow library and the NumPy library in Python.

Our approach in this solution will be to convert the input image into a NumPy array with the RGB color contents. We create a new layer with the dimension of the input image and draw a circular shape on it. We then convert the layer with the circular shape to a NumPy array with the RGB color contents. We then add the newly created NumPy array over the input image array and crop it according to the shape hence we export the image to get our final output.

Given below is the code for the following approach:

#Import libraries
import numpy as np
from PIL import Image, ImageDraw

#create the rounded image
def imgRoundFunc(imgName):
    img = Image.open(f"{imgName}.jpg").convert("RGB") #convert to RGB
    arrImg = np.array(img) #convert to numpy array

    alph = Image.new('L', img.size, 0) #create a new image with alpha channel
    draw = ImageDraw.Draw(alph) #create a draw object
    draw.pieslice([0, 0, img.size[0], img.size[1]], 0, 360, fill = 255) #create a circle

    arAlpha = np.array(alph) #conver to numpy array

    arrImg = np.dstack((arrImg, arAlpha)) #add alpha channel to the image

    Image.fromarray(arrImg).save('roundImgOutput.png') #save the resultant image

#driver
if __name__ == "__main__":
    imgName = "<imageFileName>"
    imgRoundFunc(imgName)

Output

The newly created image file ‘roundImgOutput.png’ is created with the desired result.

Explanation
Inside the ‘imgRoundFunc()’ function, we pass the input image file name. We then create the image in RGB format and create a NumPy array from it. We then create a new layer known as the alpha layer over here with the input image dimensions. We draw a circular shape over it and then convert the new layer to a NumPy array. We then add the new layer array over the input image array and get the circular-shaped image and get the resultant output. We then save the resultant image by the name ‘roundImgOutput’.

Leave a Reply

Your email address will not be published.