-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
73 lines (57 loc) · 1.97 KB
/
test.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
import cv2
import numpy as np
import imutils
import transform
#reading the image
img = cv2.imread('dualpage.jpg')
#reduce dimensions
ratio = img.shape[0] / 500.0
orig = img.copy()
img = imutils.resize(img, height = 500)
#convert it to gray scale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#apply a low pass filter
gray = cv2.GaussianBlur(gray , (15,15), 0)
#threshold the image and convert it to binary
gray = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11 , 2)
#find the edges
edge = cv2.Canny(gray, 75, 200)
#fil the space
#edge1 = cv2.morphologyEx(edge, cv2.MORPH_CLOSE, (25,25), iterations = 1)
edge = cv2.dilate(edge, (101,101))
#show image
cv2.imshow('edge image', edge)
cv2.waitKey()
cv2.destroyAllWindows()
#draw contours
(_, cnts,_) = cv2.findContours(edge.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:10]
for c in cnts:
peri = 0.02*cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c,peri, True)
#the book has approx 4 sides
if(len(approx) == 4):
screenCnt = approx
break;
#draw Contour
cnt = img.copy()
cv2.drawContours(cnt, [screenCnt], -1, (0,225,0) , 2)
cv2.imshow('Book',cnt )
cv2.waitKey()
cv2.destroyAllWindows()
#perspective trasform
# apply the four point transform to obtain a top-down
# view of the original image
origCnt = screenCnt.reshape(4, 2) * ratio
warped = transform.four_point_transform(orig,origCnt)
# convert the warped image to grayscale, then threshold it
# to give it that 'black and white' paper effect
warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
#T = cv2.adaptiveThreshold(warped,255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
#warped = (warped > T).astype("uint8") * 255
# show the original and scanned images
cv2.imshow("Original", imutils.resize(orig, height=650))
cv2.imshow("Scanned", imutils.resize(warped, height=650))
cv2.waitKey()
#write it into an image
cv2.imwrite('scanned.jpg', warped)