灰度面积

This commit is contained in:
tfarcraw 2026-07-16 02:20:33 +08:00
parent 76a9e50ea6
commit 4ada605d65
8 changed files with 313 additions and 34 deletions

View File

@ -368,6 +368,13 @@ namespace PLCSharp.VVMs.Vision
newFlow.DoubleParams["AreaMaxPercent"] = 100;
newFlow.StringParams["ResultVarName"] = "颜色面积_Result";
break;
case VisionFlowType.灰度面积:
newFlow.IntParams["GrayMin"] = 0;
newFlow.IntParams["GrayMax"] = 255;
newFlow.DoubleParams["AreaMinPercent"] = 0;
newFlow.DoubleParams["AreaMaxPercent"] = 100;
newFlow.StringParams["ResultVarName"] = "灰度面积_Result";
break;
default:
break;
}
@ -582,6 +589,9 @@ namespace PLCSharp.VVMs.Vision
case VisionFlowType.颜色面积:
ContentRegion = new ColorArea();
break;
case VisionFlowType.灰度面积:
ContentRegion = new GrayArea();
break;
}
@ -1703,6 +1713,58 @@ namespace PLCSharp.VVMs.Vision
}
}
private AsyncDelegateCommand _DrawGrayAreaROI;
/// <summary>
/// 绘制灰度面积 ROI 区域
/// </summary>
public AsyncDelegateCommand DrawGrayAreaROI =>
_DrawGrayAreaROI ??= new AsyncDelegateCommand(ExecuteDrawGrayAreaROIAsync);
private async Task ExecuteDrawGrayAreaROIAsync()
{
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>

View File

@ -1,4 +1,4 @@
<UserControl x:Class="PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm.ColorArea"
<UserControl x:Class="PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm.ColorArea"
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"
@ -89,22 +89,7 @@
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[AreaMaxPercent], TargetNullValue=100, UpdateSourceTrigger=LostFocus}" />
</Grid>
</GroupBox>
<!-- 结果变量 -->
<GroupBox Header="结果配置">
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="结果变量名" VerticalAlignment="Center" ToolTip="计算结果写入的局部变量名称" />
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.StringParams[ResultVarName], Mode=TwoWay, TargetNullValue=颜色面积_Result, UpdateSourceTrigger=LostFocus}" />
</Grid>
</GroupBox>
<!-- 执行结果 -->
<GroupBox Header="执行结果">
<Grid Margin="5">

View File

@ -1,4 +1,4 @@
using OpenCvSharp;
using OpenCvSharp;
using System.Linq;
using System.Windows.Media;
@ -34,10 +34,6 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
double areaMinPercent = item.DoubleParams.TryGetValue("AreaMinPercent", out double minP) ? minP : 0;
double areaMaxPercent = item.DoubleParams.TryGetValue("AreaMaxPercent", out double maxP) ? maxP : 100;
// 输出变量名
string resultVar = item.StringParams.TryGetValue("ResultVarName", out var rv) && !string.IsNullOrEmpty(rv)
? rv : "颜色面积_Result";
// 裁剪ROI
int x = Math.Clamp((int)roiLeft, 0, src.Width - 1);
int y = Math.Clamp((int)roiTop, 0, src.Height - 1);
@ -115,18 +111,12 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
func.Params.ResultDoubles["ColorPixelCount"] = colorPixelCount;
func.Params.ResultDoubles["ROIPixelCount"] = roiPixelCount;
// 写入判定结果到StringParams(用于UI显示)
// 写入OK/NG到ResultString
func.ResultString = result;
func.ResultDouble = areaPercent;
// 写入判定结果到StringParams(用于UI绑定显示)
item.StringParams["ColorAreaResult"] = result;
// 写入结果变量
var variable = func.Params.Variables.FirstOrDefault(v => v.Name == resultVar);
if (variable == null)
{
variable = new LocalVariableItem(resultVar, "String", result);
System.Windows.Application.Current.Dispatcher.Invoke(() => func.Params.Variables.Add(variable));
}
variable.RawValue = $"{result}|面积比:{areaPercent:F1}%|颜色像素:{colorPixelCount}|ROI像素:{roiPixelCount}";
item.Flow.Done = true;
_ = func.RenderDrawAsync();
return true;

View File

