AI-генерация изображений товаров для e-commerce
Генерация product images через AI снижает стоимость фотосессий: удаление фона, замена фона, генерация lifestyle-сцен с товаром, создание вариаций цвета/материала без новой съёмки. Типичная экономия: $50–200 за товар вместо студийной съёмки.
Удаление фона + генерация нового
from rembg import remove, new_session
from PIL import Image
from diffusers import StableDiffusionXLInpaintPipeline
import torch
import io
import numpy as np
class ProductImageGenerator:
def __init__(self):
self.bg_remover = new_session("isnet-general-use")
self.pipe = StableDiffusionXLInpaintPipeline.from_pretrained(
"diffusers/stable-diffusion-xl-1.0-inpainting-0.1",
torch_dtype=torch.float16
).to("cuda")
def remove_background(self, product_image: bytes) -> tuple[bytes, bytes]:
"""Возвращаем (изображение без фона, маска фона)"""
result = remove(product_image, session=self.bg_remover)
img_rgba = Image.open(io.BytesIO(result)).convert("RGBA")
# Маска: белый = фон (для инпейнтинга), чёрный = товар
r, g, b, a = img_rgba.split()
mask = Image.fromarray(255 - np.array(a)) # инвертируем alpha
img_rgb = Image.new("RGB", img_rgba.size, (255, 255, 255))
img_rgb.paste(img_rgba, mask=img_rgba.split()[3])
img_buf = io.BytesIO()
img_rgb.save(img_buf, format="PNG")
mask_buf = io.BytesIO()
mask.save(mask_buf, format="PNG")
return img_buf.getvalue(), mask_buf.getvalue()
def place_on_background(
self,
product_image: bytes,
background_prompt: str,
steps: int = 30
) -> bytes:
product_bytes, mask_bytes = self.remove_background(product_image)
result = self.pipe(
prompt=background_prompt,
image=Image.open(io.BytesIO(product_bytes)),
mask_image=Image.open(io.BytesIO(mask_bytes)),
num_inference_steps=steps,
guidance_scale=9.0,
strength=0.99
).images[0]
buf = io.BytesIO()
result.save(buf, format="PNG")
return buf.getvalue()
Генерация lifestyle-сцен
PRODUCT_SCENE_PROMPTS = {
"electronics": [
"modern minimalist desk setup, natural light, laptop nearby, bokeh background",
"cozy home office, wooden desk, plants, warm ambient lighting",
],
"clothing": [
"fashion editorial, urban street style, natural daylight",
"lifestyle shot, outdoor park, casual summer day",
],
"food": [
"rustic wooden table, natural light, herbs nearby, shallow depth of field",
"modern kitchen counter, marble surface, fresh ingredients",
],
"cosmetics": [
"marble surface with flowers, soft pink background, luxury aesthetic",
"bathroom counter, morning light, clean minimalist style",
]
}
async def generate_product_scenes(
product_image: bytes,
product_category: str,
num_variants: int = 4
) -> list[bytes]:
prompts = PRODUCT_SCENE_PROMPTS.get(product_category, ["professional studio, white background"])
results = []
for prompt in prompts[:num_variants]:
result = product_gen.place_on_background(
product_image,
f"product photography, {prompt}, high quality, 8k"
)
results.append(result)
return results
Генерация цветовых вариаций
async def generate_color_variants(
product_image: bytes,
colors: list[str],
product_mask: bytes # маска только товара
) -> dict[str, bytes]:
"""Меняем цвет товара через инпейнтинг с маской"""
results = {}
for color in colors:
from diffusers import StableDiffusionXLInpaintPipeline
result = pipe(
prompt=f"same product shape, {color} color, same material texture, product photography",
image=Image.open(io.BytesIO(product_image)),
mask_image=Image.open(io.BytesIO(product_mask)),
strength=0.6, # Слабый strength сохраняет форму
guidance_scale=10.0
).images[0]
buf = io.BytesIO()
result.save(buf, format="PNG")
results[color] = buf.getvalue()
return results
Интеграция с маркетплейсами
class MarketplaceImageOptimizer:
REQUIREMENTS = {
"wildberries": {"size": (1000, 1000), "format": "jpg", "bg": "white"},
"ozon": {"size": (1000, 1000), "format": "jpg", "bg": "white"},
"amazon": {"size": (2000, 2000), "format": "jpg", "bg": "white", "padding": 0.85},
"shopify": {"size": (2048, 2048), "format": "webp", "bg": "any"},
}
def optimize_for_marketplace(self, image: bytes, marketplace: str) -> bytes:
req = self.REQUIREMENTS[marketplace]
img = Image.open(io.BytesIO(image)).convert("RGB")
# Resize с сохранением пропорций + белый фон
img.thumbnail(req["size"], Image.LANCZOS)
background = Image.new("RGB", req["size"], (255, 255, 255))
offset = ((req["size"][0] - img.size[0]) // 2,
(req["size"][1] - img.size[1]) // 2)
background.paste(img, offset)
buf = io.BytesIO()
background.save(buf, format=req["format"].upper(), quality=95)
return buf.getvalue()
Сроки: сервис удаления фона + AI-фон для одного маркетплейса — 1–2 недели. Полноценная платформа с вариациями цвета и batch-обработкой каталога — 4–6 недель.







