跳到正文
DEV Community· M Paracha·· 1 小時前AI 評分50

如何用 Python 和 OpenCV 修補圖像角落區域

Inpainting a Corner Region With OpenCV in Python

AI 導讀

教程示範如何用 Python 和 OpenCV 修補圖像角落的小區域,先建立遮罩,再以 TELEA 或 NS 演算法補繪像素。TELEA 在漸變區域通常較平滑,NS 對邊緣的跟隨稍好;輕微膨脹遮罩可去除抗鋸齒標誌留下的淡色光暈。兩種傳統方法會模糊細緻紋理,也無法生成文字或平鋪圖案等結構;文章指出 LaMa 等學習模型在這類情況下效果較好。

正文

M Paracha

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

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)

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)
  • 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)

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.

來源:DEV Community · dev.to