본문 바로가기
Raspberry Pi

[RaspberryPi/Python] QR코드 인식 및 텍스트 추출

by ewaterland 2023. 11. 16.

라즈베리파이에서 QR코드 인식을 하기 위해 작성한 Python 코드.

 

1. 필요한 라이브러리

아래의 라이브러리 2개가 필요하다. 터미널에서 설치해주면 된다!

pip install opencv-python
pip install pyzbar

 

2. Python 코드

나는 로봇의 위치 정보를 저장하기 위해 좌표가 필요해서 x,y 텍스트를 추출하는 코드를 작성했다.

아래의 코드에는 불필요한 정보를 제외하고, QR코드를 인식한 후에 텍스트를 추출하는 부분만 작성하였음!

QR코드는 사진으로 올려도 되겠지만, 여기서는 카메라가 켜진다.

import cv2
from pyzbar.pyzbar import decode

print("실행 중...")

def read_qr():
    cap = cv2.VideoCapture(0)

    while True:
        ret, frame = cap.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        decoded_objects = decode(gray)

        for obj in decoded_objects:
            points = obj.polygon
            if len(points) > 4:
                hull = cv2.convexHull(points, clockwise=True)
                cv2.polylines(frame, [hull], True, (0, 255, 0), 2)

            qr_text = obj.data.decode("utf-8")  # 추출한 text를 담는 변수

            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.putText(frame, qr_text, (points[0][0], points[0][1]), font, 0.8, (0, 255, 0), 2, cv2.LINE_AA)

        cv2.imshow('QR Code Reader', frame)

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

    cap.release()
    cv2.destroyAllWindows()

read_qr()