Image Inpainting using OpenCV
OpenCV uses image inpainting to fill in missing or damaged parts of an image by reconstructing the lost regions based on the surrounding areas. OpenCV provides a simple and efficient way to perform image inpainting using two methods : Telea’s Method & Navier – Stokes Method.
Telea’s Method :
Telea’s method is a fast marching method used for image inpainting. Alexandru Telea proposed it in 2004, designing it to reconstruct damaged or missing regions in an image by iteratively propagating information from surrounding pixels. It particularly suits filling small, irregular gaps and tends to produce natural-looking results.
Steps of Telea’s Algorithm :
-
Initialize the boundary as the starting point of inpainting.
- Estimate the value of each pixel on the boundary of the missing region using neighboring pixels.
- Remove a pixel from the boundary once it is filled, and continue the process until all missing pixels are filled.
- The algorithm stops when there are no unfilled pixels remaining in the mask.
Navier – Stokes Method :
Here’s how you can use OpenCV to perform image inpainting :
Steps to perform Image Inpainting :
- First, load the input image by reading the image with damaged areas (e.g., scratches, unwanted objects). Then, proceed to the next step of processing the image for inpainting.
-
- Apply Inpainting : Use OpenCV’s cv2.inpaint function to restore the image.
Example :
import cv2 import numpy as np # Step 1: Load the damaged image image = cv2.imread('damaged_image.jpg') if image is None: print("Error: Unable to load image") exit() # Step 2: Load or create the mask # The mask should have white (255) where the image is damaged and black (0) elsewhere mask = cv2.imread('mask.png', cv2.IMREAD_GRAYSCALE) if mask is None: print("Error: Unable to load mask") exit() # Step 3: Perform inpainting using OpenCV # Inpainting methods: cv2.INPAINT_TELEA or cv2.INPAINT_NS restored_image = cv2.inpaint(image, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA) # Step 4: Display the results cv2.imshow('Original Image', image) cv2.imshow('Mask', mask) cv2.imshow('Restored Image', restored_image) cv2.waitKey(0) cv2.destroyAllWindows()
Parameters Explanation :
- image : The damaged input image.
- mask :
- The binary mask indicating damaged areas (white = damaged, black = undamaged).
- inpaintRadius : Radius of a circular neighborhood of each point in the mask. The algorithm uses this radius to fill the gaps.
- flags : The inpainting algorithm to us :
- cv2.INPAINT_TElEA : Fast marching method, suitable for natural – looking restoratio.
- cv2.inPAinT_NS : Naier-Stokes based method, suitable for restoring smoother surfaces.