项目定位与目标

机器视觉是上位机开发中含金量最高的方向之一。本项目用文件夹图片(或笔记本摄像头)模拟产线来料,做一个完整的”来料检测”小工具:取图 → 检测流程引擎(找直线、找圆、尺寸判定)→ OK/NG 判定与结果叠加 → 良率统计与声音报警 → SQLite 检测记录。重点体会策略模式在检测流程上的架构价值——新增一种检测项只需新增一个实现类,不改引擎。

学习目标:

  • 掌握 OpenCvSharp4 在 WPF 中的集成与 Mat 显示
  • 用 IInspectionStep 接口加检测引擎组织可扩展的检测流程
  • 掌握霍夫找圆、霍夫找直线、Canny 边缘、尺寸公差判定的基础用法
  • 实现 OK/NG 叠加显示、良率统计、声音报警、检测结果落 SQLite

需求清单

编号 模块 需求描述
R01 图源 文件夹图片按序循环模拟来料;或摄像头 VideoCapture 实时取图
R02 流程引擎 策略模式串联检测步骤,任一步骤 NG 短路返回
R03 检测步骤 找直线、找圆、直径公差判定三个内置步骤
R04 结果叠加 检出目标画框(OK 绿框 / NG 红框),图上标注 OK/NG
R05 统计 总数、OK 数、NG 数、良率实时显示,NG 声音报警
R06 参数界面 曝光模拟(亮度偏移)、找圆与判定参数可调
R07 记录 每次检测写 SQLite:时间、图片路径、结果、失败原因、耗时

架构设计

技术选型:.NET 8 + WPF + OpenCvSharp4 + CommunityToolkit.Mvvm + Microsoft.Data.Sqlite + Dapper。创建与安装:

dotnet new wpf -n VisionTool -f net8.0
cd VisionTool
dotnet add package OpenCvSharp4
dotnet add package OpenCvSharp4.runtime.win
dotnet add package CommunityToolkit.Mvvm
dotnet add package Microsoft.Data.Sqlite
dotnet add package Dapper

目录结构:

VisionTool/
├── Models/InspectionResult.cs      步骤结果与检测报告
├── Services/                        图源接口与实现、MatConverter、SQLite 仓储
├── Inspections/                     步骤接口(策略模式核心)、三个步骤、检测引擎
├── ViewModels/MainViewModel.cs
└── Views/MainWindow.xaml

检测流程数据流:图源 Grab 出 Mat → 曝光模拟预处理 → 引擎按序执行步骤链(共享 InspectionContext)→ 汇总 InspectionReport → 画框叠加转 BitmapSource 显示 → 统计与落库。

分步实现

步骤1:图源管理

using OpenCvSharp;

namespace VisionTool.Services;

// 图源接口:统一"文件夹模拟来料"与"摄像头实拍"两种来源
public interface IImageSource : IDisposable
{
    string Name { get; }
    // 取下一帧,无可用帧时返回 null
    Mat? Grab();
}

// 文件夹图源:按文件名顺序循环播放,模拟产线来料
public sealed class FolderImageSource : IImageSource
{
    private readonly string[] _files;
    private int _index;
    // 当前帧路径:落库记录"可追溯的图片路径"用
    public string? CurrentPath { get; private set; }

    public FolderImageSource(string folder)
    {
        // 只收常见图片格式,排除隐藏文件等杂项
        var exts = new[] { ".jpg", ".jpeg", ".png", ".bmp" };
        _files = Directory.GetFiles(folder)
            .Where(f => exts.Contains(Path.GetExtension(f).ToLowerInvariant()))
            .OrderBy(f => f).ToArray();
    }

    public string Name => $"文件夹({_files.Length} 张)";
    public Mat? Grab()
    {
        if (_files.Length == 0) return null;
        CurrentPath = _files[_index % _files.Length];
        _index++;
        var mat = Cv2.ImRead(CurrentPath);
        return mat.Empty() ? null : mat;
    }
    public void Dispose() { }
}

// 摄像头图源:包装 VideoCapture,笔记本自带摄像头即可调试
public sealed class CameraImageSource : IImageSource
{
    private readonly VideoCapture _capture;

    public CameraImageSource(int cameraIndex = 0)
    {
        _capture = new VideoCapture(cameraIndex);
        if (!_capture.IsOpened())
            throw new InvalidOperationException("无法打开摄像头");
    }