@ -0,0 +1,109 @@
<UserControl x:Class="PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm.GrayArea"
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="500" d:DesignWidth="300">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<!-- ROI 区域 -->
<GroupBox Header="ROI 区域">
<StackPanel>
<Button Height="25" Margin="5" Command="{Binding DrawGrayAreaROI}" 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.Column="2" Margin="3,0" Text="Top" VerticalAlignment="Center" />
<TextBox 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 />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60" />
<ColumnDefinition />
<ColumnDefinition Width="60" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="最小值" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.IntParams[GrayMin], TargetNullValue=0, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Grid.Column="2" Text="最大值" VerticalAlignment="Center" />
<TextBox Grid.Column="3" Text="{Binding SelectVisionFlow.IntParams[GrayMax], TargetNullValue=255, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</GroupBox>
<!-- 面积阈值 -->
<GroupBox Header="面积阈值(%)">
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="下限 %" VerticalAlignment="Center" ToolTip="灰度面积占比低于此值判定为 NG" />
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[AreaMinPercent], TargetNullValue=0, UpdateSourceTrigger=LostFocus}" />
<TextBlock Grid.Row="1" Text="上限 %" VerticalAlignment="Center" ToolTip="灰度面积占比高于此值判定为 NG" />
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectVisionFlow.DoubleParams[AreaMaxPercent], TargetNullValue=100, UpdateSourceTrigger=LostFocus}" />
</Grid>
</GroupBox>
<!-- 执行结果 -->
<GroupBox Header="执行结果">
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="面积占比" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Text="{Binding SelectedVisionFunction.Params.ResultDoubles[GrayAreaPercent], Mode=OneWay, StringFormat={}{0:F1}%}" IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="1" Text="目标像素" VerticalAlignment="Center" />
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectedVisionFunction.Params.ResultDoubles[GrayPixelCount], Mode=OneWay}" IsReadOnly="True" Background="#FFF0F0F0" />
<TextBlock Grid.Row="2" Text="判定结果" VerticalAlignment="Center" />
<TextBox Grid.Row="2" Grid.Column="1"
Text="{Binding SelectVisionFlow.StringParams[GrayAreaResult], Mode=OneWay, TargetNullValue=—}"
IsReadOnly="True" Background="#FFF0F0F0"
FontWeight="Bold" />
</Grid>
</GroupBox>
</StackPanel>
</ScrollViewer>
</UserControl>

View File

