这个基于YOLOv12的条形码检测系统是我最近完成的一个很有意思的计算机视觉项目。作为一个经常需要处理商品条码的开发者,我一直在寻找一个既能保证高准确率又能实时运行的解决方案。经过多次尝试和优化,最终基于最新的YOLOv12算法实现了这个系统,在实际测试中达到了99%以上的检测准确率。
系统最突出的特点是它的完整性和易用性。从数据采集标注、模型训练到最终的应用部署,我构建了一个端到端的解决方案。特别是加入了PyQt5开发的图形界面后,使得这个深度学习模型能够真正落地应用,即使是没有编程背景的用户也能轻松使用。
系统采用典型的前后端分离架构:
选择YOLOv12作为基础算法主要基于以下几点考虑:
为了训练出鲁棒的检测模型,我收集了超过5000张包含条码的图片,覆盖了各种常见场景:
使用LabelImg工具进行标注,保存为YOLO格式。标注时特别注意以下几点:
数据集目录结构如下:
code复制数据集/
├── images/
│ ├── train/
│ ├── val/
│ └── test/
└── labels/
├── train/
├── val/
└── test/
为了提升模型泛化能力,采用了多种数据增强技术:
建议使用以下环境配置:
bash复制# 创建conda环境
conda create -n yolov12 python=3.9
conda activate yolov12
# 安装PyTorch (根据CUDA版本选择)
pip install torch torchvision torchaudio
# 安装其他依赖
pip install ultralytics opencv-python pyqt5
使用Ultralytics提供的YOLO接口进行训练:
python复制from ultralytics import YOLO
# 加载预训练模型
model = YOLO('yolov12s.pt')
# 训练配置
results = model.train(
data='data.yaml',
epochs=100,
batch=8,
imgsz=640,
device='0', # 使用GPU
workers=4,
project='runs',
name='exp'
)
关键训练参数说明:
batch: 根据GPU显存调整,8GB显存建议batch=8imgsz: 输入图像尺寸,越大精度可能越高但速度越慢workers: 数据加载线程数,建议设为CPU核心数的1/2训练完成后,主要关注以下指标:
在我的测试中,yolov12s模型在验证集上达到了:
使用PyQt5设计了用户友好的界面,主要包含以下功能区域:
界面设计采用了深色主题,减少长时间使用的视觉疲劳,同时加入了科技感的视觉效果:
python复制# 示例:自定义按钮样式
button_style = """
QPushButton {
border: 1px solid #2ecc71;
border-radius: 5px;
color: white;
padding: 5px;
background-color: rgba(46, 204, 113, 0.2);
}
QPushButton:hover {
background-color: rgba(46, 204, 113, 0.4);
border: 1px solid #2ecc71;
box-shadow: 0 0 5px #2ecc71;
}
"""
为了保证界面流畅性,将检测任务放在独立线程中执行:
python复制class DetectionThread(QThread):
frame_received = pyqtSignal(np.ndarray, np.ndarray, list)
def __init__(self, model, source, conf, iou):
super().__init__()
self.model = model
self.source = source
self.conf = conf
self.iou = iou
self.running = True
def run(self):
cap = cv2.VideoCapture(self.source) if isinstance(self.source, int) else self.source
while self.running:
ret, frame = cap.read()
if not ret: break
# 执行检测
results = self.model(frame, conf=self.conf, iou=self.iou)
annotated = results[0].plot()
# 提取检测结果
detections = []
for box in results[0].boxes:
cls = self.model.names[int(box.cls)]
conf = float(box.conf)
x, y = box.xywh[0][:2].tolist()
detections.append((cls, conf, x, y))
# 发送结果
self.frame_received.emit(frame, annotated, detections)
cap.release()
python复制def detect_image(self):
file_path, _ = QFileDialog.getOpenFileName(
self, "选择图片", "", "图片文件 (*.jpg *.jpeg *.png *.bmp)")
if file_path:
# 初始化检测线程
self.detection_thread = DetectionThread(
model=self.model,
source=file_path,
conf=self.confidence_spinbox.value(),
iou=self.iou_spinbox.value()
)
self.detection_thread.frame_received.connect(self.update_results)
self.detection_thread.start()
python复制def detect_video(self):
file_path, _ = QFileDialog.getOpenFileName(
self, "选择视频", "", "视频文件 (*.mp4 *.avi *.mov)")
if file_path:
# 初始化视频写入器
cap = cv2.VideoCapture(file_path)
fps = cap.get(cv2.CAP_PROP_FPS)
size = (int(cap.get(3)), int(cap.get(4)))
cap.release()
# 创建输出视频
save_path = f"results/output_{time.strftime('%Y%m%d_%H%M%S')}.mp4"
self.video_writer = cv2.VideoWriter(
save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, size)
# 启动检测线程
self.detection_thread = DetectionThread(
model=self.model,
source=file_path,
conf=self.confidence_spinbox.value(),
iou=self.iou_spinbox.value()
)
self.detection_thread.frame_received.connect(self.update_results)
self.detection_thread.start()
python复制def detect_camera(self):
# 默认使用第一个摄像头
self.detection_thread = DetectionThread(
model=self.model,
source=0, # 摄像头设备号
conf=self.confidence_spinbox.value(),
iou=self.iou_spinbox.value()
)
self.detection_thread.frame_received.connect(self.update_results)
self.detection_thread.start()
系统提供了灵活的检测参数调整:
参数调整通过信号槽机制实时生效:
python复制# 置信度阈值调整
self.confidence_slider.valueChanged.connect(
lambda v: self.confidence_spinbox.setValue(v/100.0))
self.confidence_spinbox.valueChanged.connect(
lambda v: self.confidence_slider.setValue(int(v*100)))
检测漏检:
误检率高:
推理速度慢:
系统可以部署在多种平台上:
bash复制git clone https://github.com/your-repo/barcode-detection-system.git
cd barcode-detection-system
bash复制pip install -r requirements.txt
bash复制wget https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov12s.pt
bash复制python main.py
这个基础系统还可以进一步扩展:
在实际使用中,我发现系统对倾斜角度超过45度的条码检测效果还有提升空间,下一步计划通过增加更多旋转增强的训练数据来改善这一点。另外,在极低光照条件下的性能也需要进一步优化,可能会尝试添加专门的图像增强预处理模块。