    public string Name => "摄像头";
    public Mat? Grab()
    {
        var frame = new Mat();
        return _capture.Read(frame) && !frame.Empty() ? frame : null;
    }
    public void Dispose() => _capture.Release();
}

测试图片准备:找 20 张差异明显的图(机械零件、硬币、螺丝均可),一部分有清晰圆形轮廓、一部分没有,分别造 OK 与 NG 样本放入同一文件夹。

步骤2:检测流程引擎(策略模式)

using OpenCvSharp;

namespace VisionTool.Models;

// 检测上下文:步骤间共享中间结果,避免每个步骤重复找一遍
public class InspectionContext
{
    // 已找到的圆与直线,供后续尺寸判定等步骤使用
    public List<CircleSegment> Circles { get; } = new();
    public List<LineSegmentP> Lines { get; } = new();
}

// 单步骤执行结果
public class StepResult
{
    public required string StepName { get; init; }
    public bool Ok { get; init; }
    public string Message { get; init; } = "";
    // 检出区域,用于界面叠加画框
    public List<Rect> Regions { get; init; } = new();
}

// 整次检测报告
public class InspectionReport
{
    public bool IsOk { get; set; }
    public TimeSpan Duration { get; set; }
    public List<StepResult> Steps { get; } = new();
    public string FailReason => Steps.FirstOrDefault(s => !s.Ok)?.Message ?? "";
}

namespace VisionTool.Inspections;

// 检测步骤接口:策略模式,新增检测项只需新增实现类并挂到引擎
public interface IInspectionStep
{
    string Name { get; }
    StepResult Run(Mat image, InspectionContext ctx);
}

// 找圆步骤:霍夫圆变换
public sealed class FindCircleStep : IInspectionStep
{
    public string Name => "找圆";
    // 参数公开为属性,供界面绑定调节
    public int MinRadius { get; set; } = 30;
    public int MaxRadius { get; set; } = 300;
    public double AccumulatorThreshold { get; set; } = 50;

    public StepResult Run(Mat image, InspectionContext ctx)
    {
        using var gray = image.CvtColor(ColorConversionCodes.BGR2GRAY);
        using var blur = gray.MedianBlur(5);  // 中值滤波去噪,霍夫对噪声敏感
        var circles = Cv2.HoughCircles(blur, HoughModes.Gradient,
            dp: 1, minDist: 80, param1: 120, param2: AccumulatorThreshold,
            minRadius: MinRadius, maxRadius: MaxRadius);
        ctx.Circles.Clear();
        ctx.Circles.AddRange(circles);
        var result = new StepResult
        {
            StepName = Name,
            Ok = circles.Length > 0,
            Message = circles.Length > 0 ? $"找到 {circles.Length} 个圆" : "未找到圆"
        };
        foreach (var c in circles)
            result.Regions.Add(new Rect(
                (int)(c.Center.X - c.Radius), (int)(c.Center.Y - c.Radius),
                (int)(2 * c.Radius), (int)(2 * c.Radius)));
        return result;
    }
}

// 找直线步骤:Canny 边缘加概率霍夫变换
public sealed class FindLineStep : IInspectionStep
{
    public string Name => "找直线";
    public int Threshold { get; set; } = 60;
    public int MinLineLength { get; set; } = 80;

    public StepResult Run(Mat image, InspectionContext ctx)
    {
        using var gray = image.CvtColor(ColorConversionCodes.BGR2GRAY);
        using var edges = gray.Canny(50, 150);
        var segments = Cv2.HoughLinesP(edges, 1, Cv2.PI / 180,
            Threshold, MinLineLength, 10);
        ctx.Lines.Clear();
        ctx.Lines.AddRange(segments);
        var result = new StepResult
        {
            StepName = Name,
            Ok = segments.Length > 0,
            Message = segments.Length > 0 ? $"找到 {segments.Length} 条直线" : "未找到直线"
        };
        foreach (var s in segments)
            result.Regions.Add(new Rect(Math.Min(s.P1.X, s.P2.X), Math.Min(s.P1.Y, s.P2.Y),
                Math.Abs(s.P2.X - s.P1.X), Math.Abs(s.P2.Y - s.P1.Y)));
        return result;
    }
}

// 尺寸判定步骤:取最大圆做直径公差判断,演示步骤间通过上下文协作
public sealed class SizeJudgeStep : IInspectionStep
{
    public string Name => "直径判定";
    public double Nominal { get; set; } = 200;  // 名义直径(像素)
    public double Tolerance { get; set; } = 40; // 允许公差

    public StepResult Run(Mat image, InspectionContext ctx)
    {
        if (ctx.Circles.Count == 0)
            return new StepResult { StepName = Name, Ok = false, Message = "无圆可判定" };
        double diameter = ctx.Circles.Max(c => c.Radius) * 2;
        bool ok = Math.Abs(diameter - Nominal) <= Tolerance;
        return new StepResult
        {
            StepName = Name,
            Ok = ok,
            Message = $"直径 {diameter:F0}px,目标 {Nominal:F0}±{Tolerance:F0}"
        };
    }
}

// 检测引擎:按序执行步骤链,任一步骤 NG 短路返回
public sealed class InspectionEngine
{
    private readonly List<IInspectionStep> _steps = new();

    public InspectionEngine AddStep(IInspectionStep step)
    {
        _steps.Add(step);
        return this;
    }
    public InspectionReport Run(Mat image)
    {
        var report = new InspectionReport();
        var watch = System.Diagnostics.Stopwatch.StartNew();
        var ctx = new InspectionContext();
        foreach (var step in _steps)
        {
            var r = step.Run(image, ctx);
            report.Steps.Add(r);
            if (!r.Ok) break;  // 短路:前面失败,后续步骤没有执行意义
        }
        watch.Stop();
        report.Duration = watch.Elapsed;
        report.IsOk = report.Steps.All(s => s.Ok);
        return report;
    }
}

步骤3:Mat 显示转换与主 ViewModel

using System.Windows.Media;
using System.Windows.Media.Imaging;
using OpenCvSharp;

namespace VisionTool.Services;

// Mat 与 WPF 位图转换工具
public static class MatConverter
{
    // 统一转 BGRA 四通道后写像素,兼容 3 通道 BGR 与 4 通道来源
    public static BitmapSource ToBitmapSource(Mat mat)
    {
        using var bgra = mat.Channels() == 4
            ? mat.Clone()
            : mat.CvtColor(ColorConversionCodes.BGR2BGRA);
        var bmp = new WriteableBitmap(bgra.Width, bgra.Height, 96, 96, PixelFormats.Bgra32, null);
        bmp.WritePixels(new System.Windows.Int32Rect(0, 0, bgra.Width, bgra.Height),
            bgra.Data, (int)(bgra.Total() * bgra.ElemSize()), (int)bgra.Step());
        return bmp;
    }
}
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using OpenCvSharp;
using VisionTool.Inspections;
using VisionTool.Models;
using VisionTool.Services;

namespace VisionTool.ViewModels;

public partial class MainViewModel : ObservableObject
{
    private IImageSource? _source;
    private readonly InspectionEngine _engine;
    private readonly RecordRepository _repository = new();
    private readonly DispatcherTimer _autoTimer = new() { Interval = TimeSpan.FromSeconds(1.5) };

    [ObservableProperty] private ImageSource? _displayImage;
    [ObservableProperty] private bool _useCamera;
    [ObservableProperty] private string _folderPath = @"D:\imgs";
    [ObservableProperty] private bool _isAutoRun;
    [ObservableProperty] private int _totalCount;
    [ObservableProperty] private int _okCount;
    [ObservableProperty] private int _ngCount;
    [ObservableProperty] private string _lastResult = "待检测";
    [ObservableProperty] private ObservableCollection<string> _log = new();
    // 曝光模拟:-50 到 50 映射到 ConvertTo 的亮度偏移
    [ObservableProperty] private double _exposureSim;

    // 参数区:直接绑定步骤对象属性
    public FindCircleStep CircleStep { get; } = new();
    public SizeJudgeStep SizeStep { get; } = new();
    public string YieldText => TotalCount == 0 ? "--" : $"{(double)OkCount / TotalCount:P1}";

