libdmtx解码

This commit is contained in:
tfarcraw 2026-07-30 18:38:10 +08:00
parent b964cd0102
commit 92d9eff676
21 changed files with 236 additions and 72 deletions

View File

@ -18,9 +18,10 @@
<!--<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" />-->
<PackageReference Include="DotNetCore.Natasha.CSharp.Compiler" Version="10.1.2.2" />
<PackageReference Include="DotNetCore.Natasha.CSharp.Compiler.Domain" Version="10.0.0.1" />
<PackageReference Include="Libdmtx.Net" Version="0.7.9-dev.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.17" />
<PackageReference Include="MiniExcel" Version="1.45.0" />
<PackageReference Include="OpenCvSharp5.Windows" Version="5.0.0.20260718" />
<PackageReference Include="OpenCvSharp5.Windows" Version="5.0.0.20260726" />
<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" />-->

View File

@ -495,6 +495,8 @@ public partial class VisionConfigViewModel
newFlow.BoolParams["EnableMirror"] = false;
newFlow.BoolParams["EnableUpscale"] = true;
newFlow.BoolParams["UsePureBarcode"] = false;
newFlow.IntParams["DM_MinEdge"] = 0;
newFlow.IntParams["DM_MaxEdge"] = 0;
newFlow.StringParams["ResultVarName"] = "解码结果";
break;

View File

@ -52,6 +52,8 @@
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
@ -83,6 +85,12 @@
<TextBlock Grid.Row="4" Text="结果变量名" VerticalAlignment="Center" ToolTip="解码结果写入的局部变量名称" />
<TextBox Grid.Row="4" Grid.Column="1" Text="{Binding SelectVisionFlow.StringParams[ResultVarName], Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="5" Text="码最小边(px)" VerticalAlignment="Center" ToolTip="DataMatrix 的最小边缘长度(像素),0=不限制" />
<TextBox Grid.Row="5" Grid.Column="1" Text="{Binding SelectVisionFlow.IntParams[DM_MinEdge], Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="6" Text="码最大边(px)" VerticalAlignment="Center" ToolTip="DataMatrix 的最大边缘长度(像素),0=不限制" />
<TextBox Grid.Row="6" Grid.Column="1" Text="{Binding SelectVisionFlow.IntParams[DM_MaxEdge], Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />
</Grid>
</GroupBox>

View File

