有一个任务是要做毛笔字体库,首先将图片去除背景,第一批是200多张图片,如果手工去除背景工作量大,而且还不准确,使用remove bg 网站上的在线,得一个一个点,做不到批量更累。下面是使用python编写的,批量将图片去除背景方法:
code:
import requests
import os
import logging
API_ENDPOINT = 'https://api.remove.bg/v1.0/removebg'
DEFAULT_OUTPUT_FOLDER = 'output'
class RemoveBg:
def __init__(self, api_key):
self.__api_key = api_key
def remove_background_from_img_file(self, img_file_path, new_file_name=None):
with open(img_file_path, 'rb') as file:
response = requests.post(
API_ENDPOINT,
headers={'X-API-Key': self.__api_key},
files={"image_file": file},
data={'size': 'auto'}, # This line is added to request the image in its maximum size
stream=True
)
if response.status_code == requests.codes.ok:
with open(new_file_name if new_file_name else 'no-bg.png', 'wb') as out_file:
for chunk in response.iter_content(chunk_size=8192):
out_file.write(chunk)
print(f"Background removed for {img_file_path} and saved as {new_file_name}.")
else:
logging.error(f"Error processing {img_file_path}. Error: {response.text}")
def process_images_in_folder(self, input_folder, output_folder):
for file_name in os.listdir(input_folder):
if file_name.endswith(('.png', '.jpg', '.jpeg')):
img_path = os.path.join(input_folder, file_name)
output_path = os.path.join(output_folder, file_name)
self.remove_background_from_img_file(img_path, new_file_name=output_path)
def main():
api_key = input("Please enter your remove.bg API key: ")
remover = RemoveBg(api_key)
input_folder = input("Enter the path to the folder containing images (default is current folder): ") or '.'
output_folder = input(f"Enter the path for saving processed images (default is '{DEFAULT_OUTPUT_FOLDER}'): ") or DEFAULT_OUTPUT_FOLDER
if not os.path.exists(output_folder):
os.makedirs(output_folder)
remover.process_images_in_folder(input_folder, output_folder)
if __name__ == "__main__":
main()
输入api,在removebg 后台申请,记得买积分。
在输入,导入文件夹。
最后在输出 导出文件夹。
END
如本资源侵犯了您的权益,请联系投诉邮箱admin@wmphp.com进行举报!我们将在收到邮件的1个小时内处理完毕。
本站仅为平台,发布的资源均为用户投稿或转载!所有资源仅供参考学习使用,请在下载后的24小时内删除,禁止商用!
Wmphp.com(完美源码)助力正版,如您有自己的原创产品,可以联系客服投稿,代理出售!
Wmphp.com(完美源码)客服QQ:136882447
Wmphp.com(完美源码)商务电话(仅对企业客户/个人用户):15120086569 (微信同步)
请注意:本站不提供任何免费的技术咨询服务,为了节约时间,下载前 请确认自己会技术
完美源码 » Python 调用 remove bg api 批量去除图片背景
完美源码 » Python 调用 remove bg api 批量去除图片背景