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):