DEV Community

M Paracha
M Paracha

Posted on

Inpainting a Corner Region With OpenCV in Python

Inpainting, filling a small region of an image using its surroundings, is one of the most useful image-processing tricks to know. OpenCV ships two classic algorithms that work well for small areas like dust spots, scratches or a logo in a corner.

Install

pip install opencv-python numpy
Enter fullscreen mode Exit fullscreen mode

Build a mask for the corner

The mask is a single-channel image: white where you want pixels rebuilt, black everywhere else.

import cv2
import numpy as np

img = cv2.imread("input.png")
h, w = img.shape[:2]

mask = np.zeros((h, w), dtype=np.uint8)
box = int(min(h, w) * 0.08)        # 8% of the short side
margin = int(box * 0.3)
cv2.rectangle(mask,
              (w - box - margin, h - box - margin),
              (w - margin, h - margin),
              255, -1)
Enter fullscreen mode Exit fullscreen mode

Run the two algorithms

telea = cv2.inpaint(img, mask, 5, cv2.INPAINT_TELEA)
ns    = cv2.inpaint(img, mask, 5, cv2.INPAINT_NS)

cv2.imwrite("telea.png", telea)
cv2.imwrite("ns.png", ns)
Enter fullscreen mode Exit fullscreen mode
  • TELEA (fast marching) tends to look smoother on gradients.
  • NS (Navier-Stokes) follows edges a little better.

Dilate the mask slightly

Anti-aliased logos leave a faint halo. Growing the mask by a few pixels removes it:

mask = cv2.dilate(mask, np.ones((5, 5), np.uint8), iterations=1)
Enter fullscreen mode Exit fullscreen mode

Where classic inpainting struggles

Both algorithms diffuse colour inward, so they blur fine texture and cannot invent structure like text or tiled patterns. For those, learned models (LaMa and similar) do much better.

A no-code option

If you just need to clean the small visible sparkle on images you generated with Gemini, a Gemini watermark remover online does the detection and inpainting in the browser, without uploading the file.

As always, only edit images you own or have permission to edit. Visible-mark removal does not affect invisible provenance such as SynthID.

Top comments (0)