PythonとUSBカメラで実現するRaspberry PiのQRコード作成・読み取り方法

はじめに

Raspberry Piを使ってQRコードを活用するプロジェクトを紹介します。本記事では、USBカメラでのQRコード読み取りも含め、以下の2つの機能を実装します。

  1. QRコードを複数作成する
  2. USBカメラでQRコードを読み取り、対応するプログラムを実行する

簡単に操作を切り替えられるシステムを作ることができ、リモート操作や自動化にも応用できます。

QRコードの作成

まず、QRコードを作成します。

必要なライブラリをインストールします。

pip install qrcode opencv-python pyzbar

上記でうまくいかない場合は以下を試してください

sudo apt install python3-opencv

以下のコードを実行すると、**.pngのQRコード画像が生成できます。
スマホでも読み取ることができますので、ぜひやってみてください。

import qrcode

def create_qr_code(data, filename):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data(data)
    qr.make(fit=True)
    
    img = qr.make_image(fill='black', back_color='white')
    img.save(filename)
    print(f"save QRcode: {filename}")

commands = {
    "ohayou": "qr_script1.png",
    "konnichiha": "qr_script2.png",
    "konbanha": "qr_script3.png",
}

for script, filename in commands.items():
    create_qr_code(script, filename)

QRコードをUSBカメラで読み取り、プログラムを実行する

次に、QRコードをUSBカメラで読み取り、対応するスクリプトを実行するプログラムを作成します。
今回はQRコードから文字列が読み取れますので、それに対応した文字列を返します。

import cv2
import numpy as np
from pyzbar.pyzbar import decode

def respond_to_qr(message):
    responses = {
        "ohayou": "morning",
        "konnichiha": "afternoon",
        "konbanha": "evening"
    }
    return responses.get(message, "Unknown QR code")

def read_qr_code():
    cap = cv2.VideoCapture(0)  # Open camera
    print("Scan a QR code...")
    
    while True:
        ret, frame = cap.read()
        if not ret:
            continue
        
        decoded_objects = decode(frame)
        for obj in decoded_objects:
            message = obj.data.decode("utf-8")
            print(f"QR code detected: {message}")
            
            # Respond based on QR code content
            response = respond_to_qr(message)
            print(f"Response: {response}")
            
            cap.release()
            cv2.destroyAllWindows()
            return
        
        cv2.imshow("QR Code Scanner", frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()


read_qr_code()

まとめ

今回はQRコードの作成とQRコードの読み取り方を紹介しました。
QRコードを読みった後の振る舞いは色々考えられると思いますのでぜひ工夫して活用してみてください!

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

コメント

コメントする