原理:利用opencv库的API,函数cv2.inpaint(原图像,蒙版,修复算法(cv2.INPAINT_TELEA/cv2.INPAINT_NS))
1、基于快速行进算法 cv2.INPAINT_TELEA。
2、基于流体动力学并使用了偏微分方程 cv2.INPAINT_NS。
蒙版是一个标出图像破损位置的灰度(黑白/二值)图像,待修复位置为白色,其他位置为黑色
首先,先自己创造一个损坏的图片,即将图片某部分像素的值改为255,也就是待修复区域
import cv2
import numpy as np
img = cv2.imread('D:/pythonob/imageinpaint/img/flowerC.jpg',1)
for i in range(200,300):
img[200, i] = [255, 255, 255]
img[200+1, i] = [255, 255, 255]
img[200-1, i] = [255, 255, 255]
for i in range(150,250):
img[i,250] = [255,255,255]
img[i, 250+1] = [255, 255, 255]
img[i, 250-1] = [255, 255, 255]
cv2.imshow('damaged',img)
cv2.imwrite('D:/pythonob/imageinpaint/img/damagedFlower.jpg',img)
cv2.waitKey(0)
效果图:
图片修复:
import cv2
import numpy as np
img = cv2.imread('D:/pythonob/imageinpaint/img/damagedFlower.jpg',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
paint = np.zeros((height,width,1),np.uint8)
for i in range(200,300):
paint[200, i] = 255
paint[200+1, i] = 255
paint[200-1, i] = 255
for i in range(150,250):
paint[i,250] = 255
paint[i, 250+1] = 255
paint[i, 250-1] = 255
result = cv2.inpaint(img,paint,3,cv2.INPAINT_TELEA)#图像修复函数
cv2.imshow('src',img)
cv2.imshow('damaged',paint)
cv2.imshow('repainted',result)
cv2.waitKey(0)
效果图: