1. 工业视觉检测系统核心代码解析
在工业自动化领域,C#上位机结合YOLO目标检测的解决方案已经成为质量检测的主流技术方案。这套代码经过多个实际工业项目的验证,特别针对产线环境中的常见需求进行了优化设计。
1.1 缺陷图像处理模块
缺陷图像保存是视觉检测系统的基础功能,但直接保存全图会浪费存储空间且不利于后续分析。这套代码实现了智能保存策略:
csharp复制private async Task SaveDefectIfNeeded(Mat frame, List<Detection> detections)
{
// 置信度阈值过滤
if (!detections.Any(d => d.Conf > 0.6f)) return;
// 保存频率控制(3秒间隔)
var now = DateTime.Now;
if (now - lastSaveTime < minSaveInterval) return;
lastSaveTime = now;
// 带标注的全图保存
using var annotated = frame.Clone();
foreach (var d in detections) {
Cv2.Rectangle(annotated, d.Box, Scalar.Red, 2);
Cv2.PutText(annotated, $"{d.Label} {d.Conf:F2}",
new Point(d.BBox.X, d.BBox.Y - 10),
HersheyFonts.HersheySimplex, 0.7, Scalar.Red, 2);
}
string fullPath = Path.Combine("Defects", $"{timestamp}_full.jpg");
annotated.ImWrite(fullPath);
// ROI区域裁剪保存
int idx = 1;
foreach (var d in detections) {
// 边界安全检查
int x = Math.Max(0, d.Box.X);
int y = Math.Max(0, d.Box.Y);
int w = Math.Min(d.BBox.Width, frame.Width - x);
int h = Math.Min(d.BBox.Height, frame.Height - y);
if (w <= 0 || h <= 0) continue;
using var roi = new Mat(frame, new Rect(x, y, w, h));
string roiPath = Path.Combine("Defects",
$"{timestamp}_roi{idx}_{d.Label}_{d.Conf:F2}_{w}x{h}.jpg");
roi.ImWrite(roiPath);
idx++;
}
}
实际项目中发现的问题:当检测到多个相邻缺陷时,ROI区域可能出现重叠。建议在保存前先进行NMS非极大值抑制处理。
1.2 PLC通信安全机制
工业现场PLC通信的稳定性直接影响系统可靠性。这段代码实现了带
