import openai
from PIL import Image, ImageDraw
import requests
from io import BytesIO
import os
{/* Configuration */}
openai.api_base = "https://api.yelinai.com/v1"
openai.api_key = "your-api-key"
class ImageEditor:
def __init__(self):
self.api_key = openai.api_key
def create_mask_for_object_removal(self, image_path, bbox):
"""Create mask for object removal"""
img = Image.open(image_path)
mask = Image.new('RGBA', img.size, (0, 0, 0, 255))
draw = ImageDraw.Draw(mask)
draw.rectangle(bbox, fill=(0, 0, 0, 0))
return mask
def edit_image(self, image_path, mask, prompt):
"""Execute image editing"""
try:
{/* Prepare files */}
with open(image_path, 'rb') as img_file:
{/* Save mask to temporary file */}
mask_path = 'temp_mask.png'
mask.save(mask_path)
with open(mask_path, 'rb') as mask_file:
{/* Call API */}
response = openai.Image.create_edit(
image=img_file,
mask=mask_file,
prompt=prompt,
n=1,
size="1024x1024"
)
{/* Clean up temporary file */}
os.remove(mask_path)
return response['data'][0]['url']
except Exception as e:
print(f"Edit failed: {e}")
return None
def download_result(self, url, output_path):
"""Download edited image"""
response = requests.get(url)
img = Image.open(BytesIO(response.content))
img.save(output_path)
print(f"Saved to: {output_path}")
{/* Usage example */}
editor = ImageEditor()
{/* 1. Object removal example */}
image_path = "street_photo.png"
{/* Assume object to remove is at position (300, 200) to (500, 400) */}
bbox = (300, 200, 500, 400)
mask = editor.create_mask_for_object_removal(image_path, bbox)
{/* Edit image, fill removed area with background */}
result_url = editor.edit_image(
image_path,
mask,
"empty street background, seamlessly blended"
)
if result_url:
editor.download_result(result_url, "edited_street.png")