Quick-reference (QR) codes are similar to barcodes, as they are able to encode data that is represented by black and white squares. But instead of using a laser, a camera differentiates between the spaces and then sends that information to be processed. They are comprised of several large squares that help to align and position the edges of the QR code, formatting columns, a version number, and finally, the data itself.
The data they contain can encode a variety of types, including numbers, characters, and binary, which can allow for many creative uses. Advertisers often encode URLs in them that redirect the user to their website. Other companies might place important product information in a QR code, such as a serial number, and attach it to a component.Generating Them with Python
There is a Python package called "qrcode" that lets users quickly encode data inside of a QR code and then export it as an image. To install it, run:
pip3 install qrcode[pil]
Then you can import it into a script and generate a PIL image with:
code = qrcode.make('Hello world!')
Then the image can be exported to a file by using
You can further customize your codes by using the QRCode class, which gives options such as size, error correction amount, version, and border width.
Now that all of your custom QR codes have been created, compile them into a single page and print them out.
I chose to use a Raspberry Pi 4 due to how powerful it is, which can give the application a bit of a boost in speed when reading images.
I installed Raspbian on it by downloading the OS image and flashing it using Balena Etcher. Next, I connected to it via SSH and installed OpenCV with:
sudo apt-get update
sudo apt-get install python3-opencv
sudo apt-get install libqt4-test python3-sip python3-pyqt5 libqtgui4 libjasper-dev libatlas-base-dev -y
pip3 install opencv-contrib-python==126.96.36.199
sudo modprobe bcm2835-v4l2
The last command lets you use the picamera with OpenCV VideoCapture.
I tested if the installation was successful with
Reading the QR Codes
The code works as follows:
- Set up the camera and QR code detector
- Read in a new frame and extract a QR code
- If there is a code, draw a box around it and display its data above
- If the exit key 'q' hasn't been pressed, go back to step 2.
The program also shows the updated frame with the overlaid graphics on each update.Future Uses
Since QR codes are so useful for tracking many different parts, such as in a warehouse, I plan on using them to keep tabs on my collection of hardware, such as boxes of resistors or an Arduino board.