forked from AwesomeLemon/document-recognition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scan.py
72 lines (61 loc) · 2.21 KB
/
scan.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# coding=utf-8
# import the necessary packages
import util
from transform import four_point_transform
from skimage.filters import threshold_adaptive
import argparse
import cv2
def scan(imgname="chom4.jpg", show=True):
path = imgname
image = cv2.imread(path)
ratio = image.shape[0] / 700.0
orig = image.copy()
image = util.resize(image, height=700)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.medianBlur(gray, 5)
edged = cv2.Canny(gray, 40, 150)
edged_copy = edged.copy()
edged_copy = cv2.GaussianBlur(edged_copy, (3, 3), 0)
cv2.imwrite('edged.jpg', edged)
if show:
cv2.imshow("Edged", edged)
cv2.imshow("Edged blurred", edged_copy)
cv2.waitKey(0)
cv2.destroyAllWindows()
(_, cnts, _) = cv2.findContours(edged_copy, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:4]
screenCnt = []
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.015 * peri, True)
# approx = np.array(cv2.boundingRect(c))
# if our approximated contour has four points, then we
# can assume that we have found our screen
debugging = False
if debugging:
cv2.drawContours(image, [approx], -1, (0, 255, 0), 2)
cv2.imshow("Outline", image)
cv2.waitKey(0)
if len(approx) == 4:
screenCnt = approx
break
if screenCnt.__len__() != 0:
if show:
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
cv2.imwrite('outlined.jpg', image)
cv2.imshow("Outline", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)
else:
warped = orig
warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
warped = threshold_adaptive(warped, 251, offset=10)
warped = warped.astype("uint8") * 255
if show:
cv2.imshow("Original", util.resize(orig, height=650))
cv2.imshow("Scanned", util.resize(warped, height=650))
cv2.waitKey(0)
cv2.imwrite('deskewed.jpg', warped)
# scan()