@ -1,6 +1,7 @@
#nullable enable
using OpenCvSharp;
using Libdmtx;
using System.Runtime.InteropServices;
using System.Windows.Media;
using ZXing;
@ -38,6 +39,8 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
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;
int dmMinEdge = item.IntParams.TryGetValue("DM_MinEdge", out int mine) ? mine : 0;
int dmMaxEdge = item.IntParams.TryGetValue("DM_MaxEdge", out int maxe) ? maxe : 0;
// 2. ROI 裁剪
Mat roiMat;
@ -99,6 +102,15 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
// 记录实际 ROI 偏移 + 放大系数,供绘制时反向映射
double scaleInv = 1.0 / actualScale;
// 绘制 ROI 边框(蓝色)
if (hasRoi)
{
func.DrawCommands.Add(DrawCommand.Line(roiLeft, roiTop, roiLeft + imgW, roiTop, Colors.DodgerBlue, 1));
func.DrawCommands.Add(DrawCommand.Line(roiLeft + imgW, roiTop, roiLeft + imgW, roiTop + imgH, Colors.DodgerBlue, 1));
func.DrawCommands.Add(DrawCommand.Line(roiLeft + imgW, roiTop + imgH, roiLeft, roiTop + imgH, Colors.DodgerBlue, 1));
func.DrawCommands.Add(DrawCommand.Line(roiLeft, roiTop + imgH, roiLeft, roiTop, Colors.DodgerBlue, 1));
}
// 6. PureBarcode 模式:仅当 ROI 紧密框住码时生效,绕过最脆弱的 WhiteRectangleDetector
if (usePureBarcode && hasRoi)
{
@ -126,18 +138,6 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
usedPipeline = pipeline;
break;
}
// 管线 0 额外尝试垂直翻转
if (pipeline == 0)
{
Cv2.Flip(processed, processed, FlipMode.Y);
result = TryDecodeWithReader(processed, formats);
if (result != null)
{
usedPipeline = pipeline;
break;
}
}
}
// 8. 输出
@ -146,6 +146,53 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
return OutputResult(func, item, result, roiLeft, roiTop, workW, workH, scaleInv, usedPipeline);
}
// ── ZXing 失败,用 libdmtx 兜底(仅 DataMatrix 格式) ──
if (DecodeTypeIncludesDataMatrix(decodeType))
{
int libPipeline = -1;
DecodeResult[]? libResults = null;
var libOptions = new DecodeOptions { TimeoutMs = 100, MaxCodes = 10, ScanGap = 1, Shrink = 1,
EdgeMin = dmMinEdge > 0 ? dmMinEdge : null,
EdgeMax = dmMaxEdge > 0 ? dmMaxEdge : null,
};
for (int pipeline = 0; pipeline < 6 && (libResults == null || libResults.Length == 0); pipeline++)
{
using var processed = PreparePipeline(workingGray, pipeline);
if (processed == null || processed.Empty())
continue;
libResults = TryDecodeWithLibDmtx(processed, libOptions);
if (libResults != null && libResults.Length > 0)
{
libPipeline = pipeline;
break;
}
}
// 镜像 ROI 的 Y 坐标修正
if (enableMirror && libResults != null)
{
foreach (var r in libResults)
{
if (r.Corners != null)
{
for (int j = 0; j < r.Corners.Length; j++)
{
var (x, y) = r.Corners[j];
r.Corners[j] = (x, workH - 1 - y);
}
}
}
}
if (libResults != null && libResults.Length > 0)
{
return OutputLibDmtxResult(func, item, libResults, roiLeft, roiTop, workW, workH, scaleInv, libPipeline);
}
}
// 解码失败
item.StringParams["DecodeResult"] = "";
item.IntParams["UsedPipeline"] = -1;
@ -313,6 +360,8 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
}
existingVar.RawValue = new Barcode(new Pos(boxCX, boxCY, 0, 0), decodedText);
_ = func.RenderDrawAsync();
item.Flow.Done = true;
return true;
}
@ -385,5 +434,140 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
_ => [BarcodeFormat.DATA_MATRIX],
};
}
/// <summary>判断是否包含 DataMatrix 格式</summary>
private static bool DecodeTypeIncludesDataMatrix(int decodeType) => decodeType switch
{
0 => true, // DataMatrix
2 => true, // DataMatrix + QR
3 => true, // DataMatrix + QR + AZTEC + PDF_417
_ => false, // 1 = QR only, 其他
};
// ── libdmtx 兜底解码 ──────────────────────────────────
/// <summary>用 libdmtx 解码(期望 RGB 格式,需要灰度→RGB 转换)</summary>
private static DecodeResult[]? TryDecodeWithLibDmtx(Mat gray, DecodeOptions options)
{
int w = gray.Width;
int h = gray.Height;
byte[] grayPixels = new byte[w * h];
Marshal.Copy(gray.Data, grayPixels, 0, grayPixels.Length);
byte[] rgbPixels = new byte[w * h * 3];
for (int i = 0; i < grayPixels.Length; i++)
{
byte v = grayPixels[i];
int j = i * 3;
rgbPixels[j] = v; // R
rgbPixels[j + 1] = v; // G
rgbPixels[j + 2] = v; // B
}
try
{
return Dmtx.Decode(rgbPixels, w, h, w * 3, options);
}
catch
{
return null;
}
}
/// <summary>输出 libdmtx 解码结果</summary>
private static bool OutputLibDmtxResult(
VisionFunction func, VisionFlow item, DecodeResult[] results,
int roiLeft, int roiTop, int workW, int workH, double scaleInv, int pipeline)
{
string joinedText = string.Join(" | ", results.Select(r => r.Text));
item.StringParams["DecodeResult"] = joinedText;
item.IntParams["UsedPipeline"] = pipeline;
func.Params.ResultDoubles["DecodeSuccess"] = 1;
func.Params.ResultDoubles["DecodeCount"] = results.Length;
for (int i = 0; i < results.Length; i++)
{
var result = results[i];
var rawPts = result.Corners?.Length > 0
? result.Corners
.Select(c => new System.Windows.Point(
c.Item1 * scaleInv + roiLeft,
c.Item2 * scaleInv + roiTop))
.ToArray()
: [];
// libdmtx 角点顺序:[0]=左上, [1]=左下, [2]=右上, [3]=右下
// 重排为顺时针:[0]=左上, [2]=右上, [3]=右下, [1]=左下
var pts = rawPts.Length == 4
? [rawPts[0], rawPts[2], rawPts[3], rawPts[1]]
: rawPts;
if (pts.Length == 4)
{
func.DrawCommands.Add(DrawCommand.Polygon(pts, 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 = results.Length > 1 ? $"[{i + 1}] " : "";
string text = result.Text;
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}] " + (result.Text.Length > 40 ? result.Text[..40] + "…" : result.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 < results.Length; i++)
{
var result = results[i];
var corners = result.Corners;
double boxCX = corners is { Length: >= 4 }
? corners.Select(c => c.Item1 * scaleInv + roiLeft).Average()
: 0;
double boxCY = corners is { Length: >= 4 }
? corners.Select(c => c.Item2 * scaleInv + roiTop).Average()
: 0;
string varName = results.Length > 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), result.Text);
}
_ = func.RenderDrawAsync();
item.Flow.Done = true;
return true;
}
}
}

