pyzbar
安装依赖
1 2
| pip install pyzbar pip install Pillow
|
Pillow读取识别
识别代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| from PIL import Image from pyzbar.pyzbar import decode
def read_barcode(image_path): image = Image.open(image_path) image = image.convert("L") barcodes = decode(image) print(f"Found {len(barcodes)} barcodes!") for barcode in barcodes: print(f"Type: {barcode.type}") barcode_data = barcode.data.decode("utf-8") print(f"Data: {barcode_data}")
read_barcode(r"D:\ImageRes\img001.png")
|
以下的是可以识别的
但是码和数字中间没有分割的识别会有问题
OpenCV读取识别
加载图片
1 2 3 4 5
| def read_img(filename, mode=cv2.IMREAD_COLOR): raw_data = np.fromfile(filename, dtype=np.uint8) img = cv2.imdecode(raw_data, mode) return img
|
OpenCV加载图片后数据格式为numpy.ndarray
也是可以直接传入的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import cv2 import numpy as np from pyzbar.pyzbar import decode
def read_img(filename, mode=cv2.IMREAD_COLOR): raw_data = np.fromfile(filename, dtype=np.uint8) img = cv2.imdecode(raw_data, mode) return img
def read_barcode(image_path): image = read_img(image_path) barcodes = decode(image) print(f"Found {len(barcodes)} barcodes!") for barcode in barcodes: print(f"Type: {barcode.type}") barcode_data = barcode.data.decode("utf-8") print(f"Data: {barcode_data}")
read_barcode(r"D:\ImageRes\img001.png")
|
工具类
1 2 3 4 5 6 7 8 9 10
| import numpy as np from pyzbar.pyzbar import decode
def read_barcode(image: np.ndarray) -> str: barcodes = decode(image) if len(barcodes) > 0: return barcodes[0].data.decode("utf-8") else: return ""
|