Change language

Coloring images using OpenCV

| | |

Image coloring works by replacing damaged pixels with pixels that are similar to their neighbors, making them invisible and helping them blend well with the background. Take a look at the image below. 

The image has several marks on the right. To paint over this image, we need a mask , which is essentially a black image with white marks on it to indicate the areas that need to be corrected. In this case, the mask is created manually on the GIMP. 

Drawing algorithms —

OpenCV implements two drawing algorithms:

  1. "Fast march based drawing method", Alexandru Telea, 2004:
    This is fast marching based drawing method marching (FMM). Looking at the area to be painted over, the algorithm first starts with the border pixels and then moves to the pixels inside the border. It replaces each pixel that will be colored with a weighted sum of pixels in the background, with more weight given to the nearest pixels and boundary pixels.
  2. Navier Stokes, Fluid Dynamics and Images and Videos, Bertalmio, Marcelo, Andrea L. Bertozzi and Guillermo Sapiro, 2001:
    This algorithm is based on partial differential equations. Starting from the edges (known areas) towards unknown areas, it propagates isophote lines (lines that connect points of equal intensity). Finally, the variance in the area is minimized to fill in the colors.

FMM can be called with cv2.INPAINT_TELEA , whereas Navier-Stokes can be called with using cv2.INPAINT_NS . The below Python code will color the cat image using Navier Stokes.

import numpy as np

import cv2

# Open the image.

img = cv2.imread ( ’ cat_damaged.png’ )

# Load the mask.

mask = cv2.imread ( ’cat_mask.png’ , 0 )

 < / code> 
# Inpaint.

dst = cv2.inpaint (img, mask, 3 , cv2.INPAINT_NS )

# Write the output.

cv2.imwrite ( ’cat_inpainted.png’ , dst)