Skip to content

Remove Background From Image With Python For Free!

remove background from image with python

I was surfing the internet searching for AI tools and methods to make money online, and I stumbled upon an Image Background Removal service called Remove.Bg

It works great. But I was shocked by the pricing. It charges $0.2-$1.99 per Image!?

remove background from image removebg

So, I decided to take the challenge and reverse engineer this website to build my own Free Image Background Remover without relying on any APIs or Third Parties.

I kept searching for a few days and found a great python project on GitHub, Called U2Net.

A Big Shout-out and Thanks to the authors of this project!

I tried my best to make things as simple as possible so that even newbies could use and run the python script I built.

I also created a Short Video showing The Script & How to use it, and I pointed out three methods and secrets that may help you build an online income stream with the help of this script. Here is the video:

For example, You can turn this into an online tool that people pay to use based on a monthly subscription. I did something similar with BoostCTR, FreeImageAI, LargeFileSender, and H-supertools.

What you can also do is that. You can use the script, turn it into an API, publish it on RapidAPI, and sell it for a monthly recurring income. I also do this with my Domain Authority API.

Remove Background from Image with Python

So, let’s open our source code with visual studio code

The main part of our script is this magic method called removeBg(). We’ll pass the Image Path as an argument.

So, two methods are very important in this Python Script. One saves the output, and the other will create the mask of the image and the image without background and return.

So, in the first part, we are loading the model. I will also give you the trained model so you can use it directly.

After Loading, we call the removebg() function to remove the background image.

Let’s see how it works I will reopen Remove.bg and get a sample image from their website.

So we can compare the results.

I will save this cat image on my desktop.

I will copy the name and open the script again. And paste the image path here

And run the script. 

To see the Results. Go to your Python Project Folder.

Find a Folder named ‘static.’

Now in the static folder, go to inputs.

So, this is the input (this is the main image.)

The Masks folder will have a mask of the same image.  

And finally, this is the result. It’s Great!

Now let’s go to Remove.bg. The result here is almost the same. 

Thanks to everyone who helped in developing this awesome machine-learning model.

Source Code

You can Download the Full Source Code or Check it out On GitHub

By the way, here’s the script!

#start
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import cv2
import uuid
import os
from model import U2NET
from torch.autograd import Variable
from skimage import io, transform
from PIL import Image
# Get The Current Directory
currentDir = os.path.dirname(__file__)
# Functions:
# Save Results
def save_output(image_name, output_name, pred, d_dir, type):
    predict = pred
    predict = predict.squeeze()
    predict_np = predict.cpu().data.numpy()
    im = Image.fromarray(predict_np*255).convert('RGB')
    image = io.imread(image_name)
    imo = im.resize((image.shape[1], image.shape[0]))
    pb_np = np.array(imo)
    if type == 'image':
        # Make and apply mask
        mask = pb_np[:, :, 0]
        mask = np.expand_dims(mask, axis=2)
        imo = np.concatenate((image, mask), axis=2)
        imo = Image.fromarray(imo, 'RGBA')
    imo.save(d_dir+output_name)
# Remove Background From Image (Generate Mask, and Final Results)
def removeBg(imagePath):
    inputs_dir = os.path.join(currentDir, 'static/inputs/')
    results_dir = os.path.join(currentDir, 'static/results/')
    masks_dir = os.path.join(currentDir, 'static/masks/')
    # convert string of image data to uint8
    with open(imagePath, "rb") as image:
        f = image.read()
        img = bytearray(f)
    nparr = np.frombuffer(img, np.uint8)
    if len(nparr) == 0:
        return '---Empty image---'
    # decode image
    try:
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    except:
        # build a response dict to send back to client
        return "---Empty image---"
    # save image to inputs
    unique_filename = str(uuid.uuid4())
    cv2.imwrite(inputs_dir+unique_filename+'.jpg', img)
    # processing
    image = transform.resize(img, (320, 320), mode='constant')
    tmpImg = np.zeros((image.shape[0], image.shape[1], 3))
    tmpImg[:, :, 0] = (image[:, :, 0]-0.485)/0.229
    tmpImg[:, :, 1] = (image[:, :, 1]-0.456)/0.224
    tmpImg[:, :, 2] = (image[:, :, 2]-0.406)/0.225
    tmpImg = tmpImg.transpose((2, 0, 1))
    tmpImg = np.expand_dims(tmpImg, 0)
    image = torch.from_numpy(tmpImg)
    image = image.type(torch.FloatTensor)
    image = Variable(image)
    d1, d2, d3, d4, d5, d6, d7 = net(image)
    pred = d1[:, 0, :, :]
    ma = torch.max(pred)
    mi = torch.min(pred)
    dn = (pred-mi)/(ma-mi)
    pred = dn
    save_output(inputs_dir+unique_filename+'.jpg', unique_filename +
                '.png', pred, results_dir, 'image')
    save_output(inputs_dir+unique_filename+'.jpg', unique_filename +
                '.png', pred, masks_dir, 'mask')
    return "---Success---"
