一、准备工作
1.1安装基于windows平台的zbar软件和依赖环境
zbar-0.10-setup.exe
vcredist_x64.exe
可自行百度下载
ps:vcredist_x64.exe就是用来安装这些运行时库的。当我们安装一些使用MSVC开发的软件时,这些软件可能会依赖于某些特定版本的Visual C++运行时库。如果这些运行时库没有被正确地安装到系统中,那么这些软件就可能无法正常运行。
1.2安装需要的包
pyzbar pillow opencv-pyhton
安装方式一:
在pycharm的设置中找到以下位置:点击+号搜索相关的包 ,安装即可:
File | Settings | Project: pythonProject | Python Interpreter
安装方式二:
命令行Terminal安装:
pip install pyzbar
pip install pillow
pip install opencv-python
要是安装速度太慢,可以切换清华源并跟新pip版本:
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
python -m pip install --upgrade pip
二、代码编写
2.1普通功能实现
import pyzbar.pyzbar as pyzbar
from PIL import Image
import os,shutil,re
def read_barcode(picture):
# 打开图片
image = Image.open(picture)
# 使用pyzbar读取条形码
decoded_objects = pyzbar.decode(image)
# 打印条形码内容
for obj in decoded_objects:
barcodeData = obj.data.decode('utf-8')
return barcodeData
# 如果需要获取条形码的其他信息,如边界坐标等,可以使用以下代码
# point1 = obj.polygon[0]
# point2 = obj.polygon[1]
# point3 = obj.polygon[2]
# point4 = obj.polygon[3]
# print(point1, point2, point3, point4)
pyzbar.decode(image)
由于图片中可能出现多个二维码,所以这里decode得到的是一个list,需要遍历得到其中内容。
2.2功能优化
由于发现二维码的识别率和速度有点慢,所以要先对图片加工一下:
使用openCV可以对图片进行灰度处理,经过灰度处理后的图片识别率和速度都有一定的提升。
除了 灰度处理,还有其他各种类型的处理,可以自行搜索学习!
def decodeQRcode(image_filepath):
# 读取图像
image = cv2.imread(image_filepath)
# 转换图像到灰度 !!!!图片路径不能是中文,不然会报错
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 自定义对比度增强(例如,增加50%对比度)
alpha = 1.5
beta = 0
enhanced_gray = cv2.convertScaleAbs(gray, alpha=alpha, beta=beta)
# 解码图像中的二维码
decoded_objects = pyzbar.decode(enhanced_gray,symbols=[ZBarSymbol.QRCODE])
list_text = []
# 遍历解码结果
for obj in decoded_objects:
# 提取二维码的位置、数据
# x, y, w, h = obj.rect
# cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)
# print(obj)
text = obj.data.decode('utf-8')
# print("text",text)
list_text.append(text)
# cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# 设置新的尺寸,例如宽度和高度都设置为300
new_width = 800
new_height = 600
# 调整图像大小
resized_image = cv2.resize(enhanced_gray, (new_width, new_height), interpolation=cv2.INTER_AREA)
# 显示图像
# cv2.imshow('Image with QR code', resized_image)
# 显示图像
# cv2.imshow('Image with QR code', enhanced_gray)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
return list_textv