Remove Background From Image With Python For Free!

remove background from image with python

I was surfing the internet looking for AI tools and methods to make money online when 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. So, I searched 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 the Python script I built as simple as possible so that even newbies could use and run it.

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:

You can make money using this tool by turning it into an online tool that people pay to use based on a monthly subscription. Or, you can turn the script into an API, publish it on RapidAPI, and sell it for a monthly recurring income as I do with my APIs.

Remove Background from Image with Python

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

Two methods are very important in this Python Script. One saves the output, and the other will create the mask of the image, the image without background, and returns it.

In the first part, we load the model. (I will also give you the trained model so you can use it directly.) Then, 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, open the script again, and paste the image path here:

Now, run the script, and to see the results, go to your Python Project Folder.

Find a folder named ‘static’ and go to inputs in this folder.

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!

Source Code

Also, here is some help with the file structure if you download the Full Project Folder:

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.

The inputs, masks, and results are in the static folder. You can also find them here. 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.

Similar Posts

91 Comments

  1. shamsUl Din says:

    sir make a detaild video how to create website using this script

    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. Hasan Aboul Hasan says:

        Thanks, not yet. I will try my best

  2. sir your script is so good and very useful for beginners like me. so I want to add it as a tool to my website how can I do that could help with that?

    thank you very much, sir

    1. Hasan Aboul Hasan says:

      I will explain this soon

        1. Hasan Aboul Hasan says:

          I will try my best

  3. Mr.Olafson says:

    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!

    1. Hasan Aboul Hasan says:

      Thank you 🙂

  4. John Andoh says:

    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

    1. Hasan Aboul Hasan says:

      We will soon have a python course. stay tuned 🙂

  5. Thank you very much for sharing your knowledge. Your content is really of very high value and not everyone shares knowledge

    1. Hasan Aboul Hasan says:

      Thanks 🙂

  6. Isaiah Ebrume says:

    Awesome sir great work.

  7. Tariq mahmood says:

    Good work best of luck

  8. 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

    1. Hasan Aboul Hasan says:

      Thank you!

  9. Hello
    Thanks for sharing the script and tutorial
    It gives an error message only when running the script
    ModuleNotFoundError: No module named ‘torch’
    https://postimg.cc/cK05pn75

    1. Hasan Aboul Hasan says:

      PLease install requirements

  10. Mr.Hasan,
    Remove BG is the most famous site for removing background of the photos.
    You are giving a similar tool for free! You are really great.
    Thank you so much.

  11. I really appreciate what you are doing Mr Hassan

    1. Hasan Aboul Hasan says:

      Thank you!

  12. Anjum Farooq says:

    Hi you are doing a treasure hunt. Thanks so much and very appropriate to you for giving it free to us.

    1. Hasan Aboul Hasan says:

      Thank you!

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

    There’s no text file?

  14. Fatma Yılmaz says:

    Hi Hasan,firstly thansk for your effort and I have a question I can not find saved_models/u2net/u2net.pth

    1. Hasan Aboul Hasan says:

      Did you download the whole project ? or github, please double check

  15. 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,

    1. Hasan Aboul Hasan says:

      Please install the requierments

  16. i really appreciate you work mr hassan.

    1. Hasan Aboul Hasan says:

      Thank you!

  17. 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

    1. Hasan Aboul Hasan says:

      Thank you Richard 🙂

  18. Hasan Aboul Hasan says:

    I will 🙂

  19. Baffa Muhammad Inuwa says:

    Great project!!!

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

    Thank you very much.

  20. (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 ).

  21. (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.

  22. 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.

  23. 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. Hasan Aboul Hasan says:

      Thank 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.

  24. Calvin KOMDJEU says:

    Greetings Mr. Hasan,
    I am here to say a big thank you for this gift.

    Thank you!

    1. Hasan Aboul Hasan says:

      Thank you 🙂

  25. 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.

    1. Hasan Aboul Hasan says:

      I will create some courses soon

  26. stephane menga says:

    Thank you sir! Can we enhance this u2net model?

    1. Hasan Aboul Hasan says:

      sure, you can train and finetune it

  27. Am kayode says:

    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

    1. Hasan Aboul Hasan says:

      I will do soon

  28. Here is a rembg tool to remove images background. It also uses U2Net model as default. But it has more simple Python code to use. URL: https://github.com/danielgatis/rembg
    I think your code is elegant and I’m going to test it inside a Google CoLab notebook.

  29. 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.

  30. hi, no output when i use my own image as input.

    1. sure you changed the filename including the right path and suffix? ( “1.jpg” to “myself.png” for example)

  31. Nasser Aloreefy says:

    Thank you Mr. Hassan for your videos and hard work. I downloaded the whole folder and opened it in Visual Studio Code, but I couldn’t run it. Here is a screenshot of the situation ( https://prnt.sc/rOZdgEzoqBaB )

  32. Chanaka Samarawicrama says:

    how to install cv2

    1. …pip install opencv-python

  33. LeviFiction says:

    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.

  34. 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

  35. Hi Hasan

    I tried your python code. Its perfectly working for me. Thank you Hasan

    1. how is working for me say 8 errors no torch founded?

  36. mrbytes31 says:

    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!

  37. Hi Hasan, I watch the video and find the github repo, thank you for the work and info you provide.
    I only had trouble downloading the full script from https://largefilesender.com/en/5Xg6tilpedroa0T/file

    It says there is a problem while trying downloading the file. Is the github repo containing the same script?

  38. 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?

    1. Hasan Aboul Hasan says:

      Good Idea, you can do so, share with us the results of you do something like that

  39. CLARK DJILO says:

    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

    1. Hasan Aboul Hasan says:

      I will try my best

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

    1. Hasan Aboul Hasan says:

      Thanks, I will try my best 🙂

  41. Abdul Basit says:

    I Cant Find the Model in Saved Model, u2net.pth….This File does not Exist in there

    1. Hasan Aboul Hasan says:

      did you download the files provided in this post?

  42. Hi Hasan,
    Could I get the dataset that was used to train this model? 🙂

    1. Hasan Aboul Hasan says:

      Hi 🙂 check the project on github

  43. when are you releasing video on how to turn this script to website. if you can do it with wordpress will be fine

    1. Hasan Aboul Hasan says:

      I will try my best

  44. Hi Hassan. It seems the file u2net.pth is missing from the directory. It’s not there in the github link nor in the download link. Am I missing something?

    1. Hasan Aboul Hasan says:

      are you sure it is not in the downloaded zip

  45. Anas Siddiqui says:

    Hello Hassan,

    Hope you are doing well. I couldn’t find the requirements file to install the necessary packages in your downloaded folder.

  46. salman qureshi says:

    hey bro can you make detailed video how to convert that into a website

    1. Hasan Aboul Hasan says:

      I will try my best

  47. Sir, Kindly, make a detailed video on how to create a website using node js.

  48. you are an outstanding programmer my friend…
    looking for a video where you will describe :
    how to use python and all kinds of source code run not only in terminal or in a studio app. but also in web app, mobile app, making apis… from a python script or from the tool which we will make on local pc.
    hope you will understand what i’m trying to say.
    thanks for your effort from Bangladesh.

    1. Hasan Aboul Hasan says:

      Thanks, I will try my best

  49. Greetings from Nigeria sir I have been following your channel since 2020 but later quit online marketing because I tried my first blog and failed but have decided try again. Thanks so much for the much value you give in all your tutorials. Sir how can I add this script to my WordPress website. I learnt from one of your website traffic booter methods is to offer free services of value to people. I would like to gain more visitors to use the tool and also boost my website traffic. Thanks for your time

    1. Hasan Aboul Hasan says:

      Thanks, this is a python script, if you want to add to wordpress, you will need to convert into an API, and then create a custom tool on wordpress that interacts with it.

Leave a Reply

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