A QR Code Scanner in Python: Scans QR through WebCams

A QR Code Scanner in Python. It can scan QR images through the WebCam.

Introduction

Normally, we scan QR codes in a photo with the help of a mobile camera or some kind of external device. There are many third-party applications on the web that serve as a platform where we can scan a QR code directly.

But, in this tutorial, we are gonna create our own QR code scanner in python that will decode barcodes and QR codes both from an image through the Webcam of our computer or laptop.

Learn AlsoHow to Generate and Decode QR Code in Python

Technical Description

We'll use three python libraries here, OpenCV, pyzbar, and NumPy.  

OpenCV is an open-source library, widely used in artificial intelligence, computer vision, and machine learning. 

The pyzbar library is used to read one-dimensional barcodes and QR codes.

NumPy array is used in Python to work with scientific computing. This Python library is also used to work with multidimensional arrays that we are going to use in today's topic.

Requirements

First of all, it's a must to be Python 3 installed on Your machine. Then, install these libraries given below. Use pip3 instead of pip if you're using Linux.

OpenCV

  • pip install opencv-python

NumPy

  • pip install numpy

pyzbar

  • pip install pyzbar

For Mac OS

  • brew install zbar

For Linux, install the shared library given below. Otherwise, this error message may arise, "ImportError: Unable to find zbar shared library".

  • sudo apt-get install libzbar0

Code

Here is the full code for your convenience. I described each part of this code below. Visit there also.


import cv2
import numpy as np
# pyzbar import
from pyzbar.pyzbar import decode

def decoder(image):
# We're using BGR color format
trans_img = cv2.cvtColor(image,0)
BarCode = decode(trans_img)

for obj in BarCode:
points = obj.polygon
(x,y,w,h) = obj.rect
pts = np.array(points, np.int32)
# box size
pts = pts.reshape((-1, 1, 2))
thickness = 2
isClosed = True
# fill color (border)
line_color = (0, 0, 255)
cv2.polylines(image, [pts], isClosed, line_color, thickness)


# read qr codes (detect and decode qr codes)
BarCodeData = obj.data.decode("utf-8")
BarCodeType = obj.type
the_text = "Data: " + str(BarCodeData)

org = (x,y)
text_color = (0, 255, 0)
font = cv2.FONT_HERSHEY_COMPLEX_SMALL
cv2.putText(image, the_text, org, font, 0.9, text_color, 2)
# data print
print("The Data is: " + BarCodeData +" & the Type is: " + BarCodeType)

if __name__ == "__main__":
video = cv2.VideoCapture(0)
while True:
ret, frame = video.read()
decoder(frame)
cv2.imshow('Image', frame)
code = cv2.waitKey(1)
if code == ord('q'):
break

cv2.destroyAllWindows()

 

Output

Explanation of the Code

The main function


if __name__ == "__main__":
video = cv2.VideoCapture(0)
while True:
ret, frame = video.read()
decoder(frame)
cv2.imshow('Image', frame)
code = cv2.waitKey(1)
if code == ord('q'):
break

cv2.destroyAllWindows()

☛VideoCapture(0): 0 refers to the default camera. In my case, my laptop's Webcam. 

☛waitKey(1): It means, delays 1 millisecond. Wait for any key-press for 1 ms and it will continue to refresh and read the frame through the Webcam using the video.read() function. 

One question may arise in your mind, why we've not used 0 there? Because it would pause your screen and wait infinitely for key-press and will not refresh the frame.

☛if code == ord('q'): When you will press the 'q' key, the video capturing window will close and the program will stop running.

The decoder() function


def decoder(image):
# We're using BGR color format
trans_img = cv2.cvtColor(image,0)
BarCode = decode(trans_img)

for obj in BarCode:
points = obj.polygon
(x,y,w,h) = obj.rect
pts = np.array(points, np.int32)
pts = pts.reshape((-1, 1, 2))
thickness = 2
isClosed = True
line_color = (0, 0, 255)
cv2.polylines(image, [pts], isClosed, line_color, thickness)

BarCodeData = obj.data.decode("utf-8")
BarCodeType = obj.type
the_text = "Data: " + str(BarCodeData)

org = (x,y)
text_color = (0, 255, 0)
font = cv2.FONT_HERSHEY_COMPLEX_SMALL
cv2.putText(image, the_text, org, font, 0.9, text_color, 2)
print("The Data is: " + BarCodeData +" & the Type is: " + BarCodeType)

☛cv2.cvtColor(): It converts an image from one color space to another color. Here, 0 = cv2.COLOR_BGR2BGRA. There are more color options, you can get the details from here.

☛pts.reshape(): This function shapes an array without changing the actual data. The shape is in a 3-dimensional array.

☛cv2.polylines(): This method is used to draw a polygon on any image.

image - On this image, the polygon(square) would be drawn. [pts] - Array of polygonal curves. isClosed - Indicates whether the drawn poly-lines are closed.

lines_color - polyline color in BGR format. (255, 0, 0) is for Blue, (0, 255, 0) is for Green, and (0, 0, 255) is for Red. 

☛cv2.putText(): It draws the text(represents the data behind the QR Code) on the image.

org - coordinates of the Bottom-left corner of the text string in the image. By default, it appears in the top-left corner. 

fontHershey-Fonts.  

    More Font Types:

    • FONT_HERSHEY_COMPLEX,
    • FONT_HERSHEY__SIMPLEX,
    • FONT_HERSHEY_PLAIN,
    • FONT_HERSHEY_SCRIPT_COMPLEX,
    • FONT_HERSHEY__SCRIPT_SIMPLEX,
    • FONT_HERSHEY_TRIPLEX.

fontScale(0.9): It's a font scale factor, multiplied by font-specific base size.

Errors, which may arise

You may get certain error messages while running the program. Escape this part if you didn't get any.

🔹"ImportError: numpy.core.multiarray failed to import" 

Solution

If this error arises, try to upgrade the NumPy library. Simply run this command - pip install -U numpy.

🔹"AttributeError: partially initialized module 'numpy' has no attribute 'array'(most likely due to a circular import)"

Solution

If there is a file with the name numpy.py in the directory you're working in, then this problem will definitely arise. 

The solution is to rename or delete the file(numpy.py) from your current working directory.

Learn AlsoHow to Convert Speech to Text in Python

Summary

In this tutorial, we build a QR Code scanner using python which scans QR images through the WebCam.

We used three python libraries here, OpenCV, pyzbar, and NumPy create this QR Scanner. For any queries related to this topic, please comment below. You'll get an immediate response.

To get more lovely python topics, visit the separate page created only for Unique Examples. Some examples are given below.

👉Wish Your Friends with Stylish TExt in Python

👉Draw the Sketch of Lionel Messi using a Python Program

👉Create a Time Wasting Websites Blocker using Python

👉Extract emails and phone numbers from a webpage using python

Thanks for reading!💙

PySeek

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post