    public MainViewModel()
    {
        _repository.Init();
        _engine = new InspectionEngine()
            .AddStep(CircleStep)   // 步骤1:找圆
            .AddStep(SizeStep);    // 步骤2:直径判定
        _autoTimer.Tick += (_, _) => RunOnce();
    }
    partial void OnIsAutoRunChanged(bool value)
    {
        if (value) _autoTimer.Start(); else _autoTimer.Stop();
    }
    [RelayCommand]
    private void OpenSource()
    {
        try
        {
            _source?.Dispose();
            _source = UseCamera ? new CameraImageSource(0) : new FolderImageSource(FolderPath);
            Status($"图源就绪: {_source.Name}");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "图源打开失败");
        }
    }
    // 单次检测:取图、曝光模拟、引擎执行、叠加显示、统计落库
    [RelayCommand]
    private void RunOnce()
    {
        if (_source == null) { MessageBox.Show("请先打开图源"); return; }
        using var frame = _source.Grab();
        if (frame == null) { Status("无图可取"); return; }
        string imagePath = (_source as FolderImageSource)?.CurrentPath ?? "(摄像头帧)";

        // 曝光模拟:beta 为亮度偏移,alpha 固定 1.0
        using var prepared = new Mat();
        frame.ConvertTo(prepared, -1, 1.0, ExposureSim);

        var report = _engine.Run(prepared);

        // 叠加画框:OK 绿框,NG 红框,并在左上角标注总判定
        foreach (var step in report.Steps)
            foreach (var rect in step.Regions)
                Cv2.Rectangle(prepared, rect,
                    step.Ok ? new Scalar(0, 255, 0) : new Scalar(0, 0, 255), 2);
        Cv2.PutText(prepared, report.IsOk ? "OK" : "NG",
            new OpenCvSharp.Point(20, 40), HersheyFonts.HersheySimplex,
            1.2, report.IsOk ? new Scalar(0, 255, 0) : new Scalar(0, 0, 255), 2);
        DisplayImage = MatConverter.ToBitmapSource(prepared);

        // 统计与 NG 声音报警
        TotalCount++;
        if (report.IsOk) OkCount++;
        else { NgCount++; System.Media.SystemSounds.Hand.Play(); }
        OnPropertyChanged(nameof(YieldText));
        LastResult = report.IsOk ? "OK" : $"NG: {report.FailReason}";
        Status($"[{DateTime.Now:HH:mm:ss.fff}] {LastResult},耗时 {report.Duration.TotalMilliseconds:F0}ms");

        // 落库:记录时间、图片路径、结果、原因、耗时
        _repository.Insert(new DetectionRecord(
            DateTime.Now, imagePath, report.IsOk, report.FailReason,
            (int)report.Duration.TotalMilliseconds));
    }
    private void Status(string message)
    {
        Log.Insert(0, message);
        while (Log.Count > 200) Log.RemoveAt(Log.Count - 1);
    }
}

步骤4:检测参数界面与主界面 XAML

<Window x:Class="VisionTool.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="视觉检测小工具" Height="700" Width="1180">
    <DockPanel Margin="8">
        <!-- 顶部:图源与运行控制 -->
        <WrapPanel DockPanel.Dock="Top" Margin="0,0,0,8">
            <CheckBox Content="使用摄像头" IsChecked="{Binding UseCamera}" VerticalAlignment="Center"/>
            <TextBox Width="240" Text="{Binding FolderPath}" Margin="8,0,0,0"
                     ToolTip="图片文件夹路径,取消摄像头勾选时生效"/>
            <Button Content="打开图源" Command="{Binding OpenSourceCommand}" Margin="8,0,0,0" Padding="10,4"/>
            <Button Content="检测一次" Command="{Binding RunOnceCommand}" Margin="8,0,0,0"
                    FontWeight="Bold" Padding="10,4"/>
            <CheckBox Content="连续运行" IsChecked="{Binding IsAutoRun}" Margin="12,0,0,0" VerticalAlignment="Center"/>
            <TextBlock Text="{Binding LastResult}" Margin="20,0,0,0" VerticalAlignment="Center"
                       Foreground="Red" FontWeight="Bold"/>
        </WrapPanel>

        <!-- 右侧:参数与统计 -->
        <GroupBox DockPanel.Dock="Right" Width="260" Header="参数与统计">
            <StackPanel>
                <TextBlock Text="曝光模拟(亮度偏移)" Margin="0,6,0,2"/>
                <Slider Minimum="-50" Maximum="50" Value="{Binding ExposureSim}"/>
                <TextBlock Text="找圆参数" FontWeight="Bold" Margin="0,10,0,2"/>
                <UniformGrid Columns="2">
                    <TextBlock Text="最小半径"/><TextBox Text="{Binding CircleStep.MinRadius}"/>
                    <TextBlock Text="最大半径"/><TextBox Text="{Binding CircleStep.MaxRadius}"/>
                    <TextBlock Text="累加阈值"/><TextBox Text="{Binding CircleStep.AccumulatorThreshold}"/>
                </UniformGrid>
                <TextBlock Text="直径判定" FontWeight="Bold" Margin="0,10,0,2"/>
                <UniformGrid Columns="2">
                    <TextBlock Text="名义直径"/><TextBox Text="{Binding SizeStep.Nominal}"/>
                    <TextBlock Text="公差"/><TextBox Text="{Binding SizeStep.Tolerance}"/>
                </UniformGrid>
                <Separator Margin="0,10,0,6"/>
                <TextBlock Text="{Binding TotalCount, StringFormat=总数: {0}}"/>
                <TextBlock Text="{Binding OkCount, StringFormat=OK: {0}}" Foreground="Green"/>
                <TextBlock Text="{Binding NgCount, StringFormat=NG: {0}}" Foreground="Red"/>
                <TextBlock Text="{Binding YieldText, StringFormat=良率: {0}}" FontWeight="Bold"/>
            </StackPanel>
        </GroupBox>

        <!-- 底部:日志 -->
        <ListBox DockPanel.Dock="Bottom" Height="120" ItemsSource="{Binding Log}"
                 FontFamily="Consolas" Margin="0,6,0,0"/>

        <!-- 中央:图像显示 -->
        <Border BorderBrush="Gray" BorderThickness="1" Background="Gainsboro">
            <Image Source="{Binding DisplayImage}" Stretch="Uniform" Margin="4"/>
        </Border>
    </DockPanel>
