From 815011f555e747e98a8fe1d65aad7021ef7b7197 Mon Sep 17 00:00:00 2001 From: Manthan109 <42516515+Manthan109@users.noreply.github.com> Date: Thu, 22 Nov 2018 09:23:13 +0530 Subject: [PATCH] Scanning QR Code and Barcodes --- QR code scanner.py | 94 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 QR code scanner.py diff --git a/QR code scanner.py b/QR code scanner.py new file mode 100644 index 0000000..3f1d49a --- /dev/null +++ b/QR code scanner.py @@ -0,0 +1,94 @@ +from __future__ import print_function + +import pyzbar.pyzbar as pyzbar +import numpy as np +import cv2 +import time +import sqlite3 +import json + +# get the webcam: +cap = cv2.VideoCapture(0) + +cap.set(3,640) +cap.set(4,480) +#160.0 x 120.0 +#176.0 x 144.0 +#320.0 x 240.0 +#352.0 x 288.0 +#640.0 x 480.0 +#1024.0 x 768.0 +#1280.0 x 1024.0 +time.sleep(2) + +def decode(im) : + # Find barcodes and QR codes + decodedObjects = pyzbar.decode(im) + # Print results + for obj in decodedObjects: + print('Type : ', obj.type) + print('Data : ', obj.data,'\n') + return decodedObjects + +db_conn = sqlite3.connect('scanned_items.db') +db_cursor = db_conn.cursor() + +db_cursor.execute('CREATE TABLE IF NOT EXISTS scanned_items(id INTEGER PRIMARY KEY, item_name TEXT, quantity INTEGER);') + +font = cv2.FONT_HERSHEY_SIMPLEX + +while(cap.isOpened()): + # Capture frame-by-frame + ret, frame = cap.read() + # Our operations on the frame come here + im = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) + + decodedObjects = decode(im) + + for decodedObject in decodedObjects: + points = decodedObject.polygon + + # If the points do not form a quad, find convex hull + if len(points) > 4 : + hull = cv2.convexHull(np.array([point for point in points], dtype=np.float32)) + hull = list(map(tuple, np.squeeze(hull))) + else : + hull = points; + + # Number of points in the convex hull + n = len(hull) + # Draw the convext hull + for j in range(0,n): + cv2.line(frame, hull[j], hull[ (j+1) % n], (255,0,0), 3) + + x = decodedObject.rect.left + y = decodedObject.rect.top + + print(x, y) + + print('Type : ', decodedObject.type) + print('Data : ', decodedObject.data,'\n') + + barCode = str(decodedObject.data) + cv2.putText(frame, barCode, (x, y), font, 1, (0,255,255), 2, cv2.LINE_AA) + + data = json.loads(decodedObject.data) + + db_cursor.execute('SELECT * FROM scanned_items WHERE item_name=?', (data['item_name'],)) + db_data = db_cursor.fetchall() + if not db_data: + db_cursor.execute('INSERT INTO scanned_items(item_name, quantity) VALUES(?,?);', (data['item_name'], data['quantity'])) + + db_conn.commit() + # Display the resulting frame + cv2.imshow('frame',frame) + key = cv2.waitKey(1) + if key & 0xFF == ord('q'): + break + elif key & 0xFF == ord('s'): # wait for 's' key to save + cv2.imwrite('Capture.png', frame) + +# When everything done, release the capture +cap.release() +cv2.destroyAllWindows() +db_conn.close()