Python – create and read QR code

Python - create and read QR code

QR code is currently a widespread way of storing information,
both on real objects and in a virtual environment, for example by scanning a barcode
you can pay for the purchase or go to the site of interest.
This feature can be implemented in Python using Opencv,
having a built-in function for reading information, and a library qrcode.
First, let’s install the appropriate packages:


pip3 install opencv-python qrcode 

import qrcode # импотируем модуль 

string = "https://myrusakov.ru" # строка для перевода в QR

file = "myrusakov_out.jpg" # файл для хранения полученного штрих кода

image = qrcode.make(string) # метод отвечает за преобразование строки в QR

image.save(file) # сохранение  полученного объекта в  файл  myrusakov_out.jpg

With this in QR code you can encode a fairly long string, which is still limited in size. For now, we are interested in storing the address bar of the site, and then reading the data. It should be noted that there are many tools for reading code in the program area, but we use Opencv, as the most convenient for us, in view of the possibility of integration with a computer web camera, or video stream. For correct execution of the code, the image with QR code should be kept in the same folder with our script… The following script outputs the decoded string.


import cv2   # импорт модуля  из библиотеки Opencv
import numpy as np # модуль обработки массивов
import sys  # системный модуль
import time  

# Первый блок проверяет условие, передан ли скрипту в командной строке дополнительный аргумент в виде картинки **QR кода**. Если первое условие ложно, то считывается указанная нами картинка. 

if len(sys.argv)>1:
    inputImage = cv2.imread(sys.argv[1])  
else:
    inputImage = cv2.imread("myrusakov_out.jpg") #  стандартный метод opencv для считывания изображения

#  Создание функции выводящей в отдельном окне изображение QR с синим обрамлением. 
def display(im, bbox):

    n = len(bbox)

    for j in range(n):

        cv2.line(im, tuple(bbox[j][0]), tuple(bbox[ (j+1) % n][0]), (255,0,0), 3)
 
    # Display results
    cv2.imshow("Results", im)

# В Opencv имеется  встроенный метод детектор QR

qrDecoder = cv2.QRCodeDetector() # создание объекта детектора

 

# Нахождение и декодирование нашего кода. Метод **detectAndDecode** возвращает  кортеж из трех  значений которыми кодируется QR, где первый аргумент data содержит декодированную строку, bbox - координаты вершин нашего изображения и rectifiedImage,  содержит **QR** изображение в виде массива пикселей.

data, bbox, rectifiedImage = qrDecoder.detectAndDecode(inputImage)

if len(data)>0:

    print("Decoded Data : {}".format(data)) # вывод декодированной строки

    display(inputImage, bbox)

    #rectifiedImage = np.uint8(rectifiedImage);

    #cv2.imshow("Rectified QRCode", rectifiedImage); 

else:

    print("QR Code not detected")  

    cv2.imshow("Results", inputImage)

cv2.waitKey(0)

cv2.destroyAllWindows()

Thus, in this article we have learned how to programmatically create QR code from source data,
and also decrypt it.

Copying of materials is allowed only with the indication of the author (Mikhail Rusakov) and an indexed direct link to the site (http://myrusakov.ru)!

Add to my friends VK: http://vk.com/myrusakov.
If you want to rate me and my work, then write it in my group: http://vk.com/rusakovmy.

If you do not want to miss new materials on the site,
then you can subscribe to updates: Subscribe to updates

If you still have any questions, or you have a desire to comment on this article, then you can leave your comment at the bottom of the page.

If you liked the site, then post a link to it (on your site, on the forum, in contact):

Related Posts

Property Management in Dubai: Effective Rental Strategies and Choosing a Management Company

“Property Management in Dubai: Effective Rental Strategies and Choosing a Management Company” In Dubai, one of the most dynamically developing regions in the world, the real estate…

In Poland, an 18-year-old Ukrainian ran away from the police and died in an accident, – media

The guy crashed into a roadside pole at high speed. In Poland, an 18-year-old Ukrainian ran away from the police and died in an accident / illustrative…

NATO saw no signs that the Russian Federation was planning an attack on one of the Alliance countries

Bauer recalled that according to Article 3 of the NATO treaty, every country must be able to defend itself. Rob Bauer commented on concerns that Russia is…

The Russian Federation has modernized the Kh-101 missile, doubling its warhead, analysts

The installation of an additional warhead in addition to the conventional high-explosive fragmentation one occurred due to a reduction in the size of the fuel tank. The…

Four people killed by storm in European holiday destinations

The deaths come amid warnings of high winds and rain thanks to Storm Nelson. Rescuers discovered bodies in two separate incidents / photo ua.depositphotos.com Four people, including…

Egg baba: a centuries-old recipe of 24 yolks for Catholic Easter

They like to put it in the Easter basket in Poland. However, many countries have their own variations of “bab”. The woman’s original recipe is associated with…

Leave a Reply

Your email address will not be published. Required fields are marked *