Image Effects How to Make a Low-Quality Image Look Better Understanding Lossless Image Compression How to Set Up Image Registration in Python 8 Different Image Processing Techniques You Can Use 4 Ways to Make an Image Larger without Losing Quality 3 Easy Ways to Eliminate Duplicate Images The Basics of Face Detection in Python How to Implement Multiple File Upload in PHP Like a Pro Creating Custom Image Cropping Interfaces in Android How to Create Simple Yet Effective PHP Overlay Understanding Real-Time Image Recognition How to add a shadow effect to an image with CSS How to crop an image in Flutter with Cloudinary How To Rotate an Image with Java Image Processing with Python Rotating an image with CSS Enhancing User Experience with a Responsive Image Slider Building a Python Image Recognition System Building an Interactive JavaScript Image Manipulation Tool Image Align Centering with HTML and CSS Efficient Image Cropping Techniques with Angular and Cloudinary Ultimate Guide to Photo Gallery on Android A Comprehensive Guide to Adding Text to Images on Android Mastering Background Changes in React Applications Comprehensive Guide on Changing Background on Android Devices Mastering Image Rotation in Java A Guide to Adding Text to Images with Python A Guide to Converting Images to Grayscale with Python Introduction Creating an Image Overlay with JavaScript Rotating an Image in Python Creating a Dynamic Photo Gallery with jQuery Creating An Interactive Photo Gallery Using JavaScript Mastering Overlay in Android Mastering Angular Overlay: A Comprehensive Guide Comprehensive Guide to Overlay in Flutter Mastering Overlay React for Responsive Design Solutions Create a Blurred Image with PHP: A Comprehensive Guide Guide to Using Blur Image in Flutter Mastering Blur Image in React Native Mastering Image Blurring in Python Mastering the Art of Image Blurring Mastering the Art of Image Blurring in Java The Ultimate Guide to Blurring Images on Android Understanding and Implementing Blur Image in JQuery An Extensive Walkthrough of Blurring Images with JavaScript How to Use HTML, CSS, and JavaScript to Make an Image Slider HTML Image Tag How to Crop GIFs? How to Align Images with CSS Ken Burns Effect – Complete Guide and How to Apply It Cartoonify – Complete Guide on Cartoonify Image Effect Mastering Web Aesthetics: A Comprehensive Guide to Gradient Fades Sepia Effect: The Ultimate Guide to the Sepia Photo Effect What is Vignette? Guide to Vignette Image Editing Pixelate – The Ultimate Guide to the Pixelation Effect How to Outline an Image: Enhancing Visual Appeal and Depth Make Your Photos Pop with Image Effects Upscale Image – Developers guide to AI-driven image upscaling Image Manipulation: History, Concepts and a Complete Guide A Full Guide to Object-aware Cropping Simplify Your Life with Automatic Image Tagging How To Resize Images In WordPress How To Create a Progress Bar For Asset Uploads Animated GIFs – What They Are And How To Create Them How To Automatically Improve Image Resolution AI Drop Shadow Get Image Dimensions From URLs Automatically Add Sepia Effect To Images Automatically Make an Image a Cartoon Automatically Add Blur Faces Effect To Images Automatically Add Background Removal Effect to an Image How to Resize an Image with React How to Easily Resize an Image with React Native

Automatically Add Background Removal Effect to an Image

background removal

Images are used for a variety of use cases; advertising, preserving memories, and highlighting beauty to name a few. Sometimes, a perfect image might be ruined by a flaw such as an undesirable object or from harsh lighting. When a flaw draws a viewer’s attention away, you may want to consider removing the background from the image.

This post will discuss how to automatically remove a background from an image—and at scale.

In this article:

Why is background removal useful?

Sometimes there are unwanted items in an image, and rather than taking time to re-shoot them, background removal can be the most efficient process.

Although you can accomplish background removal through traditional tools, these tools require large amounts of time. Many free online tools state they can automatically remove backgrounds, but these tools often yield random and sporadic results. Enter Cloudinary.

