Python-条形码和二维码识别

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")

以下的是可以识别的

img001

img002

但是码和数字中间没有分割的识别会有问题

image-20250208115119531

OpenCV读取识别

加载图片

1
2
3
4
5
def read_img(filename, mode=cv2.IMREAD_COLOR):
# 先用numpy把图片文件存入内存:raw_data,把图片数据看做是纯字节数据
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):
# 先用numpy把图片文件存入内存:raw_data,把图片数据看做是纯字节数据
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 ""