View File

@ -320,6 +320,8 @@ namespace PLCSharp.VVMs.Vision
}
else if (item.Flow.CheckStepTime(flow.TimeoutSeconds))
{
Sw.Stop();
item.CT = Math.Round(Sw.ElapsedMilliseconds / 1000.0, 3); // 转换为秒
item.Flow.FailMessage = $"执行超时(>{flow.TimeoutSeconds:F0}秒)";
flow.IsSuccess = false;
flow.Done = true;

View File

@ -13,7 +13,7 @@ using System.Windows;
using System.Windows.Input;
using Document = Microsoft.CodeAnalysis.Document;
namespace PLCSharp.VVMs.Workflows.Script
namespace PLCSharp.VVMs.Workflows
{
/// <summary>
/// CustomTextEditor
@ -55,7 +55,7 @@ namespace PLCSharp.VVMs.Workflows.Script
ICSharpCode.AvalonEdit.Search.SearchPanel.Install(this);
DataContextChanged += OnDataContextChanged;
TextArea.Caret.PositionChanged += CaretOnPositionChanged;
Loaded += (s, e) => SetValue(ICSharpCode.AvalonEdit.TextEditor.FontSizeProperty, FontSize);
Loaded += (s, e) => SetValue(System.Windows.Controls.Control.FontSizeProperty, FontSize);
}
private int caretOffset;
@ -235,7 +235,7 @@ namespace PLCSharp.VVMs.Workflows.Script
var newSize = (double)e.NewValue;
// 设置到 WPF 控件的 FontSize 依赖属性上使渲染生效
// (这是基类 Control.FontSizeProperty,不是本类的 FontSizeProperty,不会递归)
editor.SetValue(ICSharpCode.AvalonEdit.TextEditor.FontSizeProperty, newSize);
editor.SetValue(System.Windows.Controls.Control.FontSizeProperty, newSize);
editor.FontSizeChanged?.Invoke(editor, newSize);
}

View File

@ -0,0 +1,13 @@

case 1:
if (CurrController.DI[X001].Status)
{
flow.Step++;
}
else if (flow.CheckStepTime(5))
{
throw new Exception("等待DI输入超时!");
}
break;

View File

@ -0,0 +1 @@
CurrController.SetDQ(Y001, 1); // 0=通, 1=断

View File

