利用pyzbar和zxing进行条形码解析

1.安装环境:
apt-get install zbar-tools

apt-get install python-jpype

pip install pyzbar

pip install zxing

2.代码案例 

#coding:utf-8
import pyzbar.pyzbar as pyzbar
import time
import shutil
import zxing
import cv2

def parse_code(codeimg, reader):
    """
    输入矫正过的条形码图片输出解析结果
    :param codeimg: 矫正过的条形码图片
    :return: 条形码解析结果
    """
    gray = cv2.cvtColor(codeimg, cv2.COLOR_BGR2GRAY)
    gray_h, gray_w = gray.shape
    barcodes1 = pyzbar.decode(gray)
    # barcodes2 = pyzbar.decode(np.rot90(np.rot90(gray)))
    # print('==barcodes2:', barcodes2)
    def parse_results(barcode):
        # for barcode in barcodes:
        # 提取条形码的位置
        # (x, y, w, h) = barcode.rect
        # 字符串转换
        barcodeData = barcode.data.decode("utf-8")
        return barcodeData

    if len(barcodes1):
        barcodeData = parse_results(barcodes1[0])
        if len(barcodeData) >= 10:#条形码位数大于10位
            return barcodeData
    else:


        if gray_h>gray_w:
            cv2.imwrite('./out_clip.jpg', np.rot90(codeimg)[...,::-1])
        else:
            cv2.imwrite('./out_clip.jpg', codeimg[...,::-1])
        barcode = reader.decode('./out_clip.jpg')
        # print('==barcode:', barcode)
        try:
            return barcode.raw
        except:
            return None

def debug_parse_code():
    reader = zxing.BarCodeReader()
    path = './5.png'
    img = cv2.imread(path)
    code_res = parse_code(img, reader)
    print('==code_res:', code_res)

if __name__ == '__main__':
    debug_parse_code()

你可能感兴趣的:(OCR,条形码解析)