def rbg(client, message): if not RBG_APIKEY: edit(message, get_translation("rbgApiMissing", ['**', 'Remove.BG', '`']), preview=False) return reply = message.reply_to_message if reply and (reply.photo or (reply.document and 'image' in reply.document.mime_typereply.document)): edit(message, f'`{get_translation("processing")}`') else: edit(message, f'`{get_translation("rbgUsage")}`') return IMG_PATH = f'{DOWNLOAD_DIRECTORY}/image.png' if path.exists(IMG_PATH): remove(IMG_PATH) client.download_media(message=reply, file_name=IMG_PATH) edit(message, f'`{get_translation("rbgProcessing")}`') try: remove_bg = RemoveBg(RBG_APIKEY, f'{get_translation("rbgLog")}') remove_bg.remove_background_from_img_file(IMG_PATH) rbg_img = IMG_PATH + '_no_bg.png' reply_doc(reply, rbg_img, caption=f'{get_translation("rbgResult")}') message.delete() except Exception as e: raise e
async def lastfm(client, message): if not REMOVE_BG_API_KEY: await message.edit( "Get the API from [Remove.bg](https://www.remove.bg/b/background-removal-api)", disable_web_page_preview=True, parse_mode="html") await message.edit("Analysing...") replied = message.reply_to_message if (replied and replied.media and (replied.photo or (replied.document and "image" in replied.document.mime_type))): if os.path.exists(IMG_PATH): os.remove(IMG_PATH) await client.download_media(message=replied, file_name=IMG_PATH) await message.edit(f"Removing Background...") try: rmbg = RemoveBg(REMOVE_BG_API_KEY, "removebg_error.log") rmbg.remove_background_from_img_file(IMG_PATH) RBG_IMG_PATH = IMG_PATH + "_no_bg.png" await client.send_document(chat_id=message.chat.id, document=RBG_IMG_PATH, reply_to_message_id=ReplyCheck(message), disable_notification=True) await message.delete() except Exception: await message.edit("Something went wrong!\nCheck your usage.") else: await message.edit("Usage: reply to a photo to remove background!")
def uploadfile01(request): global file global path global api_data if request.method == "POST": try: file = request.FILES.get("file", None) # 接收上传的文件 path = settings.MEDIA_ROOT # 文件存储路径 if not file: return HttpResponse("no files for upload!") destination = open(os.path.join(path, file.name), 'wb+') for chunk in file.chunks(): destination.write(chunk) except: return HttpResponse('上传失败!!!') try: rmbg = RemoveBg(api_data, "error.log") rmbg.remove_background_from_img_file(os.path.join(path, file.name)) except: return HttpResponse('抠图失败') return HttpResponse('上传成功!!!')
async def remove_bg(client, message): if not remove_bg_api: await msg(message, text="Get the API from [Remove.bg](https://www.remove.bg/b/background-removal-api)", disable_web_page_preview=True, parse_mode="html") replied = message.reply_to_message if (replied and replied.media and (replied.photo or (replied.document and "image" in replied.document.mime_type))): if os.path.exists(IMG_PATH): os.remove(IMG_PATH) await client.download_media(message=replied, file_name=IMG_PATH) await msg(message, text="`Removing Background...`") try: rmbg = RemoveBg(remove_bg_api, "rm_bg_error.log") rmbg.remove_background_from_img_file(IMG_PATH) remove_img = IMG_PATH + "_no_bg.png" await client.send_document( chat_id=message.chat.id, document=remove_img, reply_to_message_id=ReplyCheck(message), disable_notification=True) await message.delete() os.remove(remove_img) os.remove(IMG_PATH) except Exception as e: print(e) await msg(message, text="`Something went wrong!`") await sleep(3) await message.delete() else: await msg(message, text="Usage: reply to a photo to remove background!")
def rbg(message): if not RBG_APIKEY: return edit( message, get_translation('rbgApiMissing', ['**', 'Remove.BG', '`']), preview=False, ) reply = message.reply_to_message if reply and (reply.photo or (reply.document and 'image' in reply.document.mime_type)): edit(message, f'`{get_translation("processing")}`') else: edit(message, f'`{get_translation("rbgUsage")}`') return IMG_PATH = f'{DOWNLOAD_DIRECTORY}/image.png' if path.exists(IMG_PATH): remove(IMG_PATH) download_media_wc(reply, IMG_PATH) edit(message, f'`{get_translation("rbgProcessing")}`') try: remove_bg = RemoveBg(RBG_APIKEY, get_translation('rbgLog')) remove_bg.remove_background_from_img_file(IMG_PATH) rbg_img = f'{IMG_PATH}_no_bg.png' reply_doc(reply, rbg_img, caption=get_translation('rbgResult'), delete_after_send=True) message.delete() except Exception as e: return edit(message, get_translation('banError', ['`', '**', e]))
async def remove_bg(client, message): if not REMBG_API_KEY: await message.edit( "Get the API from [Remove.bg](https://www.remove.bg/api)", disable_web_page_preview=True, parse_mode="html") replied = message.reply_to_message if (replied and replied.media and (replied.photo or (replied.document and "image" in replied.document.mime_type))): if os.path.exists("./downloads/img.jpg"): os.remove("./downloads/img.jpg") orig_pic = await client.download_media(message=replied, file_name="./downloads/img.jpg") await message.edit("`Removing Background...`") try: rmbg = RemoveBg(REMBG_API_KEY, "rembg_error.log") rmbg.remove_background_from_img_file(orig_pic) remove_img = orig_pic + "_no_bg.png" new_rembg_file = orig_pic.replace(".jpg", "_rembg_telepyrobot.png") shutil.move(remove_img, new_rembg_file) await client.send_document( chat_id=message.chat.id, document=new_rembg_file, caption="Background removed using @TelePyroBot", reply_to_message_id=ReplyCheck(message), disable_notification=True) await message.delete() os.remove(new_rembg_file) os.remove(orig_pic) except Exception as ef: await message.edit(f"**Error:**\n\n`{ef}") return
def clearimg(file): try: from removebg import RemoveBg rmbg = RemoveBg(readtxtline("data/keys/removeBg.txt"), "error.log") img = rmbg.remove_background_from_img_file(file) except: img = file return img
def download_img(img_url, imgForder): print (img_url) header = {"Authorization": "Bearer " + "fklasjfljasdlkfjlasjflasjfljhasdljflsdjflkjsadljfljsda"} # 设置http header,视情况加需要的条目,这里的token是用来鉴权的一种方式 r = requests.get(img_url, headers=header, stream=True) print(r.status_code) # 返回状态码 path = imgForder + '/' + str(time.time()) + '.png' if r.status_code == 200: open(path, 'wb').write(r.content) # 将内容写入图片 print("done") rmbg = RemoveBg("Ugo6aVuLVgBgnfiv5k6Snj8k", "error.log") # 引号内是你获取的API rmbg.remove_background_from_img_file(path) # 图片地址 return path + "_no_bg.png"
def removebg(picture): global stbg, statusbar statusbar['text'] = 'Removing Background...' statusbar.update() rmbg = RemoveBg("V9TBQtaer***************(your_secret_number)", "error.log") rmbg.remove_background_from_img_file(picture) statusbar['text'] = 'Removed Background Successfully' statusbar.update() time.sleep(1.0) statusbar['text'] = 'Ready' statusbar.update()
def change_bgcolor(file_in, file_out, api_key, color): ''' #必须为png格式 ''' p, s = file_in.split(".") rmbg = RemoveBg(api_key, 'error.log') rmbg.remove_background_from_img_file(file_in) file_no_bg = "{}.{}_no_bg.{}".format(p, s, s) no_bg_image = Image.open(file_no_bg) x, y = no_bg_image.size new_image = Image.new('RGBA', no_bg_image.size, color=color) new_image.paste(no_bg_image, (0, 0, x, y), no_bg_image) new_image.save(file_out)
async def remove_background(message: Message): if not Config.REMOVE_BG_API_KEY: await message.edit( "Get the API from <a href='https://www.remove.bg/b/background-removal-api'>HERE " "</a> & add it to Heroku Config Vars <code>REMOVE_BG_API_KEY</code>", disable_web_page_preview=True, parse_mode="html") return await message.edit("Analysing...") replied = message.reply_to_message if (replied and replied.media and (replied.photo or (replied.document and "image" in replied.document.mime_type))): start_t = datetime.now() c_time = time.time() if os.path.exists(IMG_PATH): os.remove(IMG_PATH) await message.client.download_media(message=replied, file_name=IMG_PATH, progress=progress, progress_args=("Downloading Image", userge, message, c_time)) end_t = datetime.now() m_s = (end_t - start_t).seconds await message.edit( f"Image saved in {m_s} seconds.\nRemoving Background Now...") # Cooking Image try: rmbg = RemoveBg(Config.REMOVE_BG_API_KEY, "removebg_error.log") rmbg.remove_background_from_img_file(IMG_PATH) RBG_IMG_PATH = IMG_PATH + "_no_bg.png" start_t = datetime.now() c_time = time.time() await message.client.send_document( chat_id=message.chat.id, document=RBG_IMG_PATH, disable_notification=True, progress=progress, progress_args=("Uploading", userge, message, c_time, str(RBG_IMG_PATH))) await message.delete() except Exception: await message.edit("Something went wrong!\nCheck your usage quota!" ) return else: await message.edit("Reply to a photo to remove background!", del_in=5)
def uploadfile(request): global file global path if request.method == "POST": file = request.FILES.get("file", None) #接收上传的文件 path = r'D:\wxServer\receive' #创建文件存储路径 if not os.path.exists(path): os.makedirs(path) #创建存储文件的文件夹 if not file: return HttpResponse("no files for upload!") destination = open(os.path.join(path, file.name), 'wb') for chunk in file.chunks(): destination.write(chunk) destination.close() # 第三方抠图 rmbg = RemoveBg('1wXGp8Pz7YQLH85F7HzAqjkV', "error.log") rmbg.remove_background_from_img_file(os.path.join(path, file.name)) return HttpResponse('上传成功!!!')
def change_background(path, color="red", key="cLL287gL9uoGA8P3L1mgwcXU"): rmbg = RemoveBg(key, "error.log") for pic in os.listdir(path): if "_no_bg.png" not in pic: # print(pic) rmbg.remove_background_from_img_file(os.path.join(path, pic)) # print("ok") for pic in os.listdir(path): if "_no_bg.png" in pic: im = Image.open(os.path.join(path, pic)) x, y = im.size # print(x, y) try: p = Image.new('RGB', im.size, color) p.paste(im, (0, 0, x, y), im) p.save(os.path.join(path, pic) + color + '1.jpg') except: pass
async def remove_bg(client, message): if not REMOVE_BG_API: await edit_or_reply( message, text='Invalid API', disable_web_page_preview=True, parse_mode='html', ) replied = message.reply_to_message if ( replied and replied.media and ( replied.photo or (replied.document and 'image' in replied.document.mime_type) ) ): if os.path.exists(IMG_PATH): os.remove(IMG_PATH) await client.download_media(message=replied, file_name=IMG_PATH) try: rmbg = RemoveBg(REMOVE_BG_API, 'rm_bg_error.txt') rmbg.remove_background_from_img_file(IMG_PATH) remove_img = IMG_PATH + '_no_bg.png' await client.send_document( chat_id=message.chat.id, document=remove_img, reply_to_message_id=ReplyCheck(message), disable_notification=True, ) await message.delete() os.remove(remove_img) os.remove(IMG_PATH) except Exception as e: print(e) await edit_or_reply(message, text='`Something went wrong!`') await sleep(3) await message.delete() else: await edit_or_reply( message, text='Usage: reply to a photo to remove background!', )
def oss_sdk(user_id, url_list, org_pic): print('user_id:' + user_id) print(url_list) from removebg import RemoveBg import oss2 rmbg_url_list = [] for source in org_pic: # 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。 auth = oss2.Auth('LTAI4VIH8rP2cjtg', 'uzXZC3TB4egoT5FZe0nYn1BsoqXo5x') # Endpoint以杭州为例,其它Region请按实际情况填写。 bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'deepdraw-test') image_name = 'oss.' + source_obj.split('.')[-1] bucket.get_object_to_file(source_obj, image_name) print('--------------------------rmbg:url' + url) ##模型接口 rmbg = RemoveBg("swJYPyjfZsAcLnZYDqNR4ckM", "error.log") rmbg.remove_background_from_img_file(image_name) # 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。 auth = oss2.Auth('LTAI4VIH8rP2cjtg', 'uzXZC3TB4egoT5FZe0nYn1BsoqXo5x') # Endpoint以杭州为例,其它Region请按实际情况填写。 bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'deepdraw-test') file_name = '/root/deepdraw/untitled/api/no-bg.png' # <yourLocalFile>由本地文件路径加文件名包括后缀组成,例如/users/local/myfile.txt new_url = 'https://deepdraw-test.oss-cn-hangzhou.aliyuncs.com/' + oss_obj_name( user_id, file_name) bucket.put_object_from_file(oss_obj_name(user_id, file_name), file_name) rmbg_url_list.append(new_url) print('new_url:' + new_url) ret = { 'code': 1001, 'msg': '上传成功', } return rmbg_url_list
def koutu(self): rmbg = RemoveBg(api, "error.log") # rmbg = RemoveBg("pMx4gP2zzQcBtkHAJnBXAL3Z", "error.log") # path = '%s\picture' % os.getcwd() # path = 'C:\\Users\\sony\\Desktop\\picture' print('请稍等正在抠图中...', '\n') for num, pic in enumerate(os.listdir(self.path), start=1): rmbg.remove_background_from_img_file("%s/%s" % (self.path, pic)) print('第 %s 张图片抠图完成' % num) print('图片抠图完成', '\n') choice = (input("若要继续抠图请按 y ; 结束请按任意键...")) if choice != 'y': pass else: self.check_path() self.koutu()
async def remove_background(message: Message): if not Config.REMOVE_BG_API_KEY: await message.edit( "Apiyi<a href='https://www.remove.bg/b/background-removal-api'>Buradan Alın" "</a> & Heroku Config Vars'a <code>REMOVE_BG_API_KEY</code> ekleyin", disable_web_page_preview=True, parse_mode="html") return await message.edit("İnceliyorum...") replied = message.reply_to_message if (replied and replied.media and (replied.photo or (replied.document and "image" in replied.document.mime_type))): start_t = datetime.now() if os.path.exists(IMG_PATH): os.remove(IMG_PATH) await message.client.download_media(message=replied, file_name=IMG_PATH, progress=progress, progress_args=(message, "Resim İndiriliyor")) end_t = datetime.now() m_s = (end_t - start_t).seconds await message.edit(f"Resim {m_s} saniye içinde kaydedildi. \n Arka Plan Şimdi Kaldırılıyor ...") # Cooking Image try: rmbg = RemoveBg(Config.REMOVE_BG_API_KEY, "removebg_error.log") rmbg.remove_background_from_img_file(IMG_PATH) rbg_img_path = IMG_PATH + "_no_bg.png" start_t = datetime.now() await message.client.send_document( chat_id=message.chat.id, document=rbg_img_path, disable_notification=True, progress=progress, progress_args=(message, "Yükleniyor", rbg_img_path)) await message.delete() except Exception: await message.edit(" Bir şeyler ters gitti! \nkullanım kotanızı kontrol edin!") return else: await message.edit("Arka planı kaldırmak için bir resmi yanıtlayın!", del_in=5)
def change_bg_color(api_key, file_in_path, color): if type(color) is str: color_list = np.multiply(colors.hex2color(colors.cnames[color]), 255) color_list = map(int, color_list) color_tuple = tuple(color_list) elif type(color) is tuple: color_tuple = color else: print('UNKNOWN COLOR FORMAT.') return -1 first_half_path, extension_name = file_in_path.split('.') remove_background = RemoveBg(api_key, 'error.log') remove_background.remove_background_from_img_file(file_in_path) file_on_background_path = '{}.{}_no_bg.png'.format(first_half_path, extension_name) file_on_background = Image.open(file_on_background_path) size_x, size_y = file_on_background.size file_output = Image.new('RGBA', file_on_background.size, color=color_tuple) file_output.paste(file_on_background, (0, 0, size_x, size_y), file_on_background) file_output_path = '{}_output.png'.format(first_half_path) file_output.save(file_output_path)
def ps_a_img(bg_color_value): file_path = './img/source.jpeg' output_path = './img/source.jpeg_no_bg.png' rmbg = RemoveBg(api_key, "error.log") rmbg.remove_background_from_img_file(file_path) if bg_color_value != (0, 0, 0): print('设置背景颜色') # 给背景加入颜色 # 利用 PIL 库来给 PNG 图片设置背景颜色 im = Image.open(output_path) width, height = im.size try: p = Image.new('RGBA', im.size, bg_color_value) p.paste(im, (0, 0, width, height), im) p.save('./img/output.png') except Exception as e: pass else: print('保持图片透明')
def getTransparentBackgroPicture(self, api_key=None, file=None, url=None): #官网申请的api_key rmbg = RemoveBg(api_key, "error.log") # 去除本地图片背景 if file is not None: rmbg.remove_background_from_img_file(file) #去除网络图片背景色 if url is not None: rmbg.remove_background_from_img_url(img_url=url)
def drawing(fileId, filename): key = str(base64.b64decode(current_app.config.get('API_KEY')), 'utf-8') rmbg = RemoveBg(key, "error.log") for pic in os.listdir(current_app.config.get('UPLOAD_FOLDER')): if pic == filename: tempPic = pic.rsplit('.', 1)[0] url = "%s/%s" % (current_app.config.get('UPLOAD_FOLDER'), filename) rmbg.remove_background_from_img_file(url) # 更新存储量 dbtempKey = dbKey.query.filter_by( Rkey=current_app.config.get('API_KEY')).first() dbtempKey.num = dbtempKey.num - 1 current_app.config['UPGOREMOVE_COUNT'] = current_app.config[ 'UPGOREMOVE_COUNT'] - 1 sqlalchemy.session.commit() # 更换底色 oldImg = url + "_no_bg.png" newImg = "%s/%s" % (current_app.config.get('DOWNLOAD_FOLDER'), tempPic + ".png") try: shutil.move(oldImg, newImg) im = Image.open(newImg) x, y = im.size p = Image.new('RGBA', im.size, (255, 255, 255)) p.paste(im, (0, 0, x, y), im) p.save("%s/%s" % (current_app.config.get('DOWNLOAD_FOLDER'), tempPic + '_white.png')) im = Image.open(newImg) x, y = im.size p = Image.new('RGBA', im.size, (0, 0, 255)) p.paste(im, (0, 0, x, y), im) p.save("%s/%s" % (current_app.config.get('DOWNLOAD_FOLDER'), tempPic + '_blue.png')) im = Image.open(newImg) x, y = im.size p = Image.new('RGBA', im.size, (255, 0, 0)) p.paste(im, (0, 0, x, y), im) p.save("%s/%s" % (current_app.config.get('DOWNLOAD_FOLDER'), tempPic + '_red.png')) with zipfile.ZipFile( "%s/%s" % (current_app.config.get('ZIP_FOLDER'), tempPic + '.zip'), mode="w") as f: for userfile in os.listdir( current_app.config.get('DOWNLOAD_FOLDER')): if userfile.rsplit('.', 1)[1] == 'png': f.write( "%s/%s" % (current_app.config.get('DOWNLOAD_FOLDER'), userfile), userfile) return redirect( url_for('main.complete_file', filename=filename, fileId=fileId)) except FileNotFoundError: for userimg in os.listdir( current_app.config.get('UPLOAD_FOLDER')): if str(fileId) == userimg[0:6]: os.remove( "%s/%s" % (current_app.config.get('UPLOAD_FOLDER'), userimg)) return render_template('upError.html') else: continue return abort(401) return abort(401)
from removebg import RemoveBg import os from PIL import Image rmbg = RemoveBg("RKxxxxxxx", "error.log") #输入获取得API path = '%s/photoss' % os.getcwd() #图片放到同级文件夹photos中 for pic in os.listdir(path): rmbg.remove_background_from_img_file("%s\%s" % (path, pic)) rmbg = RemoveBg("RKxxxxx", "error.log") #输入获取得API rmbg.remove_background_from_img_file(r"C:\Jupyter\baby.n.png")
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from removebg import RemoveBg # https://www.remove.bg/profile#api-key rmbg = RemoveBg("YOUR API-KEY", "error.log") path = input("请输入路径:") for pic in os.listdir(path): file_path = '%s\%s' % (path, pic) rmbg.remove_background_from_img_file(file_path) print("file_path:{}".format(file_path))
import os from removebg import RemoveBg rmbg = RemoveBg("psCaKrA5rUMXJ6A12H8Kirup", "error.log") # 引号内是你获取的API #rmbg.remove_background_from_img_file("/mnt/d/picture/微信图片_20190801200023.jpg") # 图片地址 rmbg.remove_background_from_img_file("/mnt/d/picture/wy.jpg") # 图片地址 #path = "/mnt/d/picture/cqb/anan" #for pic in os.listdir(path): # path_name = os.path.join(path, pic) # rmbg.remove_background_from_img_file(path_name) # 图片地址
from removebg import RemoveBg import os # 参数填入 api key 以及批处理的日志文件位置 rmbg = RemoveBg("u3NcF5HuRAbKow7x9v7BJbfS", "./error.log") # 批处理图片的存放位置 path = os.path.join(os.getcwd(), "pic") for pic in os.listdir(path): rmbg.remove_background_from_img_file(os.path.join(path, pic))
from removebg import RemoveBg import os rmbg = RemoveBg('tQ7dLhmar9UzpXbPJDQa1kRi', 'error.log') rmbg.remove_background_from_img_file(r'C:\Users\myco\desktop\test.png') #path = '%s/picture' % os.getcwd() #for pic in os.listdir(path): # rmbg.remove_background_from_img_file('%s/%s'%(path,pic))
# changebg: 调用PIL添加背景颜色 def changebg(img, color): color_dict = { "A": (255, 0, 0), "B": (67, 142, 219), "C": (255, 255, 255) } # A:red B:bule C:white D:justremovebg im = Image.open(img) x, y = im.size try: p = Image.new('RGBA', im.size, color=color_dict.get(color)) p.paste(im, (0, 0, x, y), im) p.save('{}.png'.format('new' + color)) except: print('changebg err') pass rmbg = RemoveBg("UiwiP9dQj53v693md9UyEyZz", "error.log") # 获取单个照片的抠图 XKMh1J7geGfnGY9CFu9zXV8f rmbg.remove_background_from_img_file("./1.png") # 图片地址 option = 'B' # 蓝色 changebg('1.png_no_bg.png', option) # 批量获取抠图信息 # path = '%s/picture' % os.getcwd() # for pic in os.listdir(path): # rmbg.remove_background_from_img_file("%s/%s" % (path, pic))
# 牛逼的抠图功能 from removebg import RemoveBg import os rmbg = RemoveBg("8snqYXbpSn8EJRntH16A9ZTA", "error.log") # rmbg.remove_background_from_img_file("C:/Users/zhangchg/OneDrive/zcg/文档/个人信息/liuyanning1.jpg") #图片地址 #图片放到程序的同级文件夹 picture 里面 path = '%s/picture' % os.getcwd() for pic in os.listdir(path): rmbg.remove_background_from_img_file("%s\%s" % (path, pic))
# 调用100层 Tiramisu 进行图像分割 # Tiramisu 论文:https://arxiv.org/pdf/1611.09326.pdf # API申请地址:https://www.remove.bg/ from removebg import RemoveBg import os # 引号内是你获取的API rmbg = RemoveBg("DG2WMZrZNnU2oG8fb7mzv6Ja", "error.log") path = os.path.join(os.getcwd(),'images')#图片放到程序的同级文件夹images 里面 for pic in os.listdir(path): #print(pic) rmbg.remove_background_from_img_file(f"{path}\{pic}")
from removebg import RemoveBg import os rmbg = RemoveBg("XnmshQaJeQpt4WbNC6NDzeXb", "error.log") path = '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')