-
Notifications
You must be signed in to change notification settings - Fork 1
/
Live_Doc_Scanner.py
80 lines (69 loc) · 2.81 KB
/
Live_Doc_Scanner.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
73
74
75
76
77
78
79
80
import cv2
import numpy as np
class docScanner :
def __init__(self) -> None:
pass
def preprocessing(self,img):
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(7,7),5)
canny = cv2.Canny(blur,100,0)
kernel = np.ones((5,5))
imgDial = cv2.dilate(canny,kernel,iterations=2)
imgThre = cv2.erode(imgDial,kernel,iterations=1)
return imgThre
def getContours(self,img):
biggest = np.array([])
maxArea=0
contours,heirarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
for cnt in contours:
area = cv2.contourArea(cnt)
if area>3000:
peri = cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,0.02*peri,True)
if area > maxArea and len(approx) == 4:
biggest = approx
maxArea = area
cv2.drawContours(self.imgContour,biggest,-1,(255,0,0),20)
return biggest
def imgWarp(self,img,biggest):
reordered = self.reorder(biggest)
width,height = 480,640
pts1 = np.float32(reordered)
pts2 = np.float32([[0,0],[width,0],[0,height],[width,height]])
matrix = cv2.getPerspectiveTransform(pts1,pts2)
imgOut = cv2.warpPerspective(img,matrix,(width,height))
return imgOut
def reorder(self,mypoints):
mypoints = mypoints.reshape((4,2))
myPointsNew = np.zeros((4,1,2),np.int32)
add = mypoints.sum(1)
myPointsNew[0] = mypoints[np.argmin(add)]
myPointsNew[3] = mypoints[np.argmax(add)]
diff = np.diff(mypoints,axis=1)
myPointsNew[1] = mypoints[np.argmin(diff)]
myPointsNew[2] = mypoints[np.argmax(diff)]
return myPointsNew
def scan(self):
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
imgThre = self.preprocessing(frame)
self.imgContour = frame.copy()
biggest = self.getContours(imgThre)
if biggest.size ==0:
cv2.imshow("Doc Scanner",self.imgContour)
else :
warped = self.imgWarp(frame,biggest)
warped = warped[0:620,0:460]
# a little sharpening the image if necessary
# kernel = np.array([[0, -1, 0],
# [-1, 5,-1],
# [0, -1, 0]])
# warped = cv2.filter2D(src=warped, ddepth=-1, kernel=kernel)
cv2.imshow("DOC",warped)
cv2.imshow("Doc Scanner",self.imgContour)
if cv2.waitKey(20) & 0xFF == ord('q'):break
cap.release()
cv2.destroyAllWindows()
Doc = docScanner()
Doc.scan()