barcode
This commit is contained in:
parent
5fe374eeff
commit
8015c5bbfe
@ -21,7 +21,7 @@
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.17" />
|
||||
<PackageReference Include="MiniExcel" Version="1.45.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
|
||||
<PackageReference Include="OpenCvSharp5.Windows" Version="5.0.0.20260702" />
|
||||
<PackageReference Include="OpenCvSharp5.Windows" Version="5.0.0.20260713" />
|
||||
<PackageReference Include="Prism.DryIoc" Version="9.0.537" />
|
||||
<PackageReference Include="RoslynPad.Editor.Windows" Version="5.0.0" />
|
||||
<!--<PackageReference Include="SourceGear.sqlite3" Version="3.50.4.5" />-->
|
||||
@ -29,6 +29,7 @@
|
||||
<PackageReference Include="System.IO.Ports" Version="10.0.9" />
|
||||
<!-- 覆盖传递依赖 SQLitePCLRaw.lib.e_sqlite3 至修复版本 3.50.3(CVE-2025-6965,2.x 全部受影响且已弃用) -->
|
||||
<PackageReference Include="SQLitePCLRaw.lib.e_sqlite3" Version="3.50.3" />
|
||||
<PackageReference Include="ZXing.Net" Version="0.16.11" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
|
||||
@ -55,9 +55,9 @@ namespace PLCSharp.VVMs.Vision
|
||||
case "Pos":
|
||||
{
|
||||
var r = new Pos();
|
||||
if (value is Pos line)
|
||||
if (value is Pos pos)
|
||||
{
|
||||
r = line;
|
||||
r = pos;
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -97,9 +97,9 @@ namespace PLCSharp.VVMs.Vision
|
||||
case "Rect":
|
||||
{
|
||||
var r = new Rect();
|
||||
if (value is Rect line)
|
||||
if (value is Rect rect)
|
||||
{
|
||||
r = line;
|
||||
r = rect;
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -112,6 +112,22 @@ namespace PLCSharp.VVMs.Vision
|
||||
case "Double":
|
||||
SetProperty(ref _RawValue, value);
|
||||
break;
|
||||
case "Barcode":
|
||||
{
|
||||
var r = new Barcode();
|
||||
if (value is Barcode barcode)
|
||||
{
|
||||
r = barcode;
|
||||
}
|
||||
else
|
||||
{
|
||||
r = JsonConvert.DeserializeObject<Barcode>(value.ToString());
|
||||
}
|
||||
|
||||
SetProperty(ref _RawValue, r);
|
||||
}
|
||||
break;
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -181,6 +197,12 @@ namespace PLCSharp.VVMs.Vision
|
||||
case "Double":
|
||||
return ((double)val).ToString("F4");
|
||||
|
||||
case "Barcode":
|
||||
if (val is Barcode b)
|
||||
return $"位置:(X:{b.Box.X:F4}, Y:{b.Box.Y:F4}) 内容:({b.Info})";
|
||||
else
|
||||
return val?.ToString() ?? "";
|
||||
|
||||
default:
|
||||
return val?.ToString() ?? "";
|
||||
}
|
||||
|
||||
@ -346,6 +346,17 @@ namespace PLCSharp.VVMs.Vision
|
||||
newFlow.DoubleParams["ImageY"] = 0;
|
||||
newFlow.StringParams["TransformMat"] = "";
|
||||
break;
|
||||
case VisionFlowType.ROI解码:
|
||||
newFlow.IntParams["DecodeType"] = 0;
|
||||
newFlow.BoolParams["EnableMirror"] = false;
|
||||
newFlow.BoolParams["EnableUpscale"] = true;
|
||||
newFlow.BoolParams["UsePureBarcode"] = false;
|
||||
newFlow.StringParams["ResultVarName"] = "条码解码_Result";
|
||||
break;
|
||||
case VisionFlowType.微信解码:
|
||||
newFlow.BoolParams["EnableMirror"] = false;
|
||||
newFlow.StringParams["ResultVarName"] = "微信解码_Result";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
@ -551,6 +562,12 @@ namespace PLCSharp.VVMs.Vision
|
||||
case VisionFlowType.坐标转换:
|
||||
ContentRegion = new CoordTransform();
|
||||
break;
|
||||
case VisionFlowType.ROI解码:
|
||||
ContentRegion = new BarcodeDecode();
|
||||
break;
|
||||
case VisionFlowType.微信解码:
|
||||
ContentRegion = new WeChatDecode();
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
@ -1568,6 +1585,58 @@ namespace PLCSharp.VVMs.Vision
|
||||
});
|
||||
}
|
||||
|
||||
private AsyncDelegateCommand _DrawBarcodeROI;
|
||||
/// <summary>
|
||||
/// 绘制条码解码 ROI 区域
|
||||
/// </summary>
|
||||
public AsyncDelegateCommand DrawBarcodeROI =>
|
||||
_DrawBarcodeROI ??= new AsyncDelegateCommand(ExecuteDrawBarcodeROIAsync);
|
||||
|
||||
private async Task ExecuteDrawBarcodeROIAsync()
|
||||
{
|
||||
var window = System.Windows.Application.Current.Windows.OfType<System.Windows.Window>()
|
||||
.FirstOrDefault(w => w.IsActive);
|
||||
var imageEdit = WpfTool.FindVisualChild<ImageEdit>(window);
|
||||
if (imageEdit?.ImageSource == null)
|
||||
{
|
||||
SendInfoDialog("请先获取图片!");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var roi = await imageEdit.DrawROIAsync("条码解码");
|
||||
if (roi == null) return;
|
||||
|
||||
if (SelectVisionFlow == null) return;
|
||||
|
||||
SelectVisionFlow.DoubleParams["ROILeft"] = roi.Left;
|
||||
SelectVisionFlow.DoubleParams["ROITop"] = roi.Top;
|
||||
SelectVisionFlow.DoubleParams["ROIWidth"] = roi.Width;
|
||||
SelectVisionFlow.DoubleParams["ROIHeight"] = roi.Height;
|
||||
|
||||
// 画矩形边框
|
||||
var rect = new System.Windows.Shapes.Rectangle
|
||||
{
|
||||
Width = roi.Width,
|
||||
Height = roi.Height,
|
||||
Stroke = Brushes.Lime,
|
||||
StrokeThickness = 2,
|
||||
StrokeDashArray = new System.Windows.Media.DoubleCollection { 4, 2 },
|
||||
Tag = "条码解码",
|
||||
};
|
||||
Canvas.SetLeft(rect, roi.Left);
|
||||
Canvas.SetTop(rect, roi.Top);
|
||||
imageEdit.Draw(rect);
|
||||
|
||||
SendInfoDialog("条码解码 ROI 已保存");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SendInfoDialog($"ROI 绘制失败:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在 ImageEdit 上画矩形边框 + 中心十字
|
||||
/// </summary>
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
public record struct Circle(Pos Center, double Radius);
|
||||
public record struct Line(Pos From,Pos To);
|
||||
public record struct Rect(Pos Center, double Width,double Height);
|
||||
public record struct Barcode(Pos Box, string Info);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,120 @@
|
||||
<UserControl x:Class="PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm.BarcodeDecode"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:local="clr-namespace:PLCSharp.VVMs.Vision.VisionFlowHandler"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:vision="clr-namespace:PLCSharp.VVMs.Vision"
|
||||
mc:Ignorable="d"
|
||||
d:DataContext="{d:DesignInstance Type=vision:VisionConfigViewModel}"
|
||||
d:DesignHeight="450" d:DesignWidth="300">
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel>
|
||||
<!-- ROI 区域 -->
|
||||
<GroupBox Header="ROI 区域">
|
||||
<StackPanel>
|
||||
<Button Height="25" Margin="5" Command="{Binding DrawBarcodeROI}" Content="框选 ROI 区域" />
|
||||
<Grid Margin="5">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Margin="3,0" Text="Left" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[ROILeft], TargetNullValue=—, UpdateSourceTrigger=LostFocus}" />
|
||||
<TextBlock Grid.Row="0" Grid.Column="2"
|
||||
Margin="3,0"
|
||||
Text="Top"
|
||||
VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="0" Grid.Column="3" Text="{Binding SelectVisionFlow.DoubleParams[ROITop], TargetNullValue=—, UpdateSourceTrigger=LostFocus}" />
|
||||
<TextBlock Grid.Row="1" Margin="3,0" Text="Width" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[ROIWidth], TargetNullValue=—, UpdateSourceTrigger=LostFocus}" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="2"
|
||||
Margin="3,0"
|
||||
Text="Height"
|
||||
VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="1" Grid.Column="3" Text="{Binding SelectVisionFlow.DoubleParams[ROIHeight], TargetNullValue=—, UpdateSourceTrigger=LostFocus}" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</GroupBox>
|
||||
|
||||
<!-- 解码参数 -->
|
||||
<GroupBox Header="解码参数">
|
||||
<Grid Margin="5">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Text="解码类型" VerticalAlignment="Center" ToolTip="选择要解码的条码类型" />
|
||||
<ComboBox Grid.Column="1" SelectedIndex="{Binding SelectVisionFlow.IntParams[DecodeType], Mode=TwoWay}">
|
||||
<ComboBoxItem Content="DataMatrix" />
|
||||
<ComboBoxItem Content="QR Code" />
|
||||
<ComboBoxItem Content="DataMatrix + QR" />
|
||||
<ComboBoxItem Content="全部 2D 条码" />
|
||||
</ComboBox>
|
||||
|
||||
<TextBlock Grid.Row="1" Text="镜像 ROI" VerticalAlignment="Center" ToolTip="对 ROI 区域的图像做水平镜像翻转,应对镜像的码" />
|
||||
<CheckBox Grid.Row="1" Grid.Column="1" Margin="5,0" IsChecked="{Binding SelectVisionFlow.BoolParams[EnableMirror], Mode=TwoWay}" />
|
||||
|
||||
<TextBlock Grid.Row="2" Text="自动放大" VerticalAlignment="Center" ToolTip="小码自动放大 2-4 倍,帮助 ZXing 检测器识别 L 型边框" />
|
||||
<CheckBox Grid.Row="2" Grid.Column="1"
|
||||
Margin="5,0"
|
||||
IsChecked="{Binding SelectVisionFlow.BoolParams[EnableUpscale], Mode=TwoWay}"
|
||||
IsThreeState="False" />
|
||||
|
||||
<TextBlock Grid.Row="3" Text="PureBarcode" VerticalAlignment="Center" ToolTip="跳过检测器直接采样(需 ROI 紧密框住码,适用于严重破损码)" />
|
||||
<CheckBox Grid.Row="3" Grid.Column="1"
|
||||
Margin="5,0"
|
||||
IsChecked="{Binding SelectVisionFlow.BoolParams[UsePureBarcode], Mode=TwoWay}"
|
||||
IsThreeState="False" />
|
||||
|
||||
<TextBlock Grid.Row="4" Text="结果变量名" VerticalAlignment="Center" ToolTip="解码结果写入的局部变量名称" />
|
||||
<TextBox Grid.Row="4" Grid.Column="1" Text="{Binding SelectVisionFlow.StringParams[ResultVarName], Mode=TwoWay, TargetNullValue=条码解码_Result, UpdateSourceTrigger=LostFocus}" />
|
||||
</Grid>
|
||||
</GroupBox>
|
||||
|
||||
<!-- 解码结果 -->
|
||||
<GroupBox Header="解码结果">
|
||||
<Grid Margin="5">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Text="解码状态" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Column="1" Text="{Binding SelectedVisionFunction.Params.ResultDoubles[DecodeSuccess], Mode=OneWay}" IsReadOnly="True" Background="#FFF0F0F0" />
|
||||
|
||||
<TextBlock Grid.Row="1" Text="使用管线" VerticalAlignment="Center" ToolTip="-1=失败,0=原图,1=CLAHE+Otsu,2=自适应阈值,3=形态学闭运算,4=锐化+Otsu" />
|
||||
<TextBox Grid.Row="1" Grid.Column="1"
|
||||
Text="{Binding SelectVisionFlow.IntParams[UsedPipeline], Mode=OneWay, TargetNullValue=—}"
|
||||
IsReadOnly="True" Background="#FFF0F0F0" />
|
||||
|
||||
<TextBlock Grid.Row="2" Text="解码内容" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="2" Grid.Column="1"
|
||||
MinHeight="60"
|
||||
Text="{Binding SelectVisionFlow.StringParams[DecodeResult], Mode=OneWay}"
|
||||
TextWrapping="Wrap"
|
||||
IsReadOnly="True" Background="#FFF0F0F0" />
|
||||
</Grid>
|
||||
</GroupBox>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</UserControl>
|
||||
@ -0,0 +1,18 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// BarcodeDecode.xaml 的交互逻辑
|
||||
/// </summary>
|
||||
public partial class BarcodeDecode : UserControl
|
||||
{
|
||||
/// <summary>
|
||||
/// 条码解码参数配置控件
|
||||
/// </summary>
|
||||
public BarcodeDecode()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,389 @@
|
||||
#nullable enable
|
||||
using OpenCvSharp;
|
||||
using PLCSharp.Core.Common;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Media;
|
||||
using ZXing;
|
||||
using ZXing.Common;
|
||||
|
||||
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// 条码解码 Handler — 多管线增强版
|
||||
///
|
||||
/// 管线策略(按优先级):
|
||||
/// 0 原图灰度
|
||||
/// 1 CLAHE + Otsu
|
||||
/// 2 自适应阈值
|
||||
/// 3 形态学闭运算(3×3)
|
||||
/// 4 锐化 + Otsu
|
||||
/// 5 大核形态学闭运算(5×5,重度破损码)
|
||||
///
|
||||
/// 增强措施(所有管线共用):
|
||||
/// • Upscale:ROI 边长 < 200 时自动放大 2-4 倍,保证 ZXing 检测器有足够像素
|
||||
/// • PureBarcode:勾选后且设了 ROI 时,绕过 WhiteRectangleDetector 直接采样
|
||||
/// • 垂直翻转兜底(管线 0 额外尝试)
|
||||
/// </summary>
|
||||
public class BarcodeDecodeHandler : IVisionFlowHandler
|
||||
{
|
||||
public VisionFlowType Type => VisionFlowType.ROI解码;
|
||||
|
||||
public bool Execute(VisionFunction func, VisionFlow item)
|
||||
{
|
||||
if (func.Src == null || func.Src.Empty())
|
||||
throw new Exception("源图像为空!");
|
||||
|
||||
// 1. 读取参数
|
||||
int decodeType = item.IntParams.TryGetValue("DecodeType", out int dt) ? dt : 0;
|
||||
bool enableMirror = item.BoolParams.TryGetValue("EnableMirror", out bool em) && em;
|
||||
bool usePureBarcode = item.BoolParams.TryGetValue("UsePureBarcode", out bool pb) && pb;
|
||||
bool enableUpscale = item.BoolParams.TryGetValue("EnableUpscale", out bool up) ? up : true;
|
||||
|
||||
// 2. ROI 裁剪
|
||||
Mat roiMat;
|
||||
int roiLeft = 0, roiTop = 0;
|
||||
double left = 0, top = 0, width = 0, height = 0;
|
||||
bool hasRoi = item.DoubleParams.TryGetValue("ROILeft", out left) &&
|
||||
item.DoubleParams.TryGetValue("ROITop", out top) &&
|
||||
item.DoubleParams.TryGetValue("ROIWidth", out width) &&
|
||||
item.DoubleParams.TryGetValue("ROIHeight", out height) &&
|
||||
width > 0 && height > 0;
|
||||
|
||||
if (hasRoi)
|
||||
{
|
||||
roiLeft = (int)left;
|
||||
roiTop = (int)top;
|
||||
int w = (int)width;
|
||||
int h = (int)height;
|
||||
int x = Math.Clamp(roiLeft, 0, func.Src.Width - 1);
|
||||
int y = Math.Clamp(roiTop, 0, func.Src.Height - 1);
|
||||
w = Math.Min(w, func.Src.Width - x);
|
||||
h = Math.Min(h, func.Src.Height - y);
|
||||
if (w < 4 || h < 4)
|
||||
throw new Exception("ROI 区域太小,至少需要 4×4 像素!");
|
||||
roiMat = func.Src[new OpenCvSharp.Rect(x, y, w, h)].Clone();
|
||||
}
|
||||
else
|
||||
{
|
||||
roiMat = func.Src.Clone();
|
||||
}
|
||||
|
||||
// 3. 镜像 ROI 区域(只镜像 ROI,不影响原图)
|
||||
if (enableMirror)
|
||||
{
|
||||
Cv2.Flip(roiMat, roiMat, FlipMode.X);
|
||||
}
|
||||
|
||||
// 4. 转换为灰度
|
||||
using var grayBase = new Mat();
|
||||
if (roiMat.Channels() == 3)
|
||||
Cv2.CvtColor(roiMat, grayBase, ColorConversionCodes.BGR2GRAY);
|
||||
else if (roiMat.Channels() == 1)
|
||||
roiMat.CopyTo(grayBase);
|
||||
else
|
||||
{
|
||||
roiMat.Dispose();
|
||||
throw new Exception("不支持的图像通道数!");
|
||||
}
|
||||
roiMat.Dispose();
|
||||
|
||||
int imgW = grayBase.Width;
|
||||
int imgH = grayBase.Height;
|
||||
var formats = DecodeTypeToFormats(decodeType);
|
||||
|
||||
// 5. 自动放大 — 小码放大给检测器足够的像素
|
||||
using var workingGray = BuildWorkingGray(grayBase, enableUpscale, out double actualScale);
|
||||
int workW = workingGray.Width;
|
||||
int workH = workingGray.Height;
|
||||
|
||||
// 记录实际 ROI 偏移 + 放大系数,供绘制时反向映射
|
||||
double scaleInv = 1.0 / actualScale;
|
||||
|
||||
// 6. PureBarcode 模式:仅当 ROI 紧密框住码时生效,绕过最脆弱的 WhiteRectangleDetector
|
||||
if (usePureBarcode && hasRoi)
|
||||
{
|
||||
var pbResult = TryDecodePureBarcode(workingGray, formats);
|
||||
if (pbResult != null)
|
||||
{
|
||||
return OutputResult(func, item, pbResult, roiLeft, roiTop, workW, workH, scaleInv, pipeline: -1);
|
||||
}
|
||||
}
|
||||
|
||||
// 7. 依次尝试多条预处理管线
|
||||
Result? result = null;
|
||||
int usedPipeline = -1;
|
||||
|
||||
for (int pipeline = 0; pipeline < 6 && result == null; pipeline++)
|
||||
{
|
||||
using var processed = PreparePipeline(workingGray, pipeline);
|
||||
if (processed == null || processed.Empty())
|
||||
continue;
|
||||
|
||||
result = TryDecodeWithReader(processed, formats);
|
||||
|
||||
if (result != null)
|
||||
{
|
||||
usedPipeline = pipeline;
|
||||
break;
|
||||
}
|
||||
|
||||
// 管线 0 额外尝试垂直翻转
|
||||
if (pipeline == 0)
|
||||
{
|
||||
Cv2.Flip(processed, processed, FlipMode.Y);
|
||||
result = TryDecodeWithReader(processed, formats);
|
||||
if (result != null)
|
||||
{
|
||||
usedPipeline = pipeline;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 8. 输出
|
||||
if (result != null)
|
||||
{
|
||||
return OutputResult(func, item, result, roiLeft, roiTop, workW, workH, scaleInv, usedPipeline);
|
||||
}
|
||||
|
||||
// 解码失败
|
||||
item.StringParams["DecodeResult"] = "";
|
||||
item.IntParams["UsedPipeline"] = -1;
|
||||
func.Params.ResultDoubles["DecodeSuccess"] = 0;
|
||||
|
||||
if (roiLeft > 0 || roiTop > 0 || imgW > 0)
|
||||
{
|
||||
func.DrawCommands.Add(DrawCommand.Line(roiLeft, roiTop, roiLeft + imgW, roiTop, Colors.Red, 1));
|
||||
func.DrawCommands.Add(DrawCommand.Line(roiLeft + imgW, roiTop, roiLeft + imgW, roiTop + imgH, Colors.Red, 1));
|
||||
func.DrawCommands.Add(DrawCommand.Line(roiLeft + imgW, roiTop + imgH, roiLeft, roiTop + imgH, Colors.Red, 1));
|
||||
func.DrawCommands.Add(DrawCommand.Line(roiLeft, roiTop + imgH, roiLeft, roiTop, Colors.Red, 1));
|
||||
}
|
||||
|
||||
item.Flow.Done = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── 辅助方法 ────────────────────────────────────────
|
||||
|
||||
/// <summary>构造放大后的灰度图</summary>
|
||||
private static Mat BuildWorkingGray(Mat gray, bool enableUpscale, out double scale)
|
||||
{
|
||||
if (!enableUpscale)
|
||||
{
|
||||
scale = 1.0;
|
||||
return gray.Clone();
|
||||
}
|
||||
|
||||
int minDim = Math.Min(gray.Width, gray.Height);
|
||||
if (minDim >= 200)
|
||||
{
|
||||
scale = 1.0;
|
||||
return gray.Clone();
|
||||
}
|
||||
|
||||
// 目标:小的边至少 300px,但不超过 800px
|
||||
int targetDim = Math.Min(Math.Max(minDim * 2, 300), 800);
|
||||
scale = (double)targetDim / minDim;
|
||||
int newW = (int)(gray.Width * scale);
|
||||
int newH = (int)(gray.Height * scale);
|
||||
var enlarged = new Mat();
|
||||
Cv2.Resize(gray, enlarged, new Size(newW, newH), 0, 0, InterpolationFlags.Cubic);
|
||||
return enlarged;
|
||||
}
|
||||
|
||||
/// <summary>尝试 PureBarcode 解码(跳过 WhiteRectangleDetector)</summary>
|
||||
private static Result? TryDecodePureBarcode(Mat gray, List<BarcodeFormat> formats)
|
||||
{
|
||||
byte[] pixels = new byte[gray.Width * gray.Height];
|
||||
Marshal.Copy(gray.Data, pixels, 0, pixels.Length);
|
||||
var source = new RGBLuminanceSource(pixels, gray.Width, gray.Height, RGBLuminanceSource.BitmapFormat.Gray8);
|
||||
|
||||
var reader = new BarcodeReaderGeneric
|
||||
{
|
||||
Options = new DecodingOptions
|
||||
{
|
||||
PossibleFormats = formats,
|
||||
TryHarder = true,
|
||||
TryInverted = true,
|
||||
PureBarcode = true,
|
||||
}
|
||||
};
|
||||
return reader.Decode(source);
|
||||
}
|
||||
|
||||
/// <summary>用标准 reader 解码</summary>
|
||||
private static Result? TryDecodeWithReader(Mat mat, List<BarcodeFormat> formats)
|
||||
{
|
||||
byte[] pixels = new byte[mat.Width * mat.Height];
|
||||
Marshal.Copy(mat.Data, pixels, 0, pixels.Length);
|
||||
var source = new RGBLuminanceSource(pixels, mat.Width, mat.Height, RGBLuminanceSource.BitmapFormat.Gray8);
|
||||
|
||||
var reader = new BarcodeReaderGeneric
|
||||
{
|
||||
Options = new DecodingOptions
|
||||
{
|
||||
PossibleFormats = formats,
|
||||
TryHarder = true,
|
||||
TryInverted = true,
|
||||
}
|
||||
};
|
||||
return reader.Decode(source);
|
||||
}
|
||||
|
||||
/// <summary>写入输出结果和绘制命令</summary>
|
||||
private static bool OutputResult(
|
||||
VisionFunction func, VisionFlow item, Result result,
|
||||
int roiLeft, int roiTop, int workW, int workH, double scaleInv, int pipeline)
|
||||
{
|
||||
string decodedText = result.Text;
|
||||
item.StringParams["DecodeResult"] = decodedText;
|
||||
item.IntParams["UsedPipeline"] = pipeline;
|
||||
func.Params.ResultDoubles["DecodeSuccess"] = 1;
|
||||
|
||||
// 绘制条码边框(结果点是在放大后图像上的坐标,需要缩回原始尺寸 + ROI 偏移)
|
||||
if (result.ResultPoints != null && result.ResultPoints.Length >= 2)
|
||||
{
|
||||
var pts = result.ResultPoints
|
||||
.Select(p => new System.Windows.Point(p.X * scaleInv + roiLeft, p.Y * scaleInv + roiTop))
|
||||
.ToArray();
|
||||
|
||||
if (pts.Length == 4)
|
||||
{
|
||||
func.DrawCommands.Add(DrawCommand.Polygon(pts, Colors.Lime, 2));
|
||||
}
|
||||
else if (pts.Length == 2)
|
||||
{
|
||||
double x1 = Math.Min(pts[0].X, pts[1].X);
|
||||
double y1 = Math.Min(pts[0].Y, pts[1].Y);
|
||||
double x2 = Math.Max(pts[0].X, pts[1].X);
|
||||
double y2 = Math.Max(pts[0].Y, pts[1].Y);
|
||||
func.DrawCommands.Add(DrawCommand.Line(x1, y1, x2, y1, Colors.Lime, 2));
|
||||
func.DrawCommands.Add(DrawCommand.Line(x2, y1, x2, y2, Colors.Lime, 2));
|
||||
func.DrawCommands.Add(DrawCommand.Line(x2, y2, x1, y2, Colors.Lime, 2));
|
||||
func.DrawCommands.Add(DrawCommand.Line(x1, y2, x1, y1, Colors.Lime, 2));
|
||||
}
|
||||
|
||||
// 文本标注
|
||||
double tx = result.ResultPoints[0].X * scaleInv + roiLeft;
|
||||
double ty = result.ResultPoints[0].Y * scaleInv + roiTop - 10;
|
||||
if (ty < 0) ty = result.ResultPoints[0].Y * scaleInv + roiTop + 10;
|
||||
func.DrawCommands.Add(new DrawCommand
|
||||
{
|
||||
Shape = DrawCommand.Type.Text,
|
||||
X1 = tx,
|
||||
Y1 = ty,
|
||||
Text = decodedText.Length > 60 ? decodedText[..60] + "…" : decodedText,
|
||||
Color = Colors.Lime,
|
||||
FontSize = 14,
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
func.DrawCommands.Add(new DrawCommand
|
||||
{
|
||||
Shape = DrawCommand.Type.Text,
|
||||
X1 = roiLeft + (int)(workW * scaleInv) / 2.0 - 50,
|
||||
Y1 = roiTop + (int)(workH * scaleInv) / 2.0,
|
||||
Text = "✓ " + (decodedText.Length > 40 ? decodedText[..40] + "…" : decodedText),
|
||||
Color = Colors.Lime,
|
||||
FontSize = 16,
|
||||
});
|
||||
}
|
||||
|
||||
// 局部变量表 — 存储条码中心坐标
|
||||
double boxCX = 0, boxCY = 0;
|
||||
if (result.ResultPoints != null && result.ResultPoints.Length >= 2)
|
||||
{
|
||||
for (int i = 0; i < result.ResultPoints.Length; i++)
|
||||
{
|
||||
boxCX += result.ResultPoints[i].X * scaleInv + roiLeft;
|
||||
boxCY += result.ResultPoints[i].Y * scaleInv + roiTop;
|
||||
}
|
||||
boxCX /= result.ResultPoints.Length;
|
||||
boxCY /= result.ResultPoints.Length;
|
||||
}
|
||||
string varName = item.StringParams.TryGetValue("ResultVarName", out var rvn) && !string.IsNullOrEmpty(rvn)
|
||||
? rvn : "条码解码_Result";
|
||||
var existingVar = func.Params.Variables.FirstOrDefault(v => v.Name == varName);
|
||||
if (existingVar == null)
|
||||
{
|
||||
existingVar = new LocalVariableItem(varName, "Barcode", new Barcode(new Pos(), ""));
|
||||
System.Windows.Application.Current.Dispatcher.Invoke(
|
||||
() => func.Params.Variables.Add(existingVar));
|
||||
}
|
||||
existingVar.RawValue = new Barcode(new Pos(boxCX, boxCY, 0, 0), decodedText);
|
||||
|
||||
item.Flow.Done = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── 管线定义 ────────────────────────────────────────
|
||||
|
||||
private static Mat? PreparePipeline(Mat gray, int pipeline)
|
||||
{
|
||||
return pipeline switch
|
||||
{
|
||||
0 => gray.Clone(), // 原始灰度
|
||||
1 => ApplyClaheOtsu(gray), // CLAHE + Otsu
|
||||
2 => ApplyAdaptiveThreshold(gray), // 自适应阈值
|
||||
3 => ApplyMorphologicalClose(gray, 3), // 闭运算 3×3
|
||||
4 => ApplySharpenedOtsu(gray), // 锐化 + Otsu
|
||||
5 => ApplyMorphologicalClose(gray, 5), // 闭运算 5×5(重度破损)
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
private static Mat ApplyClaheOtsu(Mat gray)
|
||||
{
|
||||
var clahe = Cv2.CreateCLAHE(3.0, new Size(8, 8));
|
||||
var result = new Mat();
|
||||
clahe.Apply(gray, result);
|
||||
Cv2.Threshold(result, result, 0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Mat ApplyAdaptiveThreshold(Mat gray)
|
||||
{
|
||||
int bs = Math.Max(21, (int)(Math.Min(gray.Width, gray.Height) / 10) * 2 + 1);
|
||||
if (bs % 2 == 0) bs++;
|
||||
if (bs < 3) bs = 3;
|
||||
var result = new Mat();
|
||||
Cv2.AdaptiveThreshold(gray, result, 255,
|
||||
AdaptiveThresholdTypes.GaussianC, ThresholdTypes.BinaryInv, bs, 10);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Mat ApplyMorphologicalClose(Mat gray, int kernelSize)
|
||||
{
|
||||
var bin = new Mat();
|
||||
Cv2.Threshold(gray, bin, 0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
|
||||
var kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(kernelSize, kernelSize));
|
||||
Cv2.MorphologyEx(bin, bin, MorphTypes.Close, kernel, iterations: 1);
|
||||
var dilateKernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(2, 2));
|
||||
Cv2.Dilate(bin, bin, dilateKernel, iterations: 1);
|
||||
return bin;
|
||||
}
|
||||
|
||||
private static Mat ApplySharpenedOtsu(Mat gray)
|
||||
{
|
||||
using var blurred = new Mat();
|
||||
Cv2.GaussianBlur(gray, blurred, new Size(0, 0), 1.0);
|
||||
var sharp = new Mat();
|
||||
Cv2.AddWeighted(gray, 1.5, blurred, -0.5, 0, sharp);
|
||||
Cv2.Threshold(sharp, sharp, 0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
|
||||
return sharp;
|
||||
}
|
||||
|
||||
private static List<BarcodeFormat> DecodeTypeToFormats(int decodeType)
|
||||
{
|
||||
return decodeType switch
|
||||
{
|
||||
0 => [BarcodeFormat.DATA_MATRIX],
|
||||
1 => [BarcodeFormat.QR_CODE],
|
||||
2 => [BarcodeFormat.DATA_MATRIX, BarcodeFormat.QR_CODE],
|
||||
3 => [BarcodeFormat.DATA_MATRIX, BarcodeFormat.QR_CODE, BarcodeFormat.AZTEC, BarcodeFormat.PDF_417],
|
||||
_ => [BarcodeFormat.DATA_MATRIX],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,71 @@
|
||||
<UserControl x:Class="PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm.WeChatDecode"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:local="clr-namespace:PLCSharp.VVMs.Vision.VisionFlowHandler"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:vision="clr-namespace:PLCSharp.VVMs.Vision"
|
||||
mc:Ignorable="d"
|
||||
d:DataContext="{d:DesignInstance Type=vision:VisionConfigViewModel}"
|
||||
d:DesignHeight="400" d:DesignWidth="300">
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel>
|
||||
<!-- 解码参数 -->
|
||||
<GroupBox Header="解码参数">
|
||||
<Grid Margin="5">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="镜像" VerticalAlignment="Center" ToolTip="对图像做水平镜像翻转" />
|
||||
<CheckBox Grid.Column="1" Margin="5,0"
|
||||
IsChecked="{Binding SelectVisionFlow.BoolParams[EnableMirror], Mode=TwoWay}" />
|
||||
</Grid>
|
||||
</GroupBox>
|
||||
|
||||
<!-- 变量设置 -->
|
||||
<GroupBox Header="变量设置">
|
||||
<Grid Margin="5">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="结果变量名" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Column="1"
|
||||
Text="{Binding SelectVisionFlow.StringParams[ResultVarName], Mode=TwoWay, TargetNullValue=微信解码_Result, UpdateSourceTrigger=LostFocus}" />
|
||||
</Grid>
|
||||
</GroupBox>
|
||||
|
||||
<!-- 解码结果 -->
|
||||
<GroupBox Header="解码结果">
|
||||
<Grid Margin="5">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Text="解码状态" VerticalAlignment="Center" ToolTip="1=成功,0=未找到" />
|
||||
<TextBox Grid.Column="1"
|
||||
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[DecodeSuccess], Mode=OneWay}"
|
||||
IsReadOnly="True" Background="#FFF0F0F0" />
|
||||
|
||||
<TextBlock Grid.Row="1" Text="找到码数" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="1" Grid.Column="1"
|
||||
Text="{Binding SelectedVisionFunction.Params.ResultDoubles[DecodeCount], Mode=OneWay}"
|
||||
IsReadOnly="True" Background="#FFF0F0F0" />
|
||||
|
||||
<TextBlock Grid.Row="2" Text="解码内容" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="2" Grid.Column="1"
|
||||
Text="{Binding SelectVisionFlow.StringParams[DecodeResult], Mode=OneWay}"
|
||||
IsReadOnly="True" Background="#FFF0F0F0"
|
||||
TextWrapping="Wrap" MinHeight="60" />
|
||||
</Grid>
|
||||
</GroupBox>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</UserControl>
|
||||
@ -0,0 +1,18 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// WeChatDecode.xaml 的交互逻辑
|
||||
/// </summary>
|
||||
public partial class WeChatDecode : UserControl
|
||||
{
|
||||
/// <summary>
|
||||
/// 微信解码参数配置控件
|
||||
/// </summary>
|
||||
public WeChatDecode()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,145 @@
|
||||
#nullable enable
|
||||
using OpenCvSharp;
|
||||
using PLCSharp.Core.Common;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// 微信解码 Handler — 封装 OpenCV WeChatQRCode(CNN 检测 + 解码 QR 码)
|
||||
/// 支持同时检测和解码图像中的多个 QR 码。
|
||||
/// </summary>
|
||||
public class WeChatDecodeHandler : IVisionFlowHandler
|
||||
{
|
||||
public VisionFlowType Type => VisionFlowType.微信解码;
|
||||
|
||||
public bool Execute(VisionFunction func, VisionFlow item)
|
||||
{
|
||||
if (func.Src == null || func.Src.Empty())
|
||||
throw new Exception("源图像为空!");
|
||||
|
||||
// 1. 读取参数
|
||||
bool enableMirror = item.BoolParams.TryGetValue("EnableMirror", out bool em) && em;
|
||||
|
||||
// 2. 获取源图像(BGR 或灰度皆可)
|
||||
using Mat src = func.Src.Clone();
|
||||
|
||||
// 水平镜像(可选)
|
||||
if (enableMirror)
|
||||
{
|
||||
Cv2.Flip(src, src, FlipMode.X);
|
||||
}
|
||||
|
||||
// 3. 创建 WeChatQRCode(无需外部模型,OpenCV 5.x 内嵌了检测器)
|
||||
using var qr = new WeChatQRCode("", "");
|
||||
|
||||
// 4. 检测 + 解码(原生支持多个码)
|
||||
Point2f[][] corners;
|
||||
string[] texts;
|
||||
|
||||
try
|
||||
{
|
||||
texts = qr.DetectAndDecode(src, out corners);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"微信解码失败:{ex.Message}");
|
||||
}
|
||||
|
||||
int count = texts.Length;
|
||||
|
||||
// 5. 输出结果
|
||||
if (count > 0)
|
||||
{
|
||||
// 汇总所有解码文本
|
||||
string joinedText = string.Join(" | ", texts);
|
||||
item.StringParams["DecodeResult"] = joinedText;
|
||||
func.Params.ResultDoubles["DecodeSuccess"] = 1;
|
||||
func.Params.ResultDoubles["DecodeCount"] = count;
|
||||
|
||||
// 对每个检测到的码:绘制检测框 + 文本标注
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var pts = corners.Length > i ? corners[i] : [];
|
||||
string text = texts[i];
|
||||
|
||||
if (pts.Length == 4)
|
||||
{
|
||||
// 绘制四边形边框
|
||||
var polyPts = pts.Select(p => new System.Windows.Point(p.X, p.Y)).ToArray();
|
||||
func.DrawCommands.Add(DrawCommand.Polygon(polyPts, Colors.Lime, 2));
|
||||
|
||||
// 文本标注在左上角(偏移行数避免重叠)
|
||||
double labelX = pts[0].X;
|
||||
double labelY = pts[0].Y - 10 - i * 16;
|
||||
if (labelY < 0) labelY = pts[0].Y + 10 + i * 16;
|
||||
|
||||
string label = count > 1 ? $"[{i + 1}] " : "";
|
||||
label += text.Length > 50 ? text[..50] + "…" : text;
|
||||
func.DrawCommands.Add(new DrawCommand
|
||||
{
|
||||
Shape = DrawCommand.Type.Text,
|
||||
X1 = labelX,
|
||||
Y1 = labelY,
|
||||
Text = label,
|
||||
Color = Colors.Lime,
|
||||
FontSize = 14,
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
// 无角点信息,在左上角依次排列
|
||||
func.DrawCommands.Add(new DrawCommand
|
||||
{
|
||||
Shape = DrawCommand.Type.Text,
|
||||
X1 = 10,
|
||||
Y1 = 30 + i * 20,
|
||||
Text = $"✓ [{i + 1}] " + (text.Length > 40 ? text[..40] + "…" : text),
|
||||
Color = Colors.Lime,
|
||||
FontSize = 16,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 局部变量表 — 每个码存一个变量,变量名+序号递增
|
||||
string baseName = item.StringParams.TryGetValue("ResultVarName", out var rvn) && !string.IsNullOrEmpty(rvn)
|
||||
? rvn : "微信解码_Result";
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var pts = corners.Length > i ? corners[i] : [];
|
||||
string text = texts[i];
|
||||
|
||||
double boxCX = pts.Length >= 4
|
||||
? (pts[0].X + pts[1].X + pts[2].X + pts[3].X) / 4.0
|
||||
: 0;
|
||||
double boxCY = pts.Length >= 4
|
||||
? (pts[0].Y + pts[1].Y + pts[2].Y + pts[3].Y) / 4.0
|
||||
: 0;
|
||||
|
||||
string varName = count > 1 ? $"{baseName}_{i + 1}" : baseName;
|
||||
var existingVar = func.Params.Variables.FirstOrDefault(v => v.Name == varName);
|
||||
if (existingVar == null)
|
||||
{
|
||||
existingVar = new LocalVariableItem(varName, "Barcode", new Barcode(new Pos(), ""));
|
||||
System.Windows.Application.Current.Dispatcher.Invoke(
|
||||
() => func.Params.Variables.Add(existingVar));
|
||||
}
|
||||
existingVar.RawValue = new Barcode(new Pos(boxCX, boxCY, 0, 0), text);
|
||||
}
|
||||
|
||||
_ = func.RenderDrawAsync();
|
||||
|
||||
item.Flow.Done = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 未找到 QR 码
|
||||
item.StringParams["DecodeResult"] = "";
|
||||
func.Params.ResultDoubles["DecodeSuccess"] = 0;
|
||||
func.Params.ResultDoubles["DecodeCount"] = 0;
|
||||
item.Flow.Done = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,8 @@
|
||||
using DryIoc.ImTools;
|
||||
|
||||
using OpenCvSharp;
|
||||
using OpenCvSharp.Dnn;
|
||||
using static OpenCvSharp.Cv2;
|
||||
namespace PLCSharp.VVMs.Vision.VisionFlowHandler
|
||||
{
|
||||
|
||||
@ -688,4 +690,5 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json;
|
||||
using OpenCvSharp;
|
||||
using PLCSharp.Core.Common;
|
||||
using PLCSharp.Core.Prism;
|
||||
@ -18,23 +18,23 @@ namespace PLCSharp.VVMs.Vision
|
||||
{
|
||||
/// <summary>
|
||||
/// <summary>
|
||||
/// 视觉功能的执行单元,包含流程步骤列表(VisionFlows)、参数集合(Params)和运行时图像缓存
|
||||
/// 视觉功能的执行单元,包含流程步骤列表(VisionFlows)、参数集合(Params)和运行时图像缓存
|
||||
/// </summary>
|
||||
public class VisionFunction : BindableBase
|
||||
{
|
||||
/// <summary>
|
||||
/// 唯一标识
|
||||
/// 唯一标识
|
||||
/// </summary>
|
||||
[Key]
|
||||
public Guid ID { get; set; } = Guid.NewGuid();
|
||||
/// <summary>
|
||||
/// 配方标识
|
||||
/// 配方标识
|
||||
/// </summary>
|
||||
public Guid RecipeID { get; set; }
|
||||
|
||||
private string _Name;
|
||||
/// <summary>
|
||||
/// 配置项
|
||||
/// 配置项
|
||||
/// </summary>
|
||||
public string Name
|
||||
{
|
||||
@ -43,7 +43,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
{
|
||||
if (_Name != value)
|
||||
{
|
||||
Prompt = "已修改,请保存";
|
||||
Prompt = "已修改,请保存";
|
||||
}
|
||||
SetProperty(ref _Name, value);
|
||||
}
|
||||
@ -51,11 +51,11 @@ namespace PLCSharp.VVMs.Vision
|
||||
|
||||
private string _Prompt;
|
||||
/// <summary>
|
||||
/// 提示
|
||||
/// 提示
|
||||
/// </summary>
|
||||
[NotMapped]
|
||||
/// <summary>
|
||||
/// 提示
|
||||
/// 提示
|
||||
/// </summary>
|
||||
public string Prompt
|
||||
{
|
||||
@ -65,7 +65,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
|
||||
private string _Comment;
|
||||
/// <summary>
|
||||
/// 备注
|
||||
/// 备注
|
||||
/// </summary>
|
||||
public string Comment
|
||||
|
||||
@ -75,7 +75,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
{
|
||||
if (_Comment != value)
|
||||
{
|
||||
Prompt = "已修改,请保存";
|
||||
Prompt = "已修改,请保存";
|
||||
}
|
||||
SetProperty(ref _Comment, value);
|
||||
}
|
||||
@ -84,7 +84,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
|
||||
private string _ControlName;
|
||||
/// <summary>
|
||||
/// 关联的首页图像控件
|
||||
/// 关联的首页图像控件
|
||||
/// </summary>
|
||||
public string ControlName
|
||||
{
|
||||
@ -94,14 +94,14 @@ namespace PLCSharp.VVMs.Vision
|
||||
|
||||
[NotMapped]
|
||||
/// <summary>
|
||||
/// 编辑时显示的控件
|
||||
/// 编辑时显示的控件
|
||||
/// </summary>
|
||||
|
||||
public ImageEdit EditImageEdit { get; set; }
|
||||
|
||||
private Mat _Src;
|
||||
/// <summary>
|
||||
/// 源图像
|
||||
/// 源图像
|
||||
/// </summary>
|
||||
[NotMapped]
|
||||
public Mat Src
|
||||
@ -114,7 +114,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
if (old != value)
|
||||
{
|
||||
_Src = value;
|
||||
old?.Dispose(); // 释放旧 Mat 的非托管资源
|
||||
old?.Dispose(); // 释放旧 Mat 的非托管资源
|
||||
}
|
||||
|
||||
|
||||
@ -124,11 +124,11 @@ namespace PLCSharp.VVMs.Vision
|
||||
|
||||
private VisionParams _Params = new();
|
||||
|
||||
// VisionFunction 中添加辅助方法
|
||||
// VisionFunction 中添加辅助方法
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 参数集合
|
||||
/// 参数集合
|
||||
/// </summary>
|
||||
[NotMapped]
|
||||
public VisionParams Params
|
||||
@ -138,17 +138,17 @@ namespace PLCSharp.VVMs.Vision
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 序列化后的参数 JSON
|
||||
/// 序列化后的参数 JSON
|
||||
/// </summary>
|
||||
[Column("VisionParams")]
|
||||
public string SerializedVisionParams
|
||||
{
|
||||
get => JsonConvert.SerializeObject(Params); // 自动序列化
|
||||
get => JsonConvert.SerializeObject(Params); // 自动序列化
|
||||
set
|
||||
{
|
||||
try
|
||||
{
|
||||
Params = value != null ? JsonConvert.DeserializeObject<VisionParams>(value) : new VisionParams(); // 自动反序列化
|
||||
Params = value != null ? JsonConvert.DeserializeObject<VisionParams>(value) : new VisionParams(); // 自动反序列化
|
||||
}
|
||||
catch (global::System.Exception)
|
||||
{
|
||||
@ -161,7 +161,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
}
|
||||
private ObservableCollection<VisionFlow> _VisionFlows = [];
|
||||
/// <summary>
|
||||
/// 流程步骤列表
|
||||
/// 流程步骤列表
|
||||
/// </summary>
|
||||
[NotMapped]
|
||||
public ObservableCollection<VisionFlow> VisionFlows
|
||||
@ -176,27 +176,27 @@ namespace PLCSharp.VVMs.Vision
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 序列化后的流程 JSON
|
||||
/// 序列化后的流程 JSON
|
||||
/// </summary>
|
||||
[Column("VisionFlows")]
|
||||
public string SerializedVisionFlows
|
||||
{
|
||||
get => JsonConvert.SerializeObject(VisionFlows); // 自动序列化
|
||||
set => VisionFlows = JsonConvert.DeserializeObject<ObservableCollection<VisionFlow>>(value); // 自动反序列化
|
||||
get => JsonConvert.SerializeObject(VisionFlows); // 自动序列化
|
||||
set => VisionFlows = JsonConvert.DeserializeObject<ObservableCollection<VisionFlow>>(value); // 自动反序列化
|
||||
|
||||
}
|
||||
|
||||
int index = 0;
|
||||
/// <summary>
|
||||
/// 流程状态模型
|
||||
/// 流程状态模型
|
||||
/// </summary>
|
||||
[NotMapped]
|
||||
public FlowModel Flow { get; set; } = new();
|
||||
/// <summary>
|
||||
/// 运行All
|
||||
/// 运行All
|
||||
/// </summary>
|
||||
/// <param name="flow">流程状态模型</param>
|
||||
/// <returns>返回布尔值</returns>
|
||||
/// <param name="flow">流程状态模型</param>
|
||||
/// <returns>返回布尔值</returns>
|
||||
public bool RunAll(FlowModel flow)
|
||||
{
|
||||
switch (flow.Step)
|
||||
@ -232,21 +232,21 @@ namespace PLCSharp.VVMs.Vision
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 全局图像列表
|
||||
/// 全局图像列表
|
||||
/// </summary>
|
||||
[NotMapped]
|
||||
public ObservableCollection<ImageData> ImageDatas { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 视觉模型
|
||||
/// 视觉模型
|
||||
/// </summary>
|
||||
[NotMapped]
|
||||
public VisionsModel VisionsModel { get; set; }
|
||||
/// <summary>
|
||||
/// 运行项
|
||||
/// 运行项
|
||||
/// </summary>
|
||||
/// <param name="item">变量项</param>
|
||||
/// <returns>返回布尔值</returns>
|
||||
/// <param name="item">变量项</param>
|
||||
/// <returns>返回布尔值</returns>
|
||||
public bool RunItem(VisionFlow item)
|
||||
{
|
||||
if (_handlers.TryGetValue(item.Type, out var handler))
|
||||
@ -258,42 +258,44 @@ namespace PLCSharp.VVMs.Vision
|
||||
|
||||
private static readonly Dictionary<VisionFlowType, IVisionFlowHandler> _handlers = new()
|
||||
{
|
||||
[VisionFlowType.阈值] = new ThresholdHandler(),
|
||||
[VisionFlowType.阈值] = new ThresholdHandler(),
|
||||
[VisionFlowType.GRAY2BGR] = new Gray2BgrHandler(),
|
||||
[VisionFlowType.BGR2GRAY] = new Bgr2GrayHandler(),
|
||||
[VisionFlowType.取通道] = new SplitChannelHandler(),
|
||||
[VisionFlowType.取通道] = new SplitChannelHandler(),
|
||||
|
||||
[VisionFlowType.各通道最小值] = new MinChannelHandler(),
|
||||
[VisionFlowType.各通道最大值] = new MaxChannelHandler(),
|
||||
[VisionFlowType.显示图像到主页] = new ShowImageHandler(),
|
||||
[VisionFlowType.各通道最小值] = new MinChannelHandler(),
|
||||
[VisionFlowType.各通道最大值] = new MaxChannelHandler(),
|
||||
[VisionFlowType.显示图像到主页] = new ShowImageHandler(),
|
||||
|
||||
[VisionFlowType.从文件获取图片] = new GetFromFileHandler(),
|
||||
[VisionFlowType.从文件获取图片] = new GetFromFileHandler(),
|
||||
|
||||
[VisionFlowType.存到文件] = new SaveImageToFileHandler(),
|
||||
[VisionFlowType.从全局图像获取图片] = new GetFromGlobalImageHandler(),
|
||||
[VisionFlowType.存到全局图像] = new SaveImageToGlobalHandler(),
|
||||
[VisionFlowType.从局部图像获取图片] = new GetImageFromProcessHandler(),
|
||||
[VisionFlowType.存到局部图像] = new SaveImageToProcessHandler(),
|
||||
[VisionFlowType.拍照] = new GetFromCameraHandler(),
|
||||
[VisionFlowType.卡尺寻边] = new CaliperFindEdgeHandler(),
|
||||
[VisionFlowType.ORB匹配] = new ORBMatchHandler(),
|
||||
[VisionFlowType.卡尺找圆] = new CaliperFindCircleHandler(),
|
||||
[VisionFlowType.卡尺找旋转矩形] = new CaliperFindRectHandler(),
|
||||
[VisionFlowType.清除绘制] = new ClearDrawHandler(),
|
||||
[VisionFlowType.两线交点] = new TwoLineIntersectHandler(),
|
||||
[VisionFlowType.坐标转换] = new CoordinateTransformHandler(),
|
||||
[VisionFlowType.存到文件] = new SaveImageToFileHandler(),
|
||||
[VisionFlowType.从全局图像获取图片] = new GetFromGlobalImageHandler(),
|
||||
[VisionFlowType.存到全局图像] = new SaveImageToGlobalHandler(),
|
||||
[VisionFlowType.从局部图像获取图片] = new GetImageFromProcessHandler(),
|
||||
[VisionFlowType.存到局部图像] = new SaveImageToProcessHandler(),
|
||||
[VisionFlowType.拍照] = new GetFromCameraHandler(),
|
||||
[VisionFlowType.卡尺寻边] = new CaliperFindEdgeHandler(),
|
||||
[VisionFlowType.ORB匹配] = new ORBMatchHandler(),
|
||||
[VisionFlowType.卡尺找圆] = new CaliperFindCircleHandler(),
|
||||
[VisionFlowType.卡尺找旋转矩形] = new CaliperFindRectHandler(),
|
||||
[VisionFlowType.清除绘制] = new ClearDrawHandler(),
|
||||
[VisionFlowType.两线交点] = new TwoLineIntersectHandler(),
|
||||
[VisionFlowType.坐标转换] = new CoordinateTransformHandler(),
|
||||
[VisionFlowType.ROI解码] = new BarcodeDecodeHandler(),
|
||||
[VisionFlowType.微信解码] = new WeChatDecodeHandler(),
|
||||
|
||||
};
|
||||
[NotMapped]
|
||||
/// <summary>
|
||||
/// 全局模型
|
||||
/// 全局模型
|
||||
/// </summary>
|
||||
public GlobalModel GlobalModel { get; set; }
|
||||
|
||||
|
||||
[NotMapped]
|
||||
/// <summary>
|
||||
/// 绘制命令列表,用于在图像上绘制线条、圆形等图形
|
||||
/// 绘制命令列表,用于在图像上绘制线条、圆形等图形
|
||||
/// </summary>
|
||||
public List<DrawCommand> DrawCommands { get; set; } = [];
|
||||
public async Task RenderDrawAsync()
|
||||
@ -304,13 +306,13 @@ namespace PLCSharp.VVMs.Vision
|
||||
var commands = DrawCommands.ToList();
|
||||
|
||||
if (EditImageEdit != null)
|
||||
//编辑窗口显示
|
||||
//编辑窗口显示
|
||||
{
|
||||
|
||||
|
||||
foreach (var cmd in commands)
|
||||
{
|
||||
if (cmd.IsDrawnEdit) continue; // 如果已经绘制过,则跳过
|
||||
if (cmd.IsDrawnEdit) continue; // 如果已经绘制过,则跳过
|
||||
|
||||
switch (cmd.Shape)
|
||||
{
|
||||
@ -352,6 +354,31 @@ namespace PLCSharp.VVMs.Vision
|
||||
EditImageEdit.Draw(circle, (int)(cmd.Y1 - cmd.Radius), (int)(cmd.X1 - cmd.Radius));
|
||||
}
|
||||
break;
|
||||
case DrawCommand.Type.Text:
|
||||
var editText = new System.Windows.Controls.TextBlock
|
||||
{
|
||||
Text = cmd.Text,
|
||||
FontSize = cmd.FontSize,
|
||||
Foreground = new SolidColorBrush(cmd.Color),
|
||||
Tag = "DrawOverlay"
|
||||
};
|
||||
EditImageEdit.Draw(editText, (int)cmd.Y1, (int)cmd.X1);
|
||||
break;
|
||||
case DrawCommand.Type.Polygon:
|
||||
if (cmd.Points != null && cmd.Points.Length >= 2)
|
||||
{
|
||||
var poly = new System.Windows.Shapes.Polygon
|
||||
{
|
||||
Points = new System.Windows.Media.PointCollection(
|
||||
cmd.Points.Select(p => new System.Windows.Point(p.X, p.Y))),
|
||||
Stroke = new SolidColorBrush(cmd.Color),
|
||||
StrokeThickness = cmd.Thickness,
|
||||
Fill = Brushes.Transparent,
|
||||
Tag = "DrawOverlay"
|
||||
};
|
||||
EditImageEdit.Draw(poly);
|
||||
}
|
||||
break;
|
||||
}
|
||||
cmd.IsDrawnEdit = true;
|
||||
}
|
||||
@ -362,7 +389,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
{
|
||||
foreach (var cmd in commands)
|
||||
{
|
||||
if (cmd.IsDrawn) continue; // 如果已经绘制过,则跳过
|
||||
if (cmd.IsDrawn) continue; // 如果已经绘制过,则跳过
|
||||
|
||||
switch (cmd.Shape)
|
||||
{
|
||||
@ -404,13 +431,35 @@ namespace PLCSharp.VVMs.Vision
|
||||
imageEdit.Draw(circle, (int)(cmd.Y1 - cmd.Radius), (int)(cmd.X1 - cmd.Radius));
|
||||
}
|
||||
break;
|
||||
case DrawCommand.Type.Polygon:
|
||||
if (cmd.Points != null && cmd.Points.Length >= 2)
|
||||
{
|
||||
var poly = new System.Windows.Shapes.Polygon
|
||||
{
|
||||
Points = new System.Windows.Media.PointCollection(
|
||||
cmd.Points.Select(p => new System.Windows.Point(p.X, p.Y))),
|
||||
Stroke = new SolidColorBrush(cmd.Color),
|
||||
StrokeThickness = cmd.Thickness,
|
||||
Fill = Brushes.Transparent,
|
||||
Tag = "DrawOverlay"
|
||||
};
|
||||
imageEdit.Draw(poly);
|
||||
}
|
||||
break;
|
||||
case DrawCommand.Type.Text:
|
||||
var mainText = new System.Windows.Controls.TextBlock
|
||||
{
|
||||
Text = cmd.Text,
|
||||
FontSize = cmd.FontSize,
|
||||
Foreground = new SolidColorBrush(cmd.Color),
|
||||
Tag = "DrawOverlay"
|
||||
};
|
||||
imageEdit.Draw(mainText, (int)cmd.Y1, (int)cmd.X1);
|
||||
break;
|
||||
}
|
||||
cmd.IsDrawn = true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
@ -423,7 +472,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
|
||||
private ObservableCollection<ImageData> _Mats = [];
|
||||
/// <summary>
|
||||
/// 图像集合
|
||||
/// 图像集合
|
||||
/// </summary>
|
||||
public ObservableCollection<ImageData> Mats
|
||||
{
|
||||
@ -433,7 +482,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
|
||||
private ObservableDictionary<string, double> _ResultDoubles = [];
|
||||
/// <summary>
|
||||
/// 通用数值结果(如 ORB 匹配输出的 X/Y/角度偏移)
|
||||
/// 通用数值结果(如 ORB 匹配输出的 X/Y/角度偏移)
|
||||
/// </summary>
|
||||
public ObservableDictionary<string, double> ResultDoubles
|
||||
{
|
||||
@ -443,7 +492,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
|
||||
private ObservableCollection<LocalVariableItem> _Variables = [];
|
||||
/// <summary>
|
||||
/// 局部变量表(坐标点、直线、圆、矩形、数值),序列化保存在 JSON 中
|
||||
/// 局部变量表(坐标点、直线、圆、矩形、数值),序列化保存在 JSON 中
|
||||
/// </summary>
|
||||
public ObservableCollection<LocalVariableItem> Variables
|
||||
{
|
||||
|
||||
@ -65,6 +65,11 @@
|
||||
[FlowCategory("算法")]
|
||||
卡尺找旋转矩形 = 35,
|
||||
清除绘制 = 36,
|
||||
|
||||
[FlowCategory("算法")]
|
||||
ROI解码 = 37,
|
||||
[FlowCategory("算法")]
|
||||
微信解码 = 39,
|
||||
}
|
||||
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user