# ------- Load Trained Model --------
print("---Loading Model---")
model_name = 'u2net'
model_dir = os.path.join(currentDir, 'saved_models',
                         model_name, model_name + '.pth')
net = U2NET(3, 1)
if torch.cuda.is_available():
    net.load_state_dict(torch.load(model_dir))
    net.cuda()
else:
    net.load_state_dict(torch.load(model_dir, map_location='cpu'))
# ------- Load Trained Model --------
print("---Removing Background...")
# ------- Call The removeBg Function --------
imgPath = "Image_File_Path"  # Change this to your image path
print(removeBg(imgPath))
#end

Also, here is some help if you download the Full Project Folder.

File Structure

when you open the Downloads folder. You’ll find this inside:

Saved models

U2NET 

And here is the trained model so you can use it directly. 

And we have the script file here.

And the static folder, we have the inputs, masks, and results. You can find them here also. It’s super easy to use.

You can use this requirements text file directly to import and install all the requirements with the pip command.

If you have any questions, please share them in the comments below.

If you find this helpful, share it with your friends!

🟥Master the Most In-Demand Skill of the Future!

Enroll in the ‘Become a Prompt Engineer‘ program. We’ll take you from novice to expert in scripting AI workflows. Start your journey here!

What Will You Get?

  • Access to our premium Prompt Engineering Course
  • Access our private support forum to get help along your journey.
  • Access to our Premium Tested Prompts Library.
nv-author-image

Hasan Aboul Hasan

Digital Entrepreneur with 8+ years' experience, Founder & Developer of PromoterKit. Helping Digital Marketers to achieve 10X results using AI and Automation.

77 thoughts on “Remove Background From Image With Python For Free!”

    1. I wish to learn how to use this with my website just like remove.ai is, have you made a video on this? I love how you explained in the first video Hasan

  1. I love you Hassan.
    Your vids/tuts are amazingly well balanced.

    Keep up the amazing work.
    (please do more of your dry dev humor to.
    like the one “Now we are getting dangerous”)

    Epic!

  2. I tried to learn to program on Coursera but stopped along the way.
    After following your channel on Ai for some time now I am beginning to develop an interest in Python and want to learn with the help of Ai, but I don’t know how to start.

    I need your advice and direction on how to start.

    Thank you

  3. Dear Mr. Hassan.

    Thank you for sharing your ideas online for free. Your generosity and selflessness are genuinely appreciated.
    I would be much grateful if you could make a detailed video on creating an online tool with the script you gave.

    Best regards,
    Justice
    From Ghana

  4. “You can use this requirements text file directly to import and install all the requirements with the pip command.”

    There’s no text file?

  5. Hello Mr. Hasan,
    first thanks for appreciated effort for making this script for free.
    but I ran into problem when I run the script it says : ModuleNotFoundError: No module named ‘torch’.
    can you help with this?
    thanks,

  6. Hey, just watched your YouTube video on this, you did a super job explaining how it all works together with your script. I’ll be setting it up for sure. Really love your videos, watching your videos on building backlinks right now.

    Keep putting out great stuff!

    Thanks again.
    Sincerely,
    Richard Weberg

  7. Baffa Muhammad Inuwa

    Great project!!!

    More greese to your elbow Mr Abul Hasan, we really appreciate your effort.

    Thank you very much.

  8. (I’m having trouble in Installing from requirement.txt)
    Solution:

    1. Download the file from GitHub as this contains the reqiurement.txt
    2. Then open the folder in Visual studio, click on requirement.txt then go to view>terminal to access the terminal panel then type “pip install -r ” in the terminal panel (You can copy the requirement.txt file path and then place it in ).

  9. (X file or module is missing)
    Solution:
    Type “pip install scikit-image”
    Above is just one example of installing missing files, you may replace with whatever file is missing and install it.
    You will type that command in the Visual Studio terminal.

  10. Kindly Hasan bro make a detailed video as soon as possible from downloading the script and how to add all requirements installation. I will wait for you.

  11. Thank you Hasan. This is the second video of yours that I have watched. I am 10% hooked. You are my AI teacher. I have learned a bit about ChatGPT promting but I am really a beginner with coding and machine learning. I am committed to learning these things. I WILL do this as you have explained, and I will report back to you how I do with it. I want to be ahead of the game. I want to be able to do more and more of what YOU are teaching. You are a TOP teacher as well as tremendously resourceful and creative, and very generous in your spirit. I salute you!

      1. Hi Hassan, how are you? I hope you see this message and I apologize if it is long or contains errors because I am writing with Google Translate , Your experiences and videos on YouTube have always amazed me, and I have been affiliated with the channel for a long time before my card broke. I have always liked the explanation and I loved you also. I see that you have changed the content to artificial intelligence and programming a little. You are right, you are in line with what is being asked today, and it is one of the reasons for your success. After being honest, I ask you to return the old videos of SEO and affiliate marketing, and the old videos, because I go back to them sometimes. I suggest that you open another channel for artificial intelligence and your new content. I do not want you to deprive us of the benefit and enjoyment of your old videos. To be honest, I did not win from the Internet until now, because I am facing personal problems, and I cannot open a bank account, and I do not have a personal identity card at all, because I am from Syria and an immigrant, but what I gained from you is a strong experience and a new mentality. I give you my full respect Greetings, and thank you for all the value you provide, even if I did not win anything, the experience I gained is enough. Thank you. If you see the message, I apologize again if the message is long.

  12. thanks for your video.
    but hope you make a video for super newbie. if you make that course, definitely I want to buy that..
    please let me know which nocoding website did you use to make that?
    no idea what I have to learn in three of them.

  13. Hassan I av been following u for the past 2years now I love ur content but each time I found it difficult to start my online career, actually I av an elementary knowledge on html, css,c but now I av decided to start my online career by choosing to become a data scientist I av enroll on alx program if u can do video on collecting, sort of data

  14. I am getting an error. FileNotFoundError: [Errno 2] No such file or directory: ‘Image_File_Path’. When I try to run it, this happens. I have replaced the Image_Name with 1.jpg but it still happens.

  15. Wanted to thank you for this. I use a photo editor called PaintShop Pro and their AI BG replacement tool only sees people, which I never take photos of. With edits, and compiling it to an exe, I was able to make this work with that program. The two are on par when it comes to people, but your edit makes it workable for other images.

    I have shared my compiled edits with the forums so others can use the app as well, and fully referenced and attributed you as the author of the code.

  16. selam Alaikum brother , thank you for all this information and all this free content you giving us. I just downloaded this zip file and can’t find the script . the one who ifind say has 8 probles and dont work .thank you

  17. First, I received bunch of errors when running the script, but since I know how to search, I resolved it.

    Thank you for this Hassan. I appreciate your effort and sharing this script. Now, I can remove background with HD quality instead of limited size. This is really a big help.

    You are such unselfish human being. Keep sharing and more power to you!

  18. Thank you Hasan, works perfectly well! What do you think about the following idea: instead of using a single model to remove the background, you could add two or three more models, that produce slightly different results and offer the outputs additionally so the user can choose between those results?

  19. Hello Hassan

    Thank you for this very great value

    Is it possible to do a video on how to offer this as a free service on a wordpress site please ?

    Regards

  20. Hi Hasan,
    I love everything about your teaching ,I love that platform (FreeAiKitTool);please you add (TEXT TO VIDEO) To the platform please? thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

Take Your Digital Marketing Skills To The Next Level

© 2023 LearnWithHasan | All Rights Reserved.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

🔴 New Series Started: Programming With AI - RJP Technique
This is default text for notification bar