-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove lines in drawing paper.py
41 lines (34 loc) · 1.66 KB
/
remove lines in drawing paper.py
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
import cv2
import numpy as np
import matplotlib.pyplot as plt
link = r'https://stackoverflow.com/questions/71425968/remove-horizontal-lines-with-open-cv/71475252#71475252'
img = cv2.imread(r'E:\Downloads\i0RDA.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Remove horizontal lines
thresh = cv2.adaptiveThreshold(gray, 255 ,cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY_INV, 81, 17)
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25, 1))
# Using morph close to get lines outside the drawing
remove_horizontal = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE,
horizontal_kernel, iterations=3)
cnts = cv2.findContours(remove_horizontal, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
mask = np.zeros(gray.shape, np.uint8)
for c in cnts:
cv2.drawContours(mask, [c], -1, (255, 255, 255), 2)
# First inpaint
img_dst = cv2.inpaint(img, mask, 3, cv2.INPAINT_TELEA)
gray_dst = cv2.cvtColor(img_dst, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray_dst, 50, 150, apertureSize=3)
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 1))
# Using morph open to get lines inside the drawing
opening = cv2.morphologyEx(edges, cv2.MORPH_OPEN, horizontal_kernel)
cnts = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
mask = np.uint8(img_dst)
mask = np.zeros(gray_dst.shape, np.uint8)
for c in cnts:
cv2.drawContours(mask, [c], -1, (255, 255, 255), 2)
# Second inpaint
img2_dst = cv2.inpaint(img_dst, mask, 3, cv2.INPAINT_TELEA)