</Window>

步骤5:结果记录

using Dapper;
using Microsoft.Data.Sqlite;

namespace VisionTool.Services;

// 单条检测记录模型
public record DetectionRecord(
    DateTime Time, string ImagePath, bool IsOk, string Reason, int DurationMs);

// SQLite 仓储:检测记录建表、插入、查询
public sealed class RecordRepository
{
    private readonly string _connString = "Data Source=vision.db";

    public void Init()
    {
        using var conn = new SqliteConnection(_connString);
        conn.Execute("""
            CREATE TABLE IF NOT EXISTS detections(
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                ts TEXT NOT NULL,
                image_path TEXT,
                is_ok INTEGER NOT NULL,
                reason TEXT,
                duration_ms INTEGER
            );
            CREATE INDEX IF NOT EXISTS idx_detections_ts ON detections(ts);
            """);
    }
    public void Insert(DetectionRecord r)
    {
        using var conn = new SqliteConnection(_connString);
        conn.Execute(
            "INSERT INTO detections(ts, image_path, is_ok, reason, duration_ms) VALUES(@Ts, @P, @Ok, @R, @D)",
            new { Ts = r.Time.ToString("yyyy-MM-dd HH:mm:ss.fff"), P = r.ImagePath,
                  Ok = r.IsOk ? 1 : 0, R = r.Reason, D = r.DurationMs });
    }
    // 最近 N 条记录:做历史查询界面用
    public List<DetectionRecord> QueryRecent(int count = 100)
    {
        using var conn = new SqliteConnection(_connString);
        var rows = conn.Query<(string Ts, string P, long Ok, string R, long D)>(
            "SELECT ts, image_path, is_ok, reason, duration_ms FROM detections ORDER BY id DESC LIMIT @c",
            new { c = count });
        return rows.Select(x => new DetectionRecord(
            DateTime.Parse(x.Ts), x.P, x.Ok == 1, x.R ?? "", (int)x.D)).ToList();
    }
}

验收标准

扩展挑战

  • 硬触发取图:监听串口/网口的触发信号(IO 板干接点、PLC 置位),收到信号才 Grab 一帧,模拟真实产线节拍
  • 增加模板匹配步骤:新写一个 TemplateMatchStep 实现 IInspectionStep,用 Cv2.MatchTemplate 定位模板,体会策略模式”只加类不改引擎”的好处
  • 导入 ONNX 深度模型:用 Microsoft.ML.OnnxRuntime 跑分类或检测模型,把推理结果包装成 StepResult 接入引擎
  • NG 图片自动归档:按日期分文件夹保存 NG 原图,便于追溯
  • 增加 ROI 框选:在 Image 上拖拽矩形选检测区域,只对 ROI 做检测