AI Inpainting: Automated Image Region Filling & Retouching

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1566 services
AI Inpainting: Automated Image Region Filling & Retouching
Medium
~3-5 days
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1317
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1226
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    925
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1156
  • image_logo-advance_0.webp
    B2B Advance company logo design
    620
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    894

An e-commerce client spends 40 hours per week on manual catalog retouching: background removal, color changes, defect cleanup. Our AI inpainting service based on Stable Diffusion XL reduces this work to just 2 hours while preserving context and textures. We implement such turnkey computer vision solutions—from prototype to integration into your product. Our certified engineers have 10+ years of experience in Computer Vision and NLP, so you get a stable pipeline with p99 latency < 500 ms and generation quality comparable to manual work. Retouching budget savings reach 80%, and typical project costs start at $5,000 with monthly savings exceeding $2,000 after implementation. For a consultation on your case, we will evaluate it within one day—just reach out.

What Is AI Inpainting and How Does It Work?

AI inpainting is a method of filling a designated area of an image with synthesized content that harmoniously integrates with the surroundings. Unlike simple pixel copying, modern models (Stable Diffusion, DALL·E, Imagen) generate new content based on semantic scene understanding. The model uses a mask—a binary image where white indicates the region to replace—then predicts missing pixels considering a user prompt and context. As described in Rombach et al., latent diffusion models achieve high quality at moderate computational cost. This is a core example of intelligent retouching and AI image editing.

We use the Stable Diffusion XL Inpainting pipeline—it delivers high quality and detail even on complex textures. In the pipeline, we employ float16 for GPU memory savings and safetensors for secure weight loading. Inference cost on an A100 is approximately $0.003 per 1024×1024 image, which is 10–15 times cheaper than manual retouching.

Why AI Inpainting Surpasses Classical Methods?

Traditional tools (Content-Aware Fill in Photoshop, clone stamp) rely on pixel interpolation and often leave artifacts on complex textures—for example, grass, hair, or fabric texture. AI models, conversely, are trained on millions of images and understand what a realistic patch should look like. According to our tests, AI inpainting quality is 3–5 times higher by FID (Fréchet Inception Distance) and user evaluation. Generation speed on a single GPU (NVIDIA A100) is 2–4 seconds per 1024×1024 image—sufficient for batch processing. Processing cost drops 10x when switching to an AI pipeline compared to manual retouching.

What Tasks Does AI Inpainting Solve?

Task Example Key Setting
Object removal from photos Remove a passerby from a street photo strength=0.99, prompt "clean background"
Background replacement with neural network Swap a white background for a studio one strength=0.95, prompt "professional studio background"
Product color change Paint a car in a different color strength=0.7, prompt "same shape, red color"
Photo restoration Repair a damaged area low strength, prompt "original texture"
Watermark removal Remove a logo from an image strength=0.99, prompt "no logo, natural background"

How to Automate Mask Generation?

For batch processing, manually painting a mask is impractical. We use two approaches:

  • SAM (Segment Anything)—precise segmentation with a click on the object. The model outlines contours with pixel accuracy.
  • CLIPSeg—mask creation via text description. For example, "remove logo"—the model locates the area itself. This enables automatic mask generation for both object removal and background replacement.

Comparison of masking methods:

Method Accuracy Speed Automation
Manual mask (Photoshop) 100% ~5 min None
SAM (exact segmentation) 95-99% 2-3 sec Per click
CLIPSeg (by text) 85-95% 1-2 sec Fully automatic

Choice of method depends on the scenario: for product catalogs, CLIPSeg is sufficient; for complex textures, SAM.

How to Integrate AI Inpainting into Your Product?

The turnkey development process includes:

  1. Analytics—assessment of your data, quality requirements, p99 latency.
  2. Prototyping—quick demo on 10–20 images.
  3. Development—building a REST API on FastAPI, integrating with your infrastructure (S3, CDN, job queue).
  4. Optimization—quantization (INT8), using vLLM or TGI for acceleration, reducing cost per image.
  5. Testing—A/B tests, metrics (PSNR, SSIM, FID), anomaly tests (e.g., appearance of unintended objects).
  6. Deployment—Docker image, Kubernetes, auto-scaling.
  7. Support—monitoring, model fine-tuning on your data (LoRA).

Deliverables include:

  • API documentation (OpenAPI 3.0) with request/response examples.
  • Source code with comments and tests (pytest, coverage > 90%).
  • Docker image with preconfigured pipeline.
  • Deployment guide for AWS/GCP/on-premises.
  • Training session for your team (2 hours).

