Image Inpainting with OpenCV and Python

Subscribe to my newsletter and never miss my upcoming articles

Hello Developers👨‍💻,
What you do if you find your old photographs with scratches, damaged sections, or unwanted objects...
So you can fix this using photoshop. Big NOOOO!! that's not the way developers do.
We can solve this problem with our magical powers in just a few lines of code.

Image Inpainting

It is a process of removing damages such as scratches, strokes, or text on images, basically, it is the restoration of photographs.

How it Works

In this, the damaged pixel is replaced by the pixels similar to the neighboring ones and making it unnoticeable with the background.

Image Inpainting Algorithms

Here we will discuss two inpainting algorithms implemented in OpenCV

INPAINT_NS: Navier-Stokes based Inpainting

This algorithm is inspired by partial differential equations. Starting from the edges (known regions) towards the unknown regions, it propagates isophote lines (lines that join same-intensity points). Finally, variance in an area is minimized to fill colors.

INPAINT_TELEA: Fast Marching Method based

This is based on the Fast Marching Method (FMM). Looking at the region to be inpainted, the algorithm first starts with the boundary pixels and then goes to the pixels inside the boundary. It replaces each pixel to be inpainted with a weighted sum of the pixels in the background, with more weight given to nearer pixels and boundary pixels.

Main Code

inpainted_image = cv2.inpaint(src,inpaintMask, inpaintRadius,flags)
  • src = Source image
  • inpaintMask = A binary mask indicating pixels to be inpainted.
  • inpaintRadius = Neighborhood around a pixel to inpaint. Typically, if the regions to be inpainted are thin, smaller values produce better results (less blurry).
  • flags : INPAINT_NS (Navier-Stokes based method) or INPAINT_TELEA (Fast marching based method)


import cv2

# damaged_image: Image to be inpainted
damaged_image = cv2.imread('Damaged.jpeg')
damaged_image=cv2.resize(damaged_image,(400,400)) #same size as mask

# mask:  A binary mask indicating pixels to be inpainted.
mask = cv2.imread('mask.png',0)
mask = cv2.resize(mask,(400,400)) # same size as damaged image

#Final Magical Result
inpainted_image = cv2.inpaint(damaged_image,mask,3,cv2.INPAINT_TELEA)

#Write Final Image
Damaged ImageMaskResult

Working Demo: Click Here

No Comments Yet