Live Qr-scanner With Python using OpenCV :

by Ahin subhra das

Basically , a QR code works in the same way as a barcode at the supermarket. It is a machine — scannable image that can instantly be read using a Smartphone camera or computer web cam . Every QR code consists of a number of black squares and dots which represent certain pieces of information .

In this article we are going to make a Qr scanner from live stream

with python using OpenCV .

Code :

import cv2

import numpy as np

import pyzbar.pyzbar as pyzbar

cap = cv2.VideoCapture(0)

font = cv2.FONT_HERSHEY_PLAIN

while True:

_, frame = cap.read()

decodedObjects = pyzbar.decode(frame)

for obj in decodedObjects:

#print(“Data”, obj.data)

cv2.putText(frame, str(obj.data), (50, 50), font, 2,

(255, 0, 0), 3)

cv2.imshow(“Frame”, frame)

key = cv2.waitKey(1)

Code Explanation :

Firstly we need to import all libraries for our project . Here a new packeage comes that is pyzbar .

pyzbar is a pure Python library that reads one-dimensional barcodes and QR codes using the zbar library, an open source software suite for reading bar codes from various sources, such as video streams, image files and raw intensity sensors.

Then we need to call two functions one is VideoCapture() and another is FONT_HERSHEY_PLAIN() . First one is to get a video capture object for the camera and second one is for font type .

After that Set up an infinite while loop and use the read() method to read the frames using the above created object. We use cap.read() to read vedio capture files .

pyzbar.decode() function returns a list of namedtuple called Decoded . Each of them contains the following fields: data — The decoded string in bytes. You need to decode it using utf8 to get a string.

Afterwards we use for loop to print (putText) qr code string in our live vedio frame .

At last cv2.imshow(“Frame”, frame) to show the result frame in our tab .

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store