Back to all courses
This course will help you create and sell an API that removes backgrounds from images using a simple Python script.
This course will help you create and sell an API that removes backgrounds from images using a simple Python script.
It is a very popular use case. A quick search tells us that over ninety thousand people search for "remove background from image" on Google every month!
Many websites and tools are providing this service. You can upload your images there and have their backgrounds removed in no time. However, their pricing is jaw-droppingly expensive, with some charging up to $1.99 per image.
But, hold on, we've got a solution that will give them a run for their money. We can create a similar code that removes backgrounds from images. And you'll be amazed at how easy it is. The best part? You'll be able to make some serious cash with that ready-to-use Python script! It's super simple to use, and we'll show you how to create it into an API to sell it on RapidAPI Hub.
First, download and install Visual Studio Code and Python to get started. Once done, simply paste the following Python script into your code editor, and voila!
python
import torchimport torch.nn as nnimport torch.optim as optimimport numpy as npimport cv2import uuidimport osfrom model import U2NETfrom torch.autograd import Variablefrom skimage import io, transformfrom PIL import Image# Get The Current DirectorycurrentDir = os.path.dirname(__file__)# Functions:# Save Resultsdef save_output(image_name, output_name, pred, d_dir, type):predict = predpredict = 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 maskmask = 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 uint8with 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 imagetry:img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)except:# build a response dict to send back to clientreturn "---Empty image---"# save image to inputsunique_filename = str(uuid.uuid4())cv2.imwrite(inputs_dir + unique_filename + ".jpg", img)# processingimage = transform.resize(img, (320, 320), mode="constant")tmpImg = np.zeros((image.shape[0], image.shape[1], 3))tmpImg[:, :, 0] = (image[:, :, 0] - 0.485) / 0.229tmpImg[:, :, 1] = (image[:, :, 1] - 0.456) / 0.224tmpImg[:, :, 2] = (image[:, :, 2] - 0.406) / 0.225tmpImg = 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 = dnsave_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 pathprint(removeBg(imgPath))
Scroll down to the end of the script and add your desired image’s path to imgPath
and run the code in the terminal by typing python __init__.py
.
For example, I'll use the following image of a car.
I'll add its path to imgPath
test our code.
Now, run the code in the terminal by running python __init__.py
.
As a result, it will create the following image inside the project folder.
Awesome! Our code is working fine. For comparison, we can try the same image in other tools. The results will be pretty similar.
You can make a few simple changes to the code to turn it into a sellable API! Here’s what the code will look like after making the changes.
python
import torchimport torch.nn as nnimport torch.optim as optimimport numpy as npimport cv2import uuidimport osfrom model import U2NETfrom torch.autograd import Variablefrom skimage import io, transformfrom PIL import Imagefrom fastapi import FastAPI, File, UploadFilefrom fastapi.responses import JSONResponseapp = FastAPI()# Get The Current DirectorycurrentDir = os.path.dirname(__file__)# Functions:# Save Resultsdef save_output(image_name, output_name, pred, d_dir, type):predict = predpredict = 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 maskmask = 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)@app.get("/removeBG/")async def removeBG(image_file: str):# ------- 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 --------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 uint8with open(image_file, "rb") as image:f = image.read()img = bytearray(f)nparr = np.frombuffer(img, np.uint8)if len(nparr) == 0:return "---Empty image---"# decode imagetry:img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)except:# build a response dict to send back to clientreturn "---Empty image---"# save image to inputsunique_filename = str(uuid.uuid4())cv2.imwrite(inputs_dir + unique_filename + ".jpg", img)# processingimage = transform.resize(img, (320, 320), mode="constant")tmpImg = np.zeros((image.shape[0], image.shape[1], 3))tmpImg[:, :, 0] = (image[:, :, 0] - 0.485) / 0.229tmpImg[:, :, 1] = (image[:, :, 1] - 0.456) / 0.224tmpImg[:, :, 2] = (image[:, :, 2] - 0.406) / 0.225tmpImg = 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 = dnsave_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---"# print("---Removing Background...")# ------- Call The removeBg Function --------# imgPath = "1.jpg" # Change this to your image path# print(removeBg(imgPath))
So, now you can deploy this on a server like Heroku, and voila! Your very own API is ready to be sold on API marketplaces.
The best place to sell your API is the Rapid API Hub, the largest API directory in the world, where you can list your APIs and sell access to users who want to use them.
With different plans available, you can control how you monetize your creation and turn it into a lucrative business opportunity.
In summary, this course presents an incredible opportunity to create and sell an API that removes backgrounds from images. The process is simple, quick, and, most importantly, profitable! So, what are you waiting for? Get started today and let your creativity flow while making a handsome income!