Image Inpainting for Watermark Removal: Evaluation and Production Practice
Image inpainting is an ill-posed problem: many completions can look plausible for the same mask. This article explains the main technical routes, how to judge naturalness and stability beyond pixel metrics, why mask design sets the quality ceiling, and a coarse-to-fine inference and post-processing pipeline. It also covers hard backgrounds, export quality, batch architecture, failure modes, compliance, and a short selection checklist.
1. Define the problem: what image inpainting is solving
Image inpainting is straightforward to state. Given an original image I and a mask M (regions to fill marked as 1), produce a completed image I' that is consistent with the known surroundings in semantics, texture, lighting, and geometry.
The hard part is that this is a classic ill-posed inverse problem: under the same mask there are infinitely many “reasonable” completions. In practice there is no single correct answer—only a solution whose prior is stronger and whose constraints fit the scene better. That is why different tools can look very different on the same image. The gap is not raw compute; it is prior quality and constraint design.
Mainstream approaches fall into three groups:
- Texture synthesis / patch matching: copy samples from nearby regions. Fast and stable on regular gradients such as sky or walls, but weak on semantic structure such as faces or text.
- Encoder–decoder with attention or adversarial training: one forward pass, low latency, and realistic texture. Risks include low-frequency color shift and structural drift.
- Diffusion generation: the strongest prior and the most coherent structure, at the cost of iterative inference and stochastic outputs. Fix the random seed if results must be reproducible.
2. Turn “looks good” into measurable evaluation dimensions
Three common impressions map to three measurable families:
- Naturalness of the fill: focus on boundary consistency. Hair, sky gradients, and metal highlights are where a smeared look shows up first. The cause is missing high-frequency detail plus poor edge feathering. Crop and inspect at 200% and score with a double-blind mean opinion score (MOS).
- Stability on complex backgrounds: build a hard set of “high-texture background + small mask” samples and check for broken structure or wrong texture direction.
- Export fidelity: sample the preview and the final file separately, and compare edge sharpness and banding.
Use objective metrics carefully. PSNR and SSIM reward pixel-level agreement and penalize completions that are plausible but not identical to a reference, so they barely separate generative inpainting results. Perceptual similarity learned from human judgments (metrics in the LPIPS family) is closer to what people see. Use both: perceptual metrics for regression monitoring, MOS for choosing a method.
3. The mask: underestimated, and it sets the ceiling
In practice, more than half of “unnatural” repairs come from a mask that is too tight, not from the model. The mask must cover anti-aliased edges and compression ringing. Otherwise leftover artifacts are treated as real texture and extrapolated.
def build_mask(width, height, strokes, dilate_px=5):"""strokes: user strokes or polygon list; returns a single-channel mask normalized to [0, 1]"""mask = rasterize(strokes, width, height) # binary 0/255mask = morph_dilate(mask, radius=dilate_px) # morphological dilation to cover the degraded edge bandmask = gaussian_blur(mask, sigma=1.0) # soft edge to reduce blend seamsreturn mask.astype("float32") / 255.0
Practical ranges: 3–5 px for ordinary watermarks; 7–9 px when text strokes or high-contrast edges are involved. As the masked area grows, use a smaller dilation ratio so usable context is not swallowed.
4. Inference and post-processing pipeline
“Select a region, get a result” is only the minimum loop. Stable quality depends on post-processing:
def inpaint(image, mask, model, seed=42):coarse = model.segment_completion(image, mask) # structure / low frequency firstfine = model.refine(image, mask, coarse, seed=seed) # detail generation with a fixed seedfused = poisson_blend(image, fine, mask) # Poisson blend to unify gradientsfused = color_match(fused, image, mask) # mean/variance alignment to remove color shiftreturn clip_and_dither(fused) # dithering to suppress banding
Three points matter: coarse-to-fine to avoid structural collapse; gradient-domain blending to remove rectangular seams; color alignment to correct the gray or cool cast common in generative models.
5. Why complex backgrounds are unstable, and how to recover
- Multi-scale strategy: lock structure at low resolution, then upsample step by step to add detail. Long-range consistency is clearly better than one-shot inference on the full image.
- Structural conditioning: feed edge maps or depth maps as extra conditions to cut wrong texture direction.
- Candidate selection: generate 3–5 seeds for the same region and pick the best with a perceptual metric plus boundary gradient continuity. This is the most direct stability gain.
- Overlapping tiles: split large regions into tiles with 1.5× overlap and feather the overlap so long-range context is not lost.
- Human–machine fallback: leave small, strongly semantic areas (eyes, text edges) to manual touch-up and automate the rest. That mix is usually best for throughput and control.
6. Quality is often lost in the last mile
A sharp preview and a soft download are usually an export-path problem, not a model problem:
- Keep lossless formats through intermediate steps. Do not introduce lossy compression in preview and then feed that back into export.
- Export with high-quality or near-lossless settings and an explicit quality level. Do not rely on defaults.
- Set color space and ICC profile explicitly, keep the original bit depth, and avoid repeated transcoding.
- Generate the preview and the final deliverable independently.
7. Production: batch architecture and observability
For a business inpainting service, a common cloud layout works well: object storage for source assets and outputs, a message queue for buffering and retries, a container platform with separate GPU and CPU pools, and logging plus alerting as the quality gate.
- Split queues: GPU queue for generation, CPU queue for masks and blending, so expensive capacity is not spent on light work.
- Idempotent dedup: key on a content hash of the asset so repeat requests hit cache.
- Core metrics: P95 latency, failure rate, retry rate, average mask area, and perceptual-metric drift.
- Canary and A/B: a new model must pass dual gates—MOS and perceptual metrics—on a fixed evaluation set before traffic is increased.
8. Common failure modes
| Symptom | Likely cause | What to do |
|---|---|---|
| Smeared edges | Mask too tight; no detail refinement | Dilate the mask and add a second-stage refine |
| Broken background structure | Not enough context; one-shot full-image inference | Multi-scale plus overlapping tiles |
| Overall color cast | No color alignment | Match mean and variance |
| Soft download | Lossy export or repeated transcoding | Lossless intermediates and explicit quality settings |
| Non-reproducible results | Random seed not fixed | Fix the seed and store it in the job context |
9. Put compliance first
Use inpainting only on assets you own or are authorized to edit. Do not use it to strip copyright marks, fabricate visual evidence, or mislead distribution. Production systems need retention and deletion policy, access audit, and redaction of sensitive data. Run compliance checks at the pipeline entrance, not as a later cleanup.
10. Selection checklist
Four questions are enough: Can the mask be adjusted and given a soft edge? Are both automatic and manual paths available? Can export be set to lossless or high quality? Are batch processing and observability in place? A stack that covers all four is usually far more stable in production than a one-click demo.
