-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrop_to_text.py
47 lines (33 loc) · 1.38 KB
/
crop_to_text.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
42
43
44
45
46
47
import cv2
import argparse
import sys
import numpy as np
def fit_to_text(image):
#small = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
grad = cv2.morphologyEx(image, cv2.MORPH_GRADIENT, kernel)
_, bw = cv2.threshold(grad, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))
connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, kernel)
# using RETR_EXTERNAL instead of RETR_CCOMP
_, contours, hierarchy = cv2.findContours(connected.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
mask = np.zeros(bw.shape, dtype=np.uint8)
x, y, w, h = cv2.boundingRect(contours[0])
mask[y:y+h, x:x+w] = 0
cv2.drawContours(mask, contours, 0, (255, 255, 255), -1)
r = float(cv2.countNonZero(mask[y:y+h, x:x+w])) / (w * h)
if r > 0.45 and w > 8 and h > 8:
return image[y:y+h, x:x+w]
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="path to image to crop")
args = vars(ap.parse_args())
image = cv2.imread(args["image"])
#print(image.shape)
#cv2.imshow("Image", image)
#image = find_boundary(image)
image = fit_to_text(image)
#print(image.shape)
#cv2.imshow("Cropped", image)
cv2.imwrite("UbuntuMono-Cropped.png", image)