物理の駅 Physics station by 現役研究者

テクノロジーは共有されてこそ栄える

Python+OpenCV+pyzbarでQRコードを読み取ってみる

取り急ぎ、Windows PCでQRコードを読み込みたい需要があったので、書いてみた。QRコードをデコードするコードは下記のqiitaを丸パクリした。

qiita.com

import cv2
from pyzbar import pyzbar
import subprocess

# デバイス上でのウェブカメラを取得
cap = cv2.VideoCapture(1)

# Windows 10 の設定
chrome_path = r'"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"'

while True:
    ret, frame = cap.read()
    height, width, channels = frame.shape 
    size = int(min(width,height) * 0.2)
    height = height // 2
    width = width // 2

    #赤線で囲む
    frame = cv2.rectangle(frame,(width - size,height - size),(width + size,height + size),(0,0,255),3)

    # 赤線内を切り抜く(トリミング)
    size -= 5
    new_frame = frame[height - size:height + size,width - size:width + size]

    cv2.imshow("QR1",frame)
    #デバッグ用
    #cv2.imshow("QR2",new_frame)
    decoded_objs = pyzbar.decode(new_frame)

    #データがあれば
    if decoded_objs != []:
        str_dec_obj = decoded_objs[0][0].decode('utf-8', 'ignore')
        print(f'QR cord: {str_dec_obj}')

        if len(str_dec_obj) > 4 and "http" == str_dec_obj[0:4]:
            #URLの場合はchromeで開く
            command = f'{chrome_path} {str_dec_obj}'
            print(command)
            result = subprocess.run(command, shell=True)
        else:
            #URL以外の場合は検索で開く
            command = f'{chrome_path} https://www.google.com/search?q={str_dec_obj}'
            print(command)
            result = subprocess.run(command, shell=True)

        #リソースのリリース
        cap.release()
        cv2.destroyAllWindows()
        break
    #100msecの待機
    cv2.waitKey(100)

自身のラップトップ(Surface book 2)だと、前面カメラ(0)ではコードが認識せず、背面カメラ(1)でのみ認識した。原因は深く追求していない。