Media Gen SolutionSupported image utilities

Background Removal

Remove parts of the image considered to be background.

Background removal takes an existing image you provide and removes those parts of the image considered to be “background.”

Image with background

Background removed

Example Code of removing background from an image:

Python
1import requests
2import json
3import os
4import base64
5import time
6import io
7import PIL.Image
8from typing import Optional, Tuple
9
10
11def _process_test(url):
12
13 image = PIL.Image.open("headphones1.jpeg")
14
15 # Create a BytesIO buffer to hold the image data
16 image_buffer = io.BytesIO()
17 image.save(image_buffer, format='JPEG')
18 image_bytes = image_buffer.getvalue()
19 encoded_image = base64.b64encode(image_bytes).decode('utf-8')
20
21 OCTOAI_TOKEN = os.environ.get("OCTOAI_TOKEN")
22
23 payload = {
24 "init_image": encoded_image,
25 "bgcolor":(255, 255, 255, 0)
26 }
27 headers = {
28 "Authorization": f"Bearer {OCTOAI_TOKEN}",
29 "Content-Type": "application/json",
30 "X-OctoAI-Queue-Dispatch": "true"
31 }
32
33 response = requests.post(url, headers=headers, json=payload)
34
35 if response.status_code != 200:
36 print(response.text)
37 print(response.json())
38
39 img_info = response.json()["image_b64"]
40
41 img_bytes = base64.b64decode(img_info)
42 img = PIL.Image.open(io.BytesIO(img_bytes))
43
44 if img.mode == 'RGBA':
45 img = img.convert('RGB')
46
47 img.save("result_image.png")
48
49if __name__ == "__main__":
50 _process_test("https://image.octoai.run/background-removal")