Ask Your Question

Revision history [back]

I Figured out a way to do it!

image description

Reading through the documentation for PyQRCode, I found that there is the option to export the QR code as text. From there I was able to write it to a numpy array. Hopefully someone finds this helpful in the future.

import cv2
import pyqrcode
import numpy as np
import datetime
import math

image = cv2.imread('chain.jpg', )

timestamp = str(datetime.datetime.now())

# Make the QR Code (CSV) - These values are populated by the inspection process
temp_qrcode = pyqrcode.create(filename+','+timestamp+','+result)

# Convert the QR Code to a string
temp_qrcode = temp_qrcode.text()

# Remove all instances of "Newline" from string
temp_qrcode = temp_qrcode.replace('\n', '')

# Get the total number of pixels (characters) from the QR Code string
size = len(temp_qrcode)

# The QRcode is square, square root of the size will give us image dimensions.
shape = int(math.sqrt(size))

# Create a numpy array that will become our QR Code image
qr = np.zeros([shape, shape], dtype='uint8')


# Set counters for iteration.
row = column = 0

for char in temp_qrcode:
    if char == '0':
        qr[row][column] = 255
        column = column + 1

    if char == '1':
        qr[row][column] = 0
        column = column + 1

    if column == shape:
        row = row + 1
        column = 0

# Scale up the QR code.
qr = cv2.resize(qr, (100, 100), fx=0, fy=0, interpolation=cv2.INTER_LANCZOS4)

# Apply border to QR code
qr = cv2.copyMakeBorder(qr, 2, 2, 2, 2, cv2.BORDER_CONSTANT, value=0)

# Overlay the QR Code onto the
x_offset = y_offset = 0
image[y_offset:y_offset+stamp.qr[0], x_offset:x_offset+qr.shape[1]] = qr

cv2.imwrite(filename, image)