Last active
May 14, 2019 09:17
-
-
Save protorob/b23433835e7b5d62dc7be28dadbc9546 to your computer and use it in GitHub Desktop.
A simple Python script to batch remove backgrounds from images in a directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This script asumes that you have two directories | |
# One directory called "origin" with your original images | |
# Another directory valled "results" that is going to be filled with your processed images :-) | |
# The name of the directories should be exactly like that "origin" and "results" respectively | |
# The script also need a remove.bg API key, so you should get one of those | |
# https://www.remove.bg/api | |
# it also require "requests" to be installed (see python-requests.org) | |
import requests | |
import os | |
# The directory with your original images | |
filepath = 'origin' | |
# "small": 1 credit, "medium": 3 credits, "hd": 5 credits, "4k": 8 credits, "auto" = automatically use highest resolution available (based on image size and subscription plan). | |
img_size = 'auto' | |
# Your Remove.bg Api Key | |
removebg_key = 'YOUR-API-KEY-GOES-HERE' | |
for thefile in os.listdir(filepath): | |
filename = os.fsdecode(thefile) | |
filename_noext= os.path.splitext(thefile)[0] | |
response = requests.post( | |
'https://api.remove.bg/v1.0/removebg', | |
files={'image_file': open('origin/{}'.format(filename), 'rb')}, | |
data={'size': img_size}, | |
headers={'X-Api-Key': removebg_key}, | |
) | |
if response.status_code == requests.codes.ok: | |
with open('results/{}.png'.format(filename_noext), 'wb') as out: | |
out.write(response.content) | |
print('Great, {} has been processed!'.format(filename)) | |
i += 1 | |
else: | |
print("Error:", response.status_code, response.text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment