Remove Background From Image With Python For Free!

Remove Background from Image with Python

Removing the background from an image is a common task in image processing, whether you’re enhancing photos, creating graphics, or preparing images for websites. Python, with its powerful libraries like OpenCV and PIL (Pillow), provides a convenient and effective way to achieve this. In this guide, we’ll explore how to remove the background from an image using Python, and best of all, it’s completely free!

Prerequisites

Before diving into the process, make sure you have Python installed on your machine. You can download Python from the official website (https://www.python.org/), and for package management, we’ll use pip, which usually comes bundled with Python.

To follow along with the examples, install the required libraries:

pip install opencv-python numpy pillow

Steps to Remove Background

Let’s break down the process into simple steps:

1. Import Libraries

import cv2
import numpy as np
from PIL import Image

We import OpenCV (cv2) for image processing, NumPy (numpy) for numerical operations, and Pillow (Image) for opening and saving images.

2. Load the Image

image_path = 'path/to/your/image.jpg'
image = cv2.imread(image_path)

Replace ‘path/to/your/image.jpg’ with the actual path to your image. cv2.imread reads the image, and we store it in the variable image.

3. Convert Image to Grayscale

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

Converting the image to grayscale simplifies the background removal process. We use cv2.cvtColor to convert the image from BGR (Blue, Green, Red) to grayscale.

4. Apply Thresholding

_, thresh = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY)

Thresholding converts the grayscale image into a binary image, where pixels are either black or white. Adjust the threshold value based on your image characteristics.

5. Find Contours

contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

Contours are the boundaries of the objects in the image. We find contours using cv2.findContours on the thresholded image.

6. Create a Mask

mask = np.zeros_like(image)
cv2.drawContours(mask, contours, -1, (255, 255, 255), thickness=cv2.FILLED)

We create a mask, a black image with the same dimensions as the original image. cv2.drawContours fills the contours with white color on the mask.

7. Bitwise AND

result = cv2.bitwise_and(image, mask)

Using bitwise AND between the original image and the mask removes the background.

Putting It All Together

import cv2
import numpy as np
from PIL import Image

# Load the image
image_path = 'path/to/your/image.jpg'
image = cv2.imread(image_path)

# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply thresholding
_, thresh = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY)

# Find contours
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Create a mask
mask = np.zeros_like(image)
cv2.drawContours(mask, contours, -1, (255, 255, 255), thickness=cv2.FILLED)

# Bitwise AND
result = cv2.bitwise_and(image, mask)

# Display the result
cv2.imshow('Original Image', image)
cv2.imshow('Background Removed', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Replace ‘path/to/your/image.jpg’ with the actual path to your image. This script displays both the original image and the background-removed image.

Source Code

Now that we’ve gone through the steps, let’s break down the source code:

  • cv2.imread(image_path): Reads the image.
  • cv2.cvtColor(image, cv2.COLOR_BGR2GRAY): Converts the image to grayscale.
  • cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY): Applies thresholding to create a binary image.
  • cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE): Finds contours in the binary image.
  • np.zeros_like(image): Creates a black mask with the same dimensions as the original image.
  • cv2.drawContours(mask, contours, -1, (255, 255, 255), thickness=cv2.FILLED): Draws contours on the mask, filling them with white color.
  • cv2.bitwise_and(image, mask): Applies bitwise AND to remove the background.
  • cv2.imshow: Displays the original image and the background-removed image.

Customization and Fine-Tuning

  • Adjust Thresholding: Experiment with the threshold value (cv2.threshold) to get the best result based on the characteristics of your image.
  • Refine Contours: Depending on your image, you might need to refine the contours using techniques like dilation or erosion.
  • Optimize for Specific Images: This script provides a basic approach. For complex images or specific requirements, consider additional techniques.

Conclusion

Removing the background from an image using Python is a powerful and accessible process, especially with the wealth of libraries available. The combination of OpenCV, NumPy, and Pillow provides a versatile toolkit for image processing tasks.

Whether you’re enhancing product images for an e-commerce website or creating visually appealing graphics, the ability to remove the background allows for greater flexibility and creativity in your projects. The provided source code serves as a foundation that you can build upon and customize to suit your specific needs.

Feel free to experiment, fine-tune, and integrate this process into your image processing workflows. With the right tools and a bit of Python scripting, you can achieve impressive results in removing backgrounds from images without any cost.

Vanel Sylvestre

I am Vanel Sylvestre , welcome to my world, i am a real estate investor, business owner and also i am an affiliate marketer with over 10 years of experience in online marketing i have been making thousands Online Using Online Marketing Tools. In This blog We share some online marketing tools that can help you grow your business, if this is something you are interested in, one more time welcome to my world.

Leave a Reply