Removing the background from an image and replacing it with a new one is a common task in image processing, especially in design, marketing, and photography. Python, with its powerful libraries, offers a simple and efficient way to accomplish this task. In this article, we will walk you through how to remove an image’s background and replace it with a new background using Python.
We will leverage libraries like OpenCV, Pillow, and rembg for background removal and image manipulation. Let’s explore each step with detailed coding examples and explanations.
Prerequisites
Before we begin, ensure you have the following libraries installed:
pip install opencv-python pillow rembg
- OpenCV: An open-source library for computer vision and image manipulation.
- Pillow (PIL): A powerful image processing library.
- rembg: A popular tool for removing the background from images using AI models.
Step 1: Load and Display the Image
To start, we’ll load an image using OpenCV and display it. You can use any image with a clear foreground subject to see the effect.
import cv2
from matplotlib import pyplot as plt
# Load the image using OpenCV
image_path = 'your_image.jpg'
image = cv2.imread(image_path)
# Convert image from BGR (OpenCV default) to RGB
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Display the original image
plt.imshow(image_rgb)
plt.title('Original Image')
plt.axis('off')
plt.show()
Output:

Step 2: Remove the Background
We’ll use the rembg library, which removes the background from the image. This tool uses deep learning to distinguish between the foreground (subject) and the background.
Here’s how to remove the background:
from PIL import Image
from rembg import remove
# Load the image using Pillow
input_image = Image.open('your.jpg')
# Remove the background
output_image = remove(input_image)
# Save the image without background
output_image.save('output_no_background.png')
# Display the image without the background
output_image.show()
Output:

The rembg library efficiently processes the image and removes the background, leaving only the foreground subject. The result is a PNG image with a transparent background.
Step 3: Replace the Background
Now that we have an image with a transparent background, we can replace the background with another image. We’ll use Pillow to overlay the subject on a new background image.
Here’s how you can replace the background:
from PIL import Image
from rembg import remove
# Load the image using Pillow
input_image = Image.open('your.jpg')
# Remove the background
output_image = remove(input_image)
# Save the image without background
output_image.save('output_no_background.png')
# Display the image without the background
output_image.show()
# Open the new background image
background = Image.open('new.jpg')
# Resize the background to match the size of the original image
background = background.resize(output_image.size)
# Paste the foreground (subject) onto the new background
background.paste(output_image, (0, 0), output_image)
# Save and display the final image
background.save('final_image.png')
background.show()

Detailed Explanation
1. Loading and Displaying the Image:
We first load the image using OpenCV’s cv2.imread() function. Since OpenCV uses the BGR color space, we convert it to RGB using cv2.cvtColor() to display it correctly with matplotlib.
2. Removing the Background:
The rembg library is a powerful background removal tool. The function remove() processes the image and returns a PNG with a transparent background. We use the PIL library to load and save the images, as it handles formats like PNG with transparency support.
- Foreground Subject Detection: The AI model in
rembgidentifies the subject in the image and separates it from the background. - Transparent Background: The resulting image is saved as a PNG with a transparent background, making it easier to overlay on another image.
3. Replacing the Background:
In this step, we replace the transparent background with a new one using Pillow. First, we open the new background image and resize it to match the dimensions of the original image. Then, we use the paste() method to overlay the subject (foreground) onto the new background.
- Image Alignment: We position the foreground at the top-left corner using
(0, 0)coordinates. The third argument inpaste()ensures that the transparency of the foreground is preserved when pasting it onto the new background.
Once you’ve replaced the background, you can further enhance the image by applying filters, resizing the image, or adding borders.
Note: you can simply use this code to remove background of any image. Instead of using paid tools or adobe.
Conclusion
Removing and replacing the background of an image using Python is an accessible and highly efficient process, thanks to powerful libraries like OpenCV, Pillow, and rembg. Each of these tools contributes specific strengths to the workflow: OpenCV offers robust image manipulation, Pillow provides image handling and enhancement capabilities, and rembg leverages AI for precise background removal.
By combining these libraries, you can automate background removal and replacement, making it perfect for tasks in graphic design, product photography, marketing, and more. The process begins by loading the image, then removing the background using AI-based techniques, and finally replacing it with any background of your choice, allowing for endless creativity and customization.
This approach not only simplifies what used to be a labor-intensive task but also opens the door for developers and non-designers alike to handle image processing efficiently. With just a few lines of Python code, you can achieve professional-level results in your projects. Whether you are building web applications, editing photographs, or creating custom visuals for marketing campaigns, mastering these techniques will significantly enhance your ability to manipulate images programmatically.





Leave a Reply