[Python] Automatically remove the background of the picture-Python matting, it is so easy

Cutout

The PS cutout is too complicated, and there are too many shortcut keys to remember. Sometimes the cutout is really needed. What should I do? As an IT learner, we can create many interesting things by ourselves.

We use the API of the removebg website to achieve automatic matting. Isn’t it cool? It can be achieved in a few simple lines of Python code, which is simply convenient.

Let's take a look? !

 

1. Remove the background of a picture

removebg website: https://www.remove.bg/zh/upload

First log in to the removebg website and register, check the API key in my account

from removebg import RemoveBg

# 去除一张图片
rmbg = RemoveBg('', 'error.log') #‘’为你的API密钥
path = 'data/image'
rmbg.remove_background_from_img_file(f"{path}/1.jpg")#图片根据自己的照片名称来修改哦

Then follow the code over there, modify your path, select the picture, note that the picture here is named 1.jpg, the picture after removing the background is automatically named the original name plus _no_bg.png, and the background is removed The picture is saved under the original picture path.

 

2. Remove the background of multiple photos

The code is no different from the previous one, but a loop is added, which is still very easy and simple

import os
from removebg import RemoveBg

#扣除多张图片
rmbg = RemoveBg('', 'error.log') #还是API密钥
path = 'data/image/removebg'#还是照片路径
for pic in os.listdir(path):
    img_path = os.path.join(path, pic)
    rmbg.remove_background_from_img_file(img_path)
    print(f"{img_path} is done!")

It should be noted that when picking up multiple images at a time, the format of the image itself may be incorrect or mismatched, resulting in an error. Common image format errors are reported as follows:

The HyperText Transfer Protocol (HTTP) 400 Bad Request

The very violent solution is to delete this picture. Don't ask me how I knew it, because there is a 2 missing in my picture.

Take a look at the effect, it is possible to cope with the less demanding cutout effect!

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/107840109