Outils pour utilisateurs

Outils du site


diy:projets:qrdeciphering

Introduction

The goal of this program is to detect and decipher one or several QR codes in a picture.

Required Libraries

In order to decipher QR codes, we will use the zbarlight library, installed (on Debian) as follows:
apt-get install libzbar0 libzbar-dev
pip install zbarlight
We will also use a number of standard Python libraries.

 from PIL import Image
 import zbarlight
 from subprocess import Popen, PIPE
 import sys
 import datetime

Explanation

The program allows exactly one argument: the IP address of the Raspberry Pi whose camera we're going to be using.
To avoid any issue, we check that it is a valid IP address with the following function:

 def isValidIPV4(adr):
   nums = adr.split('.')
   if len(nums) != 4:
       return False
   try:
       return all(0 <= int(num) < 256 for num in nums)
   except ValueError:
       return False

If the right argument was given, we can remote into the pi to take a picture. To do so, we use subprocess.Popen() to run the following command with the given ip:
ssh -t pi@<ip> “raspistill -hf -vf -o <nom_fichier> –nopreview –timeout 10”
To avoid conflict with an already existing picture, we put the date and time in the new picture's name.

 if (len(sys.argv) == 2 and isValidIPV4(sys.argv[1])):
    filename = 'qrcodereader_' + datetime.datetime.now().strftime("%Y-%m-%d-%H:%M:%S") + '.jpg'
 
    print("Taking picture...")
    command = ['ssh', '-t', 'pi@' + sys.argv[1], "raspistill -hf -vf -o " + filename + " --nopreview --timeout 10"]
    x = Popen(command, stdout=PIPE, stderr=PIPE)
    stderr = x.stderr.read()
    print stderr

We then import the resulting image over ssh using the rsync command.

    print("Importing...")
    command = ['rsync', '-avz', '--ignore-existing', '--remove-source-files', 'pi@' + sys.argv[1] + ':~/' + filename, '/home/silver/BE/' + filename]
    x = Popen(command, stdout=PIPE, stderr=PIPE)
    stderr = x.stderr.read()
    print stderr

We now simply use zbarlight to decode any and all QR codes fully visible on the picture. We only need to open and load the image, before applying the scan_codes function.

    file_path = './' + filename
    with open(file_path, 'rb') as image_file:
        image = Image.open(image_file)
        image.load()
 
    code = zbarlight.scan_codes('qrcode', image)
    print('QR codes: %s' % code)

The program outputs a full list of all deciphered QR codes.

diy/projets/qrdeciphering.txt · Dernière modification : 2018/05/23 13:56 de ycaminade