-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner.py
More file actions
126 lines (90 loc) · 2.69 KB
/
scanner.py
File metadata and controls
126 lines (90 loc) · 2.69 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#! /usr/bin/env python3
# encoding:utf-8
import time
import cv2
import pymongo
from pyzbar.pyzbar import decode
from pymongo import MongoClient
def get_database():
""" Connect to mongodb database """
# Provide the mongodb atlas url to connect python to mongodb
CONNECTION_STRING = input("mongoDB connection string: ")
# Create a connection using MongoClient.
client = MongoClient(CONNECTION_STRING)
database = input("Database name: ")
return client[database]
def input_book_info(barcode):
""" input book item
Args: barcode
Returns:
book information
"""
title = input("Enter book title: ")
author = input("Enter author(first): ")
category = input("Enter category: ")
language = input("Enter language: ")
book_info = {
"_id" : barcode,
"title" : title,
"author" : author,
"language" : language,
"category" : category
}
print(book_info)
return book_info
def retrieve_record(collection, book_id):
""" retrieve book item
Args:
collection
book_id
Returns:
book information
"""
book_info = collection.find_one({"_id": book_id})
print(book_info)
return book_info
def config_camera(width, height):
""" camera configuration """
capture = cv2.VideoCapture(0)
capture.set(3, width)
capture.set(4, height)
return capture
def main():
# connect to database
dbname = get_database()
collection_name = dbname["books"]
while True:
print("Input 1 for retrieving items, 2 for inserting items.")
mode = input("Selected mode: ")
if mode not in ['1','2']:
print("Invalid Mode!")
else:
break
# configurate camera
cap = config_camera(640, 480)
camera = True
while (camera == True):
success, frame = cap.read()
for code in decode(frame):
# read barcode
barcode = code.data.decode('utf-8')
print(barcode)
time.sleep(1)
# retrieve record from database
if mode == '1':
book = retrieve_record(collection_name, barcode)
# insert record to database
if mode == '2':
book = input_book_info(barcode)
try:
collection_name.insert_one(book)
except pymongo.errors.DuplicateKeyError:
print("ID exists!")
continue
cv2.imshow('Code-scanner',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()