“Image

What is Cloudinary?

With Cloudinary, you can automatically perform background removal effects, at scale. It uses machine learning and artificial intelligence to quickly and accurately identify the main foreground before removing the background. What’s more, Cloudinary can perform this on multiple images simultaneously.

So let’s move ahead and see how you can use Cloudinary to remove backgrounds from your images

Getting started

To remove backgrounds from images using Cloudinary, first create a free account.

Additionally, you must have the Node JS SDK installed on your PC, and register for the “Cloudinary AI Background Removal” add-on. To register, login to your account and navigate to the “Add-ons” tab:

Cloudinary Add-ons inside of the console

Scroll down and select the “Cloudinary AI Background Removal” add-on:

AI background removal

Then choose the best plan for you. The free plan is what we will use in this tutorial:

Select background removal add-on

Now that you’ve set up your account, it’s time to start removing backgrounds from images!

How to remove background when uploading images to Cloudinary

Cloudinary allows you to request background removal a few ways; either when uploading images to Cloudinary (from your server-side code or directly from the browser) or updating an existing image, either programmatically or interactively.

Let’s start by creating a JS script that uploads images to the cloud. To do this, you’ll first need your Cloudinary environment variable. Retrieve this by clicking on “Dashboard” and looking at the API Environment variable as shown below:

Welcome to your CLoudinary Dashboard

Then, create a project folder on your computer. Open the folder and create a file with an .env extension. Open this file and paste your environment variable:

Enter environment variable

Next, set up your upload environment. You’ll use two different libraries, the Cloudinary Node JS SDK and the dotenv, allowing the development environment to use your Cloudinary account credentials to upload assets. Open the terminal and navigate to your project folder. Run the following commands to install the libraries:

npm install dotenv
npm install cloudinary

Create an assets folder in your project folder and add the images you want to upload:

Add asset to remove background

Now set up the upload script. Create a file named Upload.js in your project folder and import the relevant libraries:

// Reads the Cloudinary Environment variable
require("dotenv").config();

// Using V2 of Cloudinary Node JS SDK
const cloudinary = require("cloudinary").v2;

// Picking up env and configuring
console.log(cloudinary.config().cloud_name);

Call the upload API and reference the file you want to upload:

// Calling upload API
cloudinary.uploader
.upload("assets\wood_chair.jpg", {
    // Specifying the resource type of the image
    // image is the default resource type even if
    // you don't specify
    resource_type: "image", public_id: "wood_chair"
})
.then((result) => {

    // JSON.stringify will provide output in a formatted
    // string
    console.log("success", JSON.stringify(result, null, 2));

})
.catch((error) => {
    console.log("error", JSON.stringify(error, null, 2));
});

Then, run the code using Node:

node Upload.js

Run the code Node.js

You can view the uploaded image by using the URL provided in the terminal or going to the “Media Library” tab in Cloudinary:

Add media in media library

You’ll notice the image name carried over from upload. The image name is also called the Public ID in Cloudinary.

Here is the uploaded image:

Uploaded image ready to remove background image of a chair

To remove the background from the image, simply modify the upload API by adding background_removal and specifying it as "cloudinary_ai":

// Calling upload API
cloudinary.uploader
.upload("assets/wood_chair.jpg", {
    // Specifying the resource type of the image
    // image is the default resource type even if
    // you don't specify
    resource_type: "image", public_id: "wood_chair_removed",

    // Adding Background Removal
    background_removal: "cloudinary_ai"
})
.then((result) => {

    // JSON.stringify will provide output in a formatted
    // string
    console.log("success", JSON.stringify(result, null, 2));

})
.catch((error) => {
    console.log("error", JSON.stringify(error, null, 2));
});

In addition, we also change the public_id (the unique identifier for an asset stored in Cloudinary) to wood_chair_removed in order to avoid overriding the existing image on the cloud.

Here is the final code to remove the background from the image:

