Create and read QR code with Python in 3 minutes (OpenCV and qrcode)

Pawel Stasinski
2 min readSep 25, 2019

--

Today we will create a QR code in Python, and read it using OpenCV.
You can split the article into two parts:

  • create QR code in Python.
  • scan QR code using OpenCV on video.

Step 1 - create a Python QR code

Prepare a virtual environment for your project in virtualenv.
(Repo: https://github.com/fuwiak/qr_code)

# terminal(Bash)

virtualenv -p python3 env #create virtual env with name 'env'
source env/bin/activate #activate enviroment 'env'
pip install -r requirements.txt # install python modules

Here we generate a QR-code using the qrcode library:

import qrcode 
img_name = "medium.png"
def generate(data="https://habr.com", img_name="habr.png"):
img = qrcode.make(data) #generate QRcode
img.save(img_name)
return img
generate()
# in command line
python3 generate_qr.py

Here is and is obtained in our folder such a the:

Uploading an image:

def read_qr(img_name):
import cv2
img = cv2.imread(img_name)
return img
qr = read_qr(img_name) #<class 'numpy.ndarray'>

By the way, if someone has to do image processing(approximately QR-code), you can do it in scikit-image.
I wrote a simple tutorial on this topic. https://medium.com/@stasinskipawel/image-processing-with-python-scikit-image-de3969533701

Step 2-scan the QR code with OpenCV on video

# command line
python3 video.py

Just attach the QR-code to the camera:

import cv2def video_reader():
cam = cv2.VideoCapture(0)
detector = cv2.QRCodeDetector()
while True:
_, img = cam.read()
data, bbox, _ = detector.detectAndDecode(img)
if data:
print("QR Code detected-->", data)
cv2.imshow("img", img)
if cv2.waitKey(1) == ord("Q"):
break
cam.release()
cv2.destroyAllWindows()
video_reader()

To turn off the program press the keyboard “Q”.

--

--