import cv2
from pyzbar import pyzbar
 
def decode_barcode(pic):
    # 读取图像
    image = cv2.imread(pic)
    # 将图像转换为灰度图
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # 显示灰度图像  
    cv2.imshow('Gray Image', gray)  
    cv2.waitKey(0)  
    cv2.destroyAllWindows()
    # 使用pyzbar解码条码
    barcodes = pyzbar.decode(gray)
 
    # 遍历解码结果
    for barcode in barcodes:
        # 提取条码的边界框坐标
        (x, y, w, h) = barcode.rect
 
        # 在图像上绘制条码的边界框
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
 
        # 提取条码的数据
        barcode_data = barcode.data.decode("utf-8")
        barcode_type = barcode.type
 
        # 在图像上绘制条码的数据和类型
        text = "{} ({})".format(barcode_data, barcode_type)
        cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
 
        # 打印条码的数据和类型
        print("[INFO] Found barcode: {}, {}".format(barcode_data, barcode_type))
 
    # 显示图像(可选)
    cv2.imshow('Gray image', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
 

 
# 调用条码识别函数
decode_barcode('128a.png')

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