// Reads the Cloudinary Environment variable
require("dotenv").config();

// Using V2 of Cloudinary Node JS SDK
const cloudinary = require("cloudinary").v2;

// Picking up env and configuring
console.log(cloudinary.config().cloud_name);

// Calling upload API
cloudinary.uploader
.upload("assets/wood_chair.jpg", {
    // Specifying the resource type of the image
    // image is the default resource type even if
    // you don't specify
    resource_type: "image", public_id: "wood_chair_removed",

    // Adding Background Removal
    background_removal: "pixelz"
})
.then((result) => {

    // JSON.stringify will provide output in a formatted
    // string
    console.log("success", JSON.stringify(result, null, 2));

})
.catch((error) => {
    console.log("error", JSON.stringify(error, null, 2));

Running the code yields the following image:

Chair image with background removed automatically

How to remove background programmatically from images

Now, let’s look at how to update images in the cloud. First, upload a sample image to the cloud. The image named cld-sample-5 (this is also the image Public ID) provided in your free account will be used for this tutorial:

Image of a shoe to remove background from

Create a new file in your project folder named Update.js, and use the same libraries from previously. Call the Cloudinary API with the .update method while specifying the public_id of the image and the background removal transformation you want to apply:

// Reads the Cloudinary Environment variable
require("dotenv").config();

// Using V2 of Cloudinary Node JS SDK
const cloudinary = require("cloudinary").v2;

// Picking up env and configuring
console.log(cloudinary.config().cloud_name);

// Updating the Image
cloudinary.api.
update("cld-sample-5",
  { background_removal: "cloudinary_ai"})
.then(result=>console.log(result));

In the Cloudinary Media Library, you’ll see the following:

Shoe with background removed in Cloudinary Media Library

Running the code yields the resulting image:

Shoe with removed background with AI

Additionally, you can use the API to remove backgrounds from images on the fly. Let’s remove the background from wood_chair, which was previously uploaded:

Uploaded image ready to remove background image of a chair

Using the same code as above, simply call the image using cloudinary.image and specify the effect parameter as "background_removal". Here is the final code:

// Reads the Cloudinary Environment variable
require("dotenv").config();
 
// Using V2 of Cloudinary Node JS SDK
const cloudinary = require("cloudinary").v2;
 
// Picking up env and configuring
console.log(cloudinary.config().cloud_name);

// Retrieving image while specifying red eye removal
const img = cloudinary.image("wood_chair",
    {effect: "redeye"}
    );

console.log('images', img)

Running the code yields the following image:

Chair image with background removed automatically

Removing the background from images programmatically at scale

With Cloudinary, you can apply different transformations to your images on the fly. To remove the background from hundreds of images, you must list your assets and run API calls on them.

To scale our transformation, you’ll first upload your assets to Cloudinary. For this demonstration, however, we will use the sample images provided by Cloudinary. Login to Cloudinary and navigate to the Media Library tab. The images are highlighted below:

Highlighted images to remove background

You can see the public_id of the uploaded images as versions of “cld-sample.” We will be using the Cloudinary API on these images.

Next, using the same code as before, run the same API call for the images with the only difference being the public_id:

// Reads the Cloudinary Environment variable
require("dotenv").config();

// Using V2 of Cloudinary Node JS SDK
const cloudinary = require("cloudinary").v2;

// Picking up env and configuring
console.log(cloudinary.config().cloud_name);

// Retrieving Images
const img1 = cloudinary.image("cld-sample", { effect: "background_removal"});
const img2 = cloudinary.image("cld-sample-2", { effect: "background_removal"});
const img3 = cloudinary.image("cld-sample-3", { effect: "background_removal"});
const img4 = cloudinary.image("cld-sample-4", { effect: "background_removal"});
console.log("images", img1);
console.log("images", img2);
console.log("images", img3);
console.log("images", img4);

Run the code to generate the image URLs:

Generate image URLs with the code

View the uploaded images using the URLs provided in the terminal. Here are the resulting images:

Resulting image

Image with background removed

Image with background removed

Image with background removed

Conclusion

Background removal is a common use case that allows you to optimize your images as needed. Cloudinary is a powerful media-management platform that uses automation and machine learning to streamline workflows. Over a million developers choose Cloudinary to manage their media—bulk uploads of raw photos to on the fly transformations that create optimizations, media variants, and responsive delivery on all devices. To learn more, visit the Cloudinary Documentation. To get started, visit https://cloudinary.com/users/register_free.

More from Cloudinary:

Cloud-based API for applying effects on images

Send API Requests with Ease Using Cloudinary Postman Collections

Automatically Generate Collages At Scale with Cloudinary

QUICK TIPS
Colby Fayock
Cloudinary Logo Colby Fayock

In my experience, here are tips that can help you better implement background removal using Cloudinary and achieve optimal results:

  1. Choose the right background removal method for accuracy
    Cloudinary supports different background removal options, such as cloudinary_ai, pixelz, and remove.bg. Each has its own strengths. For high-accuracy results, especially in complex images, consider starting with cloudinary_ai. For batch processing large eCommerce inventories or cleaner studio backgrounds, pixelz can be a better option due to its customization for product images.
  2. Use ‘e_outline’ for additional refinements
    After removing the background, if you want a cleaner, well-defined subject, add an e_outline transformation. This creates a smoother edge around your subject and avoids the jagged or fuzzy edges that can sometimes occur after background removal. Use the thickness parameter to control the width of the outline.
  3. Add context-appropriate backgrounds automatically
    After removing the background, consider automatically adding context-appropriate backgrounds, such as gradients or branded color backdrops. This can be accomplished by chaining transformations using overlays, or by using Cloudinary’s b_auto:rgb to select complementary colors from the image itself.
  4. Test with shadow and border effects for a polished look
    To ensure your product images look professional, apply drop shadows or borders after removing the background. Use the e_dropshadow or bo_Xpx_solid parameters to achieve this. This technique is especially useful for eCommerce and marketing images, making products appear polished and ready for use on websites.
  5. Use the ‘crop pad’ mode to retain aspect ratios
    Background removal can alter the visual balance of your images. To maintain uniform aspect ratios and consistency, use the c_pad transformation after removing the background. This ensures that even after background removal, the image retains its standard size and padding, which is essential when managing bulk product images.
  6. Combine with auto-gravity for centered subjects
    If your subject shifts after background removal, consider combining the g_auto gravity option to automatically center the subject. This transformation can help adjust the subject’s position within the frame, keeping it well-centered, which is crucial for maintaining visual alignment across a gallery or product catalog.
  7. Adjust transformation presets based on image type
    Different types of images require different levels of background removal precision. Create and use named transformation presets based on the subject—such as people, products, or text—to ensure that the background removal is optimized for each scenario. This way, you won’t have to manually configure different settings each time.
  8. Leverage batch processing for large-scale operations
    For handling large volumes of images, use Cloudinary’s batch processing API. Automate the background removal across multiple images by iterating through image IDs, applying the same background_removal effect. This approach is ideal for content moderation or platforms with user-generated content, where manual editing isn’t feasible.
  9. Implement image quality analysis before processing
    Before applying background removal, check the image quality and resolution using Cloudinary’s q_auto or fl_lossy transformation. This ensures that the background removal is being performed on high-quality images, resulting in better edge detection and fewer artifacts during the transformation.
  10. Monitor processing costs with transformation analytics
    Background removal, especially using AI, can be resource-intensive. Use Cloudinary’s transformation analytics to monitor processing costs and effectiveness. If certain image types (e.g., complex backgrounds) are repeatedly failing, consider pre-processing them or using a lower-cost alternative. This will help optimize both your budget and image quality.

By following these tips, you can leverage Cloudinary’s capabilities for background removal more effectively and ensure a streamlined, high-quality media management process.

Last updated: Oct 3, 2024