1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】QRコードを読み取ってブラウザで開く方法

1
Posted at

はじめに

本記事では、Pythonを使ってQRコードを読み込み、
含まれているURLをブラウザで開く方法をまとめます。

前回のQRコード作成記事の続編として、
読み込み〜ブラウザ起動の流れをまとめました。


1. 必要なライブラリのインストール

pip install opencv-python pyzbar pillow
ライブラリ 用途
opencv-python 画像処理・カメラ読み込み
pyzbar QRコード・バーコードのデコード
pillow 画像ファイルの読み込み

Windowsでpyzbarを使う場合、別途ZBarのDLLが必要です。
以下からダウンロードして配置してください。

pip install pyzbarでインストール後、
エラーが出た場合はpyzbar[pyzbar]を試してください。


2. 画像ファイルからQRコードを読み込む

import webbrowser
from PIL import Image
from pyzbar.pyzbar import decode


def read_qrcode_from_image(image_path: str) -> list[str]:
    """画像ファイルからQRコードを読み込んでデータを返す"""
    img = Image.open(image_path)
    decoded_objects = decode(img)

    results = []
    for obj in decoded_objects:
        data = obj.data.decode("utf-8")
        results.append(data)

    return results


def open_url_from_qrcode(image_path: str) -> None:
    """QRコードのURLをブラウザで開く"""
    results = read_qrcode_from_image(image_path)

    if not results:
        print("QRコードが見つかりませんでした。")
        return

    for data in results:
        print(f"読み込んだデータ: {data}")

        # URLの場合はブラウザで開く
        if data.startswith("http://") or data.startswith("https://"):
            print(f"ブラウザで開きます: {data}")
            webbrowser.open(data)
        else:
            print(f"URLではないデータ: {data}")


if __name__ == "__main__":
    open_url_from_qrcode("qrcode.png")

3. カメラからリアルタイムでQRコードを読み込む

import webbrowser
import cv2
from pyzbar.pyzbar import decode


def read_qrcode_from_camera() -> None:
    """カメラからリアルタイムでQRコードを読み込んでブラウザで開く"""
    cap = cv2.VideoCapture(0)  # 0=デフォルトカメラ

    if not cap.isOpened():
        print("カメラを開けませんでした。")
        return

    print("QRコードをカメラにかざしてください。")
    print("終了するには 'q' を押してください。")

    opened_urls = set()  # 同じURLを複数回開かないようにする

    while True:
        ret, frame = cap.read()
        if not ret:
            break

        # QRコードをデコード
        decoded_objects = decode(frame)

        for obj in decoded_objects:
            data = obj.data.decode("utf-8")

            # QRコードの位置に枠を描画
            points = obj.polygon
            if len(points) == 4:
                pts = [(p.x, p.y) for p in points]
                for i in range(4):
                    cv2.line(frame, pts[i], pts[(i + 1) % 4], (0, 255, 0), 2)

            # データをフレームに表示
            cv2.putText(
                frame, data[:50], (10, 30),
                cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2
            )

            # 新しいURLの場合のみブラウザで開く
            if data not in opened_urls:
                opened_urls.add(data)
                print(f"検出: {data}")
                if data.startswith("http://") or data.startswith("https://"):
                    webbrowser.open(data)

        cv2.imshow("QRコードリーダー", frame)

        if cv2.waitKey(1) & 0xFF == ord("q"):
            break

    cap.release()
    cv2.destroyAllWindows()


if __name__ == "__main__":
    read_qrcode_from_camera()

4. URLの種類別に処理を分ける

import webbrowser
import subprocess
from PIL import Image
from pyzbar.pyzbar import decode


def process_qrcode_data(data: str) -> None:
    """QRコードのデータ種別に応じて処理を分ける"""
    print(f"読み込んだデータ: {data}")

    if data.startswith("http://") or data.startswith("https://"):
        # URLはブラウザで開く
        print("URLをブラウザで開きます")
        webbrowser.open(data)

    elif data.startswith("TEL:"):
        # 電話番号を表示
        tel = data.replace("TEL:", "")
        print(f"電話番号: {tel}")

    elif data.startswith("mailto:"):
        # メールを開く
        print("メールクライアントで開きます")
        webbrowser.open(data)

    elif data.startswith("WIFI:"):
        # WiFi情報を表示
        print(f"WiFi情報: {data}")

    else:
        # その他はテキストとして表示
        print(f"テキスト: {data}")


if __name__ == "__main__":
    img = Image.open("qrcode.png")
    decoded_objects = decode(img)

    if not decoded_objects:
        print("QRコードが見つかりませんでした。")
    else:
        for obj in decoded_objects:
            data = obj.data.decode("utf-8")
            process_qrcode_data(data)

まとめ

用途 方法
画像から読み込む PIL + pyzbar
カメラから読み込む OpenCV + pyzbar
ブラウザで開く webbrowser.open(url)
URL以外の処理 データの先頭文字列で判定
重複防止 set()で開済みURLを管理
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?