Remove Image Backgrounds in Google Colab or Jupyter Without a GPU (API Notebook)
Colab is where most people first try background removal in Python, and where most of them hit the same walls: the free runtime has no GPU when you need one, the model download eats the session, and results vanish when the runtime resets. Calling an API from the notebook sidesteps all three — no model, no GPU, results written straight to Drive. This is the notebook, cell by cell, with the key kept out of the notebook file.
In this guide
Cell 1: the key, kept out of the notebook
In Colab, open the Secrets panel (the key icon in the left sidebar), add BGCLEAR_API_KEY with your key from the dashboard, and enable notebook access. Secrets are not saved into the .ipynb, so the notebook can be shared safely. Local Jupyter: use an environment variable instead.
import os, requests
try:
from google.colab import userdata # Colab
KEY = userdata.get("BGCLEAR_API_KEY")
except ImportError:
KEY = os.environ["BGCLEAR_API_KEY"] # local Jupyter
API = "https://www.bgclear.ai/api/v1/remove"
HEADERS = {"Authorization": f"Bearer {KEY}"}
def remove_background(data: bytes, size="preview", fmt="png", bg_color=None) -> bytes:
form = {"size": size, "format": fmt}
if bg_color: form["bg_color"] = bg_color
r = requests.post(API, headers=HEADERS, files={"image_file": ("image.jpg", data)}, data=form, timeout=90)
if r.status_code != 200:
raise RuntimeError(r.json()["error"]["message"])
print("credits remaining:", r.headers.get("X-Credits-Remaining"))
return r.contentsize="preview" (up to 800 px) is free and unlimited — ideal while you iterate; switch to "full" (one credit) or "auto" for final outputs.
Cell 2: upload, process, show inline
from google.colab import files # local Jupyter: use ipywidgets FileUpload or a path
from IPython.display import Image, display
uploaded = files.upload() # opens the file picker
for name, data in uploaded.items():
png = remove_background(data, size="preview")
display(Image(data=png, width=400))
with open(name.rsplit(".", 1)[0] + "-cutout.png", "wb") as f:
f.write(png)The checkerboard you would see in an editor is not shown by display — transparent areas render on white in the notebook, which is fine for checking edges. For a white-background product image, pass bg_color="ffffff", fmt="jpg".
Cell 3: batch a Google Drive folder
Mount Drive, walk a folder, skip files already done, pace under the 60-requests-a-minute limit, and use each file's hash as an Idempotency-Key so a rerun after a runtime reset never charges twice.
import hashlib, pathlib, time
from google.colab import drive
drive.mount("/content/drive")
src = pathlib.Path("/content/drive/MyDrive/products/raw")
dst = pathlib.Path("/content/drive/MyDrive/products/cutouts"); dst.mkdir(parents=True, exist_ok=True)
for path in sorted(src.glob("*.jp*g")) + sorted(src.glob("*.png")):
out = dst / (path.stem + ".png")
if out.exists():
continue # resumable
data = path.read_bytes()
r = requests.post(API, headers={**HEADERS, "Idempotency-Key": hashlib.sha256(data).hexdigest()},
files={"image_file": (path.name, data)}, data={"size": "full", "format": "png"}, timeout=90)
if r.status_code == 429:
time.sleep(int(r.headers.get("X-RateLimit-Reset", "5"))); continue
if r.status_code == 402:
raise SystemExit("Out of credits — https://www.bgclear.ai/api-pricing/")
if r.status_code != 200:
print(path.name, "->", r.json()["error"]["message"]); continue
out.write_bytes(r.content)
print(out.name, "| credits left:", r.headers.get("X-Credits-Remaining"))
time.sleep(1.1) # ≤60/minResults land in Drive as they finish, so a Colab timeout mid-run loses nothing — rerun the cell and it continues.
Why not run a model in the notebook?
You can — rembg installs in Colab — but the free tier's CPU runtime takes several seconds per image, the model download repeats on every fresh runtime, and GPU availability on the free tier is not guaranteed. The rembg comparison goes through the trade-offs. For a notebook that has to work every time for a class, a client or a colleague, an API call is the boring choice: previews free, full resolution one credit — $9 for 100, $39 for 500, $129 for 2,000, no subscription (pricing). Images above 4 megapixels go through the async jobs endpoint; the Python tutorial has that cell too.
Frequently asked questions
Does this work on the free Colab tier?
Yes — no GPU is needed; the notebook only makes HTTP calls. It also runs in local Jupyter, VS Code notebooks and Kaggle (with internet enabled).
Is my API key saved in the notebook?
Not if you use Colab Secrets (userdata) or an environment variable as shown. Never paste the key into a cell you might share.
How many images can I process for free?
Unlimited at preview size (≤800 px). Full-resolution images cost one credit each; the first key includes 10.
Can I save results back to Drive automatically?
Yes — cell 3 mounts Drive and writes each cutout as it completes, making the batch resumable after a runtime reset.