Language - Python(Opencv)

Python Opnecv - pyzbar 라이브러리

KimTory 2022. 1. 12. 15:19

IDE → Visual Code 

라이브러리 → Opencv 4.7, pyzbar, numpy

 

import pyzbar.pyzbar as pyzbar

import numpy as np
import cv2

def decode(im):
    decodedObjects = pyzbar.decode(im)

    for obj in decodedObjects:
        print("Type", obj.type)
        print("Data", obj.data, "\n")

    return decodedObjects

def display(im, decodedObjects):

    // cv2.rectangle 방식
    for decodedObject in decodedObjects:
        x,y,w,h = decodedObject.rect

        barcode_info = decodedObject.data.decode("utf-8")

        cv2.rectangle(im, (x, y), (x + w, y + h), (0, 0, 255), 2)
        cv2.putText(im, barcode_info, (x , y - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)

    cv2.imshow("Results", im)
    cv2.waitKey(0)
    
    // cv2.line 방식
    // for decodedObject in decodedObjects:
    //     points = decodedObject.polygon

    //     if len(points) > 4:
    //         hull = cv2.convexHull(np.array([point for point in points], dtype=np.float32))
    //         hull = list(map(tuple, np.squeeze(hull)))
    //     else:
    //         hull = points;

    //    n = len(hull)

    //    for j in range(0, n):
    //        cv2.line(im, hull[j], hull[(j + 1) % n], (255, 0, 0), 1)

    cv2.imshow("Results", im)
    cv2.waitKey(0)


if __name__=="__main__":

    im = cv2.imread("d:\\Systemdata\\zbar.jpg")
    cv2.imshow("Display", im)
    decodedObjects = decode(im)

    display(im, decodedObjects)

바코드 결과 / 원본 이미지