opencv-python 去除图片文字
思路: 原图增强后提取增强后图片的轮廓进行闭运算,闭运算后的图像当掩码来修复原图即可去除文字
图像增强代码链接
import numpy as np
import cv2
def replaceZeroes(data):
min_nonzero = min(data[np.nonzero(data)])
data[data == 0] = min_nonzero
return data
def SSR(src_img, size):
L_blur = cv2.GaussianBlur(src_img, (size, size), 0)
img = replaceZeroes(src_img)
L_blur = replaceZeroes(L_blur)
dst_Img = cv2.log(img / 255.0)
dst_Lblur = cv2.log(L_blur / 255.0)
dst_IxL = cv2.multiply(dst_Img, dst_Lblur)
log_R = cv2.subtract(dst_Img, dst_IxL)
dst_R = cv2.normalize(log_R, None, 0, 255, cv2.NORM_MINMAX)
log_uint8 = cv2.convertScaleAbs(dst_R)
return log_uint8
if __name__ == '__main__':
img = 'cavity.png'
size = 3
src_img = cv2.imread(img)
b_gray, g_gray, r_gray = cv2.split(src_img)
b_gray = SSR(b_gray, size)
g_gray = SSR(g_gray, size)
r_gray = SSR(r_gray, size)
result = cv2.merge([b_gray, g_gray, r_gray])
cv2.imshow('img', src_img)
cv2.imshow('aaa', result)
cv2.imwrite('cavity1.png', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
对增强后图像进行Canny:
import cv2 as cv
img = cv.imread('cavity1.png', cv.IMREAD_GRAYSCALE)
canny_img = cv.Canny(img, 200, 150)
cv.imwrite('cavity2.png', canny_img)
1
2
3
4
对边缘图像进行闭运算得到掩码图:
import cv2 as cv
import numpy as np
img = cv.imread('cavity2.png', 1)
k = np.ones((3, 3), np.uint8)
img2 = cv.morphologyEx(img, cv.MORPH_CLOSE, k) # 闭运算
cv.imwrite('cavity3.png', img2)
1
2
3
4
5
6
7
对图像进行修复:
import cv2 as cv
def repair(path):
img = cv.imread(path)
b = cv.imread('cavity3.png',0)
dst = cv.inpaint(img, b, 5, cv.INPAINT_TELEA)
cv.imshow('dst', dst)
cv.imwrite(f'repair_{path}', dst)
cv.waitKey()
cv.destroyAllWindows()
if __name__ == '__main__':
repair('cavity.png')
来源:oschina
链接:https://my.oschina.net/u/4322037/blog/4295903