How to Scan QR Code from Desktop Screen in Python

In our life, we usually take out smartphone to scan QR code. But when we are working on a computer, smartphone may not be the best choice for scanning QR codes that appear on web pages. One reason is the pictures taken from a monitor screen have the Moire’ patterns which interfere QR code recognition. The other reason is you may want to use the decoded information directly on PC, such as a URL for opening a website. This article will implement a simple tool with Python to facilitate QR code recognition on desktop screen.

Installation

The required Python packages include PIL, OpenCV, Dynamsoft Barcode Reader and Qt.

Barcode SDK License

To unlock the capabilities of Dynamsoft Barcode SDK, you’d better apply for a 30-day free trial license.

Scanning QR Code from Screen

Since I have implemented a GUI barcode reader using Qt for Python, OpenCV and Dynamsoft Barcode Reader, the remaining stuff is to add screen snipping functionality. Inspired by https://github.com/harupy/snipping-tool, I learned the steps of implementing the screenshot functionality:

  1. Create a custom Qt widget and put it on top of the screen.
  2. Draw the selected area in paintEvent() function while moving the mouse.
  3. As the mouse is released, call PIL.ImageGrab.grab() to get the image of the selected area.

Add buttons for snipping events

We open the design.ui file in Qt Creator and add two buttons for triggering the snipping events.

Save the file and recompile design.ui to design.py:

In app_advanced.py, the two new buttons should be recognizable now. Connect them to slot functions:

Create a SnippingTool.py file, in which we create a custom Qt widget:

The size of the widget should be the same as the screen resolution, which can be obtained from the primaryScreen() function.

Next, we handle the mouse events:

While the mouse is moving, we draw a rectangle to indicate the selected area in paintEvent() function:

Take screen images

PIL is the Python library for capturing images from the screen. After releasing the mouse, we take the screenshot of the selected area based on the coordinates of the rectangle:

Taking full screen image is easy:

Hide and show the application window

Once the snipping widget is ready, we can call it in button click event. Note: to avoid obstructing the screen, the application window should be minimized before launching the snipping widget and restored after the snipping is completed:

Test the screen QR reader

  1. Run the barcode recognition program:

2. Search Google for QR code.

3. Click the Select Area button to scan QR code (one or multiple) returned by search engine.

4. You can also make a full screen barcode recognition by one click.

Source Code

https://github.com/yushulx/python-gui-barcode-reader

Originally published at https://www.dynamsoft.com on October 7, 2021.

Manager of Dynamsoft Open Source Projects | Tech Lover