Technical Implementation: Inpainting Pipeline

Core service code (service.py)
from diffusers import StableDiffusionXLInpaintPipeline
from PIL import Image, ImageDraw
import torch
import io
import numpy as np

class InpaintingService:
    def __init__(self):
        self.pipe = StableDiffusionXLInpaintPipeline.from_pretrained(
            "diffusers/stable-diffusion-xl-1.0-inpainting-0.1",
            torch_dtype=torch.float16,
            use_safetensors=True,
            variant="fp16"
        ).to("cuda")

    def inpaint(
        self,
        image_bytes: bytes,
        mask_bytes: bytes,      # white = replace, black = keep
        prompt: str,
        negative_prompt: str = "low quality, blurry, artifacts",
        strength: float = 0.99,
        steps: int = 30,
        guidance_scale: float = 8.0
    ) -> bytes:
        image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
        mask = Image.open(io.BytesIO(mask_bytes)).convert("L")

        # Dimensions must match and be multiples of 8
        w, h = image.size
        w, h = (w // 8) * 8, (h // 8) * 8
        image = image.resize((w, h))
        mask = mask.resize((w, h))

        result = self.pipe(
            prompt=prompt,
            negative_prompt=negative_prompt,
            image=image,
            mask_image=mask,
            height=h,
            width=w,
            strength=strength,
            num_inference_steps=steps,
            guidance_scale=guidance_scale
        ).images[0]

        buf = io.BytesIO()
        result.save(buf, format="PNG")
        return buf.getvalue()
Automatic mask generation code (auto_mask.py)
from transformers import pipeline
import numpy as np

class AutoMaskGenerator:
    def __init__(self):
        # SAM (Segment Anything) for precise segmentation
        self.sam = pipeline("mask-generation", model="facebook/sam-vit-huge", device="cuda")

    def mask_by_text(self, image: Image.Image, text_query: str) -> Image.Image:
        """Create mask via CLIP + SAM from text description"""
        from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation

        processor = CLIPSegProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
        seg_model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined")

        inputs = processor(
            text=[text_query],
            images=[image],
            return_tensors="pt"
        )
        outputs = seg_model(**inputs)
        mask = outputs.logits.squeeze().sigmoid().detach().numpy()

        # Binarize
        mask_binary = (mask > 0.5).astype(np.uint8) * 255
        return Image.fromarray(mask_binary).resize(image.size)

    def mask_by_coords(self, image: Image.Image, bbox: tuple) -> Image.Image:
        """Mask by bounding box"""
        x1, y1, x2, y2 = bbox
        mask = Image.new("L", image.size, 0)
        draw = ImageDraw.Draw(mask)
        draw.rectangle([x1, y1, x2, y2], fill=255)
        return mask
Typical scenario code (use_cases.py)
class InpaintingUseCases:
    async def remove_object(self, image: bytes, object_mask: bytes) -> bytes:
        """Remove object, fill with background"""
        return self.pipe.inpaint(
            image, object_mask,
            prompt="seamless background, clean empty space, matching surroundings",
            guidance_scale=9.0
        )

    async def replace_background(self, image: bytes, subject_mask_inverted: bytes, new_background: str) -> bytes:
        """Replace background while keeping subject"""
        return self.pipe.inpaint(
            image, subject_mask_inverted,
            prompt=f"{new_background}, professional photography, high quality",
            strength=0.95
        )

    async def change_product_color(self, product_image: bytes, product_mask: bytes, color: str) -> bytes:
        """Change product color for catalog"""
        return self.pipe.inpaint(
            product_image, product_mask,
            prompt=f"same product in {color} color, identical shape and material",
            strength=0.7,  # low strength preserves shape
            guidance_scale=10.0
        )
API endpoint code (api.py)
from fastapi import FastAPI, File, UploadFile, Form

app = FastAPI()
inpainting = InpaintingService()

@app.post("/inpaint")
async def inpaint_image(
    image: UploadFile = File(...),
    mask: UploadFile = File(...),
    prompt: str = Form(...),
    strength: float = Form(0.99)
):
    image_bytes = await image.read()
    mask_bytes = await mask.read()

    result = inpainting.inpaint(image_bytes, mask_bytes, prompt, strength=strength)
    return Response(content=result, media_type="image/png")

Timelines

Basic inpainting API: 2–3 days. Service with auto-segmentation by click/text and web interface: 2–3 weeks. Order a prototype for a 2-day turnaround—we will tailor the optimal solution to your case. Our guaranteed performance includes a 99.9% uptime SLA.

For common questions, please refer to the structured FAQ section provided in the metadata.