@ -0,0 +1,15 @@
using System.Windows.Controls;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
{
/// <summary>
/// GrayArea.xaml 的交互逻辑
/// </summary>
public partial class GrayArea : UserControl
{
public GrayArea()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,115 @@
using OpenCvSharp;
using System.Windows.Media;
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
{
/// <summary>
/// 灰度面积Handler — 计算ROI内指定灰度范围的面积占比,超出上下限输出NG
/// </summary>
public class GrayAreaHandler : IVisionFlowHandler
{
public VisionFlowType Type => VisionFlowType.灰度面积;
public bool Execute(VisionFunction func, VisionFlow item)
{
var src = func.Src ?? throw new Exception("请先获取图片!");
// 读取ROI参数
if (!item.DoubleParams.TryGetValue("ROILeft", out double roiLeft) ||
!item.DoubleParams.TryGetValue("ROITop", out double roiTop) ||
!item.DoubleParams.TryGetValue("ROIWidth", out double roiWidth) ||
!item.DoubleParams.TryGetValue("ROIHeight", out double roiHeight))
throw new Exception("ROI未配置,请先框选ROI区域!");
// 读取灰度范围
int grayMin = item.IntParams.TryGetValue("GrayMin", out int gm) ? Math.Clamp(gm, 0, 255) : 0;
int grayMax = item.IntParams.TryGetValue("GrayMax", out int gmx) ? Math.Clamp(gmx, 0, 255) : 255;
// 读取面积百分比上下限
double areaMinPercent = item.DoubleParams.TryGetValue("AreaMinPercent", out double minP) ? minP : 0;
double areaMaxPercent = item.DoubleParams.TryGetValue("AreaMaxPercent", out double maxP) ? maxP : 100;
// 裁剪ROI
int x = Math.Clamp((int)roiLeft, 0, src.Width - 1);
int y = Math.Clamp((int)roiTop, 0, src.Height - 1);
int w = Math.Min((int)roiWidth, src.Width - x);
int h = Math.Min((int)roiHeight, src.Height - y);
if (w <= 0 || h <= 0)
throw new Exception("ROI超出图像范围!");
using Mat roi = new Mat(src, new OpenCvSharp.Rect(x, y, w, h));
// 转灰度
using Mat gray = new Mat();
if (roi.Channels() == 3)
Cv2.CvtColor(roi, gray, ColorConversionCodes.BGR2GRAY);
else
roi.CopyTo(gray);
// 创建灰度范围掩码
using Mat mask = new Mat();
Cv2.InRange(gray, new Scalar(grayMin), new Scalar(grayMax), mask);
// 统计目标像素数
int targetPixelCount = Cv2.CountNonZero(mask);
// ROI总像素数
int roiPixelCount = w * h;
// 计算面积百分比
double areaPercent = roiPixelCount > 0
? (double)targetPixelCount / roiPixelCount * 100.0
: 0;
func.ResultDouble = areaPercent;
// 判断OK/NG
bool isPass = areaPercent >= areaMinPercent && areaPercent <= areaMaxPercent;
string result = isPass ? "OK" : "NG";
func.ResultString = result;
// 在原始图像上绘制ROI边框
func.DrawCommands.Add(DrawCommand.Line(x, y, x + w, y, Colors.Lime, 2));
func.DrawCommands.Add(DrawCommand.Line(x + w, y, x + w, y + h, Colors.Lime, 2));
func.DrawCommands.Add(DrawCommand.Line(x + w, y + h, x, y + h, Colors.Lime, 2));
func.DrawCommands.Add(DrawCommand.Line(x, y + h, x, y, Colors.Lime, 2));
// 绘制目标区域的轮廓
using Mat maskForContour = mask.Clone();
Cv2.FindContours(maskForContour, out Point[][] contours, out _, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
if (contours.Length > 0)
{
var sorted = contours.OrderByDescending(c => Cv2.ContourArea(c)).ToArray();
var largest = sorted[0];
var offsetPts = largest.Select(p => new System.Windows.Point(p.X + x, p.Y + y)).ToArray();
func.DrawCommands.Add(DrawCommand.Polygon(offsetPts, Colors.Yellow, 2));
double maxArea = Cv2.ContourArea(largest);
foreach (var contour in sorted.Skip(1))
{
if (Cv2.ContourArea(contour) >= maxArea * 0.2)
{
var pts = contour.Select(p => new System.Windows.Point(p.X + x, p.Y + y)).ToArray();
func.DrawCommands.Add(DrawCommand.Polygon(pts, Colors.Yellow, 1));
}
}
}
// 在图像上显示结果文本
string text = $"灰度面积: {areaPercent:F1}% [{result}]";
func.DrawCommands.Add(DrawCommand.TextBlock(x, y - 20 < 0 ? y + h + 5 : y - 20, text, Colors.Cyan, 14));
// 写入结果到ResultDoubles
func.Params.ResultDoubles["GrayAreaPercent"] = Math.Round(areaPercent, 2);
func.Params.ResultDoubles["GrayPixelCount"] = targetPixelCount;
func.Params.ResultDoubles["ROIPixelCount"] = roiPixelCount;
// 写入判定结果到StringParams(用于UI绑定显示)
item.StringParams["GrayAreaResult"] = result;
item.Flow.Done = true;
_ = func.RenderDrawAsync();
return true;
}
}
}

View File

@ -109,7 +109,7 @@ namespace PLCSharp.VVMs.Vision
public double ResultDouble { get; set; }
[NotMapped]
public string RusultString { get; set; }
public string ResultString { get; set; }
[NotMapped]
public List<Pos> ResultPosList { get; set; } = [];
@ -130,7 +130,7 @@ namespace PLCSharp.VVMs.Vision
public List<double> ResultDoubleList { get; set; } = [];
[NotMapped]
public List<string> RusultStringList { get; set; } = [];
public List<string> ResultStringList { get; set; } = [];
#endregion
@ -336,6 +336,7 @@ namespace PLCSharp.VVMs.Vision
[VisionFlowType.ROI解码] = new BarcodeDecodeHandler(),
[VisionFlowType.微信解码] = new WeChatDecodeHandler(),
[VisionFlowType.颜色面积] = new ColorAreaHandler(),
[VisionFlowType.灰度面积] = new GrayAreaHandler(),
};
[NotMapped]

View File

@ -69,6 +69,8 @@
[FlowCategory("算法")]
ROI解码 = 37,
[FlowCategory("算法")]
灰度面积 = 38,
[FlowCategory("算法")]
微信解码 = 39,
}