Code Monkey home page Code Monkey logo

remove-bg's Introduction

remove-bg

A Python API wrapper for removing backgrounds from picture using remove.bg's API.

License

This code is licensed under the MIT License. See here for more details.

Installation

pip install removebg

Usage

remove_background_from_img_file

Removes the background given an image file.

Parameter Default Value Description
img_file_path req. param path to the source image file
size 'regular' size of the output image ('auto' = highest available resolution, 'preview'
type 'auto' foreground object ('auto' = autodetect, 'person', 'product', 'car')
type_level 'none' classification level of the foreground object ('none' = no classification, '1' = coarse classification (e.g. 'car'), '2' = specific classification (e.g. 'car_interior'), 'latest' = latest classification)
format 'auto' image format ('auto' = autodetect, 'png', 'jpg', 'zip')
roi '0 0 100% 100%' region of interest, where to look for foreground object (x1, y1, x2, y2) in px or relative (%)
crop None px or relative, single val = all sides, two vals = top/bottom, left/right, four vals = top, right, bottom, left
scale 'original' image scale relative to the total image size
position 'original' 'center', 'original', single val = horizontal and vertical, two vals = horizontal, vertical
channels 'rgba' request the finalized image ('rgba') or an alpha mask ('alpha')
shadow False whether to add an artificial shadow (some types aren't supported)
semitransparency True semitransparency for windows or glass objects (some types aren't supported)
bg None background (None = no background, path, url, color hex code (e.g. '81d4fa', 'fff'), color name (e.g. 'green'))
bg_type None background type (None = no background, 'path', 'url', 'color')
new_file_name 'no-bg.png' file name of the result image

Code Example:

from removebg import RemoveBg

rmbg = RemoveBg("YOUR-API-KEY", "error.log")
rmbg.remove_background_from_img_file("joker.jpg")

remove_background_from_img_url

Removes the background given an image URL.

Parameter Default Value Description
img_url req. param URL to the source image
size 'regular' size of the output image ('auto' = highest available resolution, 'preview'
type 'auto' foreground object ('auto' = autodetect, 'person', 'product', 'car')
type_level 'none' classification level of the foreground object ('none' = no classification, '1' = coarse classification (e.g. 'car'), '2' = specific classification (e.g. 'car_interior'), 'latest' = latest classification)
format 'auto' image format ('auto' = autodetect, 'png', 'jpg', 'zip')
roi '0 0 100% 100%' region of interest, where to look for foreground object (x1, y1, x2, y2) in px or relative (%)
crop None px or relative, single val = all sides, two vals = top/bottom, left/right, four vals = top, right, bottom, left
scale 'original' image scale relative to the total image size
position 'original' 'center', 'original', single val = horizontal and vertical, two vals = horizontal, vertical
channels 'rgba' request the finalized image ('rgba') or an alpha mask ('alpha')
shadow False whether to add an artificial shadow (some types aren't supported)
semitransparency True semitransparency for windows or glass objects (some types aren't supported)
bg None background (None = no background, path, url, color hex code (e.g. '81d4fa', 'fff'), color name (e.g. 'green'))
bg_type None background type (None = no background, 'path', 'url', 'color')
new_file_name 'no-bg.png' file name of the result image

Code Example:

from removebg import RemoveBg

rmbg = RemoveBg("YOUR-API-KEY", "error.log")
rmbg.remove_background_from_img_url("http://www.example.com/some_image.jpg")

remove_background_from_base64_img

Removes the background given a base64 image string.

Parameter Default Value Description
base64_img req. param base64 image string
size 'regular' size of the output image ('auto' = highest available resolution, 'preview'
type 'auto' foreground object ('auto' = autodetect, 'person', 'product', 'car')
type_level 'none' classification level of the foreground object ('none' = no classification, '1' = coarse classification (e.g. 'car'), '2' = specific classification (e.g. 'car_interior'), 'latest' = latest classification)
format 'auto' image format ('auto' = autodetect, 'png', 'jpg', 'zip')
roi '0 0 100% 100%' region of interest, where to look for foreground object (x1, y1, x2, y2) in px or relative (%)
crop None px or relative, single val = all sides, two vals = top/bottom, left/right, four vals = top, right, bottom, left
scale 'original' image scale relative to the total image size
position 'original' 'center', 'original', single val = horizontal and vertical, two vals = horizontal, vertical
channels 'rgba' request the finalized image ('rgba') or an alpha mask ('alpha')
shadow False whether to add an artificial shadow (some types aren't supported)
semitransparency True semitransparency for windows or glass objects (some types aren't supported)
bg None background (None = no background, path, url, color hex code (e.g. '81d4fa', 'fff'), color name (e.g. 'green'))
bg_type None background type (None = no background, 'path', 'url', 'color')
new_file_name 'no-bg.png' file name of the result image

Code Example:

from removebg import RemoveBg
import base64

rmbg = RemoveBg("YOUR-API-KEY", "error.log")
with open("joker.jpg", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())
rmbg.remove_background_from_base64_img(encoded_string)

Contributions

Contributions and feature requests are always welcome.

remove-bg's People

Contributors

andrewvaliente avatar brilam avatar grbavacigla avatar muzk avatar theunkn0wn1 avatar weathercold avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

remove-bg's Issues

Format and other options

Hi, i am looking for some features that API provides, but this library doesn't. Would you merge my pull request? Thanks.

ModuleNotFoundError: No module named 'websockets.datastructures'

when running rembg s cmd it throws this error
also I have installed websocket

Traceback (most recent call last):
File "C:\Python310\lib\runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Python310\lib\runpy.py", line 86, in run_code
exec(code, run_globals)
File "C:\Python310\Scripts\rembg.exe_main
.py", line 7, in
File "C:\Python310\lib\site-packages\click\core.py", line 1130, in call
return self.main(*args, **kwargs)
File "C:\Python310\lib\site-packages\click\core.py", line 1055, in main
rv = self.invoke(ctx)
File "C:\Python310\lib\site-packages\click\core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Python310\lib\site-packages\click\core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Python310\lib\site-packages\click\core.py", line 760, in invoke
return _callback(*args, **kwargs)
File "C:\Python310\lib\site-packages\rembg\cli.py", line 419, in s
uvicorn.run(app, host="0.0.0.0", port=port, log_level=log_level)
File "C:\Python310\lib\site-packages\uvicorn\main.py", line 576, in run
server.run()
File "C:\Python310\lib\site-packages\uvicorn\server.py", line 60, in run
return asyncio.run(self.serve(sockets=sockets))
File "C:\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "C:\Python310\lib\site-packages\uvicorn\server.py", line 67, in serve
config.load()
File "C:\Python310\lib\site-packages\uvicorn\config.py", line 471, in load
ws_protocol_class = import_from_string(WS_PROTOCOLS[self.ws])
File "C:\Python310\lib\site-packages\uvicorn\importer.py", line 24, in import_from_string
raise exc from None
File "C:\Python310\lib\site-packages\uvicorn\importer.py", line 21, in import_from_string
module = importlib.import_module(module_str)
File "C:\Python310\lib\importlib_init
.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1050, in _gcd_import
File "", line 1027, in _find_and_load
File "", line 1006, in _find_and_load_unlocked
File "", line 688, in _load_unlocked
File "", line 883, in exec_module
File "", line 241, in _call_with_frames_removed
File "C:\Python310\lib\site-packages\uvicorn\protocols\websockets\auto.py", line 17, in
from uvicorn.protocols.websockets.websockets_impl import WebSocketProtocol
File "C:\Python310\lib\site-packages\uvicorn\protocols\websockets\websockets_impl.py", line 9, in
from websockets.datastructures import Headers
ModuleNotFoundError: No module named 'websockets.datastructures'

No module named removebg even if installed.

File "C:\Theodore\programFiles\Python27\Lib\site-packages\removebg_init_.py", line 1, in
from removebg.removebg import RemoveBg
ImportError: No module named removebg

【Solution】
change the package path in init.py can correct it.
from removebg.removebg import RemoveBg =>
from .removebg import RemoveBg

Multiple API-Key

Hi, I'm trying to use the removebg package as part of my camera capture python script. My question is if I have to keep requesting new API Key everytime I run the script? Thanks

The picture cannot be opened after setting the color

from removebg import RemoveBg
rmbg = RemoveBg("CYoE87mDaDA9jcb3nKSHG5c7", "error.log") # 引号内是你获取的API
rmbg.remove_background_from_img_file("bus.jpg",bg_color="green") #图片地址

The code can be executed, but the generated picture cannot be opened, how to solve it, thank you!

size param

What's the difference between auto, full, and 4k of size param?

file name

sir, can you give me an example of new_file_name

Multi-imgs error

Add a func in removebg.py:

    def remove_background_and_save_img(self, img_file_path,save_path, size="regular", bg_color=None):
        """
        Removes the background given an image file and outputs the file as the original file name with "no_bg.png"
        appended to it.
        :param img_file_path: the path to the image file
        :param size: the size of the output image (regular = 0.25 MP, hd = 4 MP, 4k = up to 10 MP)
        """
        # Open image file to send information post request and send the post request
        img_file = open(img_file_path, 'rb')
        response = requests.post(
            API_ENDPOINT,
            files={'image_file': img_file},
            data={
                'size': size,
                'bg_color': bg_color
            },
            headers={'X-Api-Key': self.__api_key})
        response.raise_for_status()
        # print(f'input_file:{img_file.name}')
        st1=img_file.name.split('.')[0]
        st2=st1.split("/")[-1]
        # print(f'st2:{st2}')
        save_path=os.path.join(save_path,st2)
        print('save bg removed',save_path)
        self.__output_file__(response,  save_path + "_no_bg.png")

firstly, works well. After weekends,it report:" requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://api.remove.bg/v1.0/removebg "

Could u pls tell why

bug

It does't make a img file in my Linux

Zip output format

Does this library support zip format as the image output? Let me know so that i can contribute something

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.