@ -1,40 +0,0 @@
//IO操作
//读取DI输入、设置DQ输出
case 0:
CurrController = globalModel.ControllersModel.Controllers.FirstOrDefault(c => c.ControllerNo == 0);
flow.Step++;
break;
//等待DI输入信号
case 1:
if (CurrController.DI[X001].Status)
{
flow.Step++;
}
else if (flow.CheckStepTime(5))
{
throw new Exception("等待DI输入超时!");
}
break;
//设置DQ输出
case 2:
CurrController.SetDQ(Y001, 1); // 1=通, 0=断
flow.Step++;
break;
//延时后关闭输出
case 3:
if (flow.CheckStepTime(2)) // 等待2秒
{
var dqOff = CurrController.DQ.FirstOrDefault(d => d.Name == "DQ名称");
if (dqOff != null)
{
CurrController.SetDQ(dqOff.Number, 0);
}
flow.Step++;
}
break;

View File

@ -1,10 +1,4 @@
//机器人相对运动
case 4:
CurrRobot = globalModel.GetRobot("机器人名称"); //如果前面已经获取过机器人对象,这里可以省略
flow.Step++;
break;
case 6:
CurrRobot.Jog("点位名称", "X+", 10);
flow.Step++;

View File

@ -1,8 +1,4 @@
//机器人绝对运动
case 3:
CurrRobot = globalModel.GetRobot("机器人名称");//如果前面已经获取过机器人对象,这里可以省略
flow.Step++;
break;
case 4:
CurrRobot.RunPoint("点位名称");
flow.Step++;

View File

@ -0,0 +1 @@
CurrVariable = globalModel.GetVariable("变量名");

View File

@ -0,0 +1 @@
CurrController = globalModel.ControllersModel.Controllers.FirstOrDefault(c => c.ControllerNo == 0);

View File

@ -0,0 +1,2 @@
CurrRobot = globalModel.GetRobot("机器人名称");

View File

@ -1,6 +1,6 @@
//全局变量
case 2:
CurrVariable = globalModel.GetVariable("变量名");//如果前面已经获取,这里可以省略
CurrVariable = globalModel.GetVariable("变量名");//如果前面已经获取,这里可以删除
CurrVariable.Value = 100; // 设置变量值
flow.Step++;
break;

View File

@ -1,4 +1,4 @@
namespace PLCSharp.VVMs.Workflows.Script
namespace PLCSharp.VVMs.Workflows
{
/// <summary>
/// 快捷代码片段项

View File

@ -6,7 +6,6 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:PLCSharp.VVMs.Workflows"
xmlns:editor="clr-namespace:PLCSharp.VVMs.Workflows.Script"
prism:ViewModelLocator.AutoWireViewModel="True"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type=local:WorkflowConfigViewModel}"
@ -48,7 +47,7 @@
</ScrollViewer>
</GroupBox>
<GroupBox Grid.Column="1" Margin="3" Header="{Binding SelectedFlowTask.Name}">
<editor:CustomTextEditor x:Name="editor"
<local:CustomTextEditor x:Name="editor"
Margin="5"
Text="{Binding SelectedFlowTask.Code}"
FontSize="20" FontFamily="Consolas"
@ -70,7 +69,7 @@
<MenuItem HorizontalAlignment="Center" Command="{Binding Save}" Header="保存" InputGestureText="Ctrl+S" />
</ContextMenu>
</avalonEdit:TextEditor.ContextMenu>
</editor:CustomTextEditor>
</local:CustomTextEditor>
</GroupBox>
<GridSplitter Grid.Column="2" HorizontalAlignment="Stretch" Background="DimGray" />

View File

@ -1,6 +1,5 @@
using PLCSharp.Core.Prism;
using PLCSharp.Models;
using PLCSharp.VVMs.Workflows.Script;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Events;

View File

@ -120,6 +120,7 @@ public class Extension_" + newTask.ID.ToString().Replace("-", "") +
{
if (System.Windows.MessageBox.Show($"确认删除任务 [{SelectedTask.Name}]?", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes)
break;
SelectedTask.Stop();
var task = _DatasContext.Workflows.Where(c => c.ID == SelectedTask.ID).FirstOrDefault();
if (task != null)
{