How to Remove Background from Images in Python

02 May 2023 Balmiki Mandal 0 Python

How to Remove Background of Images in Python?

Using Python, you can remove the background of an image with the help of some awesome libraries like OpenCV and Pillow. Python offers powerful image processing capabilities that allow you to manipulate images and enhance them in various ways. In this tutorial, we will show you how to remove the background of an image using Python.

Using OpenCV

The OpenCV library is a great tool for performing image processing operations. It has many useful functions, such as adding filters and adjusting colors. We can use the OpenCV library to remove the background of an image. Here’s the code:


import cv2

# Read the input image
image = cv2.imread('input.jpg')

# Create a mask with the same dimensions as the image
mask = np.zeros(image.shape[:2], dtype=np.uint8)

# Set the background pixels to white (255)
mask[:] = 255

# Create a background substraction object 
background_substraction = cv2.createBackgroundSubtractorMOG2()

# Apply background substraction
mask = background_substraction.apply(image)

# Apply the mask to the input image
result = cv2.bitwise_and(image, image, mask=mask)

# Save the result
cv2.imwrite('output.png', result)

The code above first reads an input image, then creates a black mask with the same dimensions as the image, sets all the background pixels to white (255), and then creates a background substraction object. Next, it applies the background substraction to the input image and then applies the mask to the image. Finally, it saves the result.

Using Pillow

The Pillow library is another great tool for manipulating images. We can use it to remove the background of an image. Here’s the code:


from PIL import Image

# Read the input image
image = Image.open('input.jpg')

# Create a mask with the same dimensions as the image
mask = Image.new('L', image.size, color=255)

# Create a background substraction object 
background_substraction = Image.new('L', image.size, color=0)

# Apply background substraction
mask = background_substraction.point(lambda x: 0 if x == 0 else 255, '1')

# Apply the mask to the input image
result = Image.composite(image, mask, mask)

# Save the result
result.save('output.png')

The code above first reads an input image, then creates a black mask with the same dimensions as the image. Next, it creates a background substraction object and applies the background substraction to the input image. Finally, it applies the mask to the image and saves the result.

Now that you know how to remove the background of an image using Python, you can try it out on your own images and see the results!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.