-
Notifications
You must be signed in to change notification settings - Fork 1
/
camera_async_api.py
93 lines (75 loc) · 2.91 KB
/
camera_async_api.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
81
82
83
84
85
86
87
88
89
90
91
92
93
import argparse
import docscanner
import sys
import numpy as np
import cv2
import time
g_results = None
g_normalized_images = []
def callback(results):
global g_results
g_results = results
def showNormalizedImage(name, normalized_image):
mat = docscanner.convertNormalizedImage2Mat(normalized_image)
cv2.imshow(name, mat)
return mat
def process_video(scanner):
scanner.addAsyncListener(callback)
cap = cv2.VideoCapture(0)
while True:
ret, image = cap.read()
ch = cv2.waitKey(1)
if ch == 27:
break
elif ch == ord('n'): # normalize image
if g_results != None:
g_normalized_images = []
index = 0
for result in g_results:
x1 = result.x1
y1 = result.y1
x2 = result.x2
y2 = result.y2
x3 = result.x3
y3 = result.y3
x4 = result.x4
y4 = result.y4
normalized_image = scanner.normalizeBuffer(
image, x1, y1, x2, y2, x3, y3, x4, y4)
g_normalized_images.append(
(str(index), normalized_image))
mat = showNormalizedImage(str(index), normalized_image)
index += 1
elif ch == ord('s'): # save image
for data in g_normalized_images:
# cv2.imwrite('images/' + str(time.time()) + '.png', image)
cv2.destroyWindow(data[0])
data[1].save(str(time.time()) + '.png')
print('Image saved')
g_normalized_images = []
if image is not None:
scanner.detectMatAsync(image)
if g_results != None:
for result in g_results:
x1 = result.x1
y1 = result.y1
x2 = result.x2
y2 = result.y2
x3 = result.x3
y3 = result.y3
x4 = result.x4
y4 = result.y4
cv2.drawContours(
image, [np.intp([(x1, y1), (x2, y2), (x3, y3), (x4, y4)])], 0, (0, 255, 0), 2)
cv2.putText(image, 'Press "n" to normalize image',
(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
cv2.putText(image, 'Press "s" to save image', (10, 60),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
cv2.putText(image, 'Press "ESC" to exit', (10, 90),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
cv2.imshow('Document Scanner', image)
docscanner.initLicense(
"DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==")
scanner = docscanner.createInstance()
ret = scanner.setParameters(docscanner.Templates.color)
process_video(scanner)