颜色面积
This commit is contained in:
parent
fbd1b0216a
commit
6057298e11
@ -297,6 +297,13 @@ namespace PLCSharp.Core.UserControls
|
||||
double width = _tempRoi.Width;
|
||||
double height = _tempRoi.Height;
|
||||
|
||||
// 点击不拖动(宽度或高度 < 1)视为误操作,不创建 pending,保持 drawing=true 让用户重试
|
||||
if (width < 1 || height < 1)
|
||||
{
|
||||
isMouseLeftButtonDown = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (_roiMode == ROIType.RotateRect)
|
||||
{
|
||||
_pendingRotateRoi = new RotateRectROI
|
||||
|
||||
@ -357,6 +357,17 @@ namespace PLCSharp.VVMs.Vision
|
||||
newFlow.BoolParams["EnableMirror"] = false;
|
||||
newFlow.StringParams["ResultVarName"] = "微信解码_Result";
|
||||
break;
|
||||
case VisionFlowType.颜色面积:
|
||||
newFlow.IntParams["HMin"] = 0;
|
||||
newFlow.IntParams["HMax"] = 180;
|
||||
newFlow.IntParams["SMin"] = 0;
|
||||
newFlow.IntParams["SMax"] = 255;
|
||||
newFlow.IntParams["VMin"] = 0;
|
||||
newFlow.IntParams["VMax"] = 255;
|
||||
newFlow.DoubleParams["AreaMinPercent"] = 0;
|
||||
newFlow.DoubleParams["AreaMaxPercent"] = 100;
|
||||
newFlow.StringParams["ResultVarName"] = "颜色面积_Result";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
@ -568,6 +579,9 @@ namespace PLCSharp.VVMs.Vision
|
||||
case VisionFlowType.微信解码:
|
||||
ContentRegion = new WeChatDecode();
|
||||
break;
|
||||
case VisionFlowType.颜色面积:
|
||||
ContentRegion = new ColorArea();
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
@ -1637,6 +1651,58 @@ namespace PLCSharp.VVMs.Vision
|
||||
}
|
||||
}
|
||||
|
||||
private AsyncDelegateCommand _DrawColorAreaROI;
|
||||
/// <summary>
|
||||
/// 绘制颜色面积 ROI 区域
|
||||
/// </summary>
|
||||
public AsyncDelegateCommand DrawColorAreaROI =>
|
||||
_DrawColorAreaROI ??= new AsyncDelegateCommand(ExecuteDrawColorAreaROIAsync);
|
||||
|
||||
private async Task ExecuteDrawColorAreaROIAsync()
|
||||
{
|
||||
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>
|
||||
|
||||
@ -0,0 +1,136 @@
|
||||
<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"
|
||||
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 DrawColorAreaROI}" 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>
|
||||
|
||||
<!-- HSV 范围 -->
|
||||
<GroupBox Header="HSV 范围">
|
||||
<Grid Margin="5">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
<RowDefinition />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="50" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="50" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- H -->
|
||||
<TextBlock Text="H 最小值" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Column="1" Text="{Binding SelectVisionFlow.IntParams[HMin], TargetNullValue=0, UpdateSourceTrigger=PropertyChanged}" />
|
||||
<TextBlock Grid.Column="2" Text="H 最大值" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Column="3" Text="{Binding SelectVisionFlow.IntParams[HMax], TargetNullValue=180, UpdateSourceTrigger=PropertyChanged}" />
|
||||
|
||||
<TextBlock Grid.Row="1" Text="S 最小值" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectVisionFlow.IntParams[SMin], TargetNullValue=0, UpdateSourceTrigger=PropertyChanged}" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="2" Text="S 最大值" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="1" Grid.Column="3" Text="{Binding SelectVisionFlow.IntParams[SMax], TargetNullValue=255, UpdateSourceTrigger=PropertyChanged}" />
|
||||
|
||||
<TextBlock Grid.Row="2" Text="V 最小值" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding SelectVisionFlow.IntParams[VMin], TargetNullValue=0, UpdateSourceTrigger=PropertyChanged}" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="2" Text="V 最大值" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="2" Grid.Column="3" Text="{Binding SelectVisionFlow.IntParams[VMax], 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 />
|
||||
</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">
|
||||
<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[ColorAreaPercent], 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[ColorPixelCount], Mode=OneWay}" IsReadOnly="True" Background="#FFF0F0F0" />
|
||||
|
||||
<TextBlock Grid.Row="2" Text="判定结果" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Row="2" Grid.Column="1"
|
||||
Text="{Binding SelectVisionFlow.StringParams[ColorAreaResult], Mode=OneWay, TargetNullValue=—}"
|
||||
IsReadOnly="True" Background="#FFF0F0F0"
|
||||
FontWeight="Bold" />
|
||||
</Grid>
|
||||
</GroupBox>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</UserControl>
|
||||
@ -0,0 +1,15 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// ColorArea.xaml 的交互逻辑
|
||||
/// </summary>
|
||||
public partial class ColorArea : UserControl
|
||||
{
|
||||
public ColorArea()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,135 @@
|
||||
using OpenCvSharp;
|
||||
using System.Linq;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Algorithm
|
||||
{
|
||||
/// <summary>
|
||||
/// 颜色面积Handler — 计算ROI内指定HSV范围的颜色面积占比,超出上下限输出NG
|
||||
/// </summary>
|
||||
public class ColorAreaHandler : 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区域!");
|
||||
|
||||
// 读取HSV范围
|
||||
int hMin = item.IntParams.TryGetValue("HMin", out int hm) ? Math.Clamp(hm, 0, 180) : 0;
|
||||
int hMax = item.IntParams.TryGetValue("HMax", out int hmx) ? Math.Clamp(hmx, 0, 180) : 180;
|
||||
int sMin = item.IntParams.TryGetValue("SMin", out int sm) ? Math.Clamp(sm, 0, 255) : 0;
|
||||
int sMax = item.IntParams.TryGetValue("SMax", out int smx) ? Math.Clamp(smx, 0, 255) : 255;
|
||||
int vMin = item.IntParams.TryGetValue("VMin", out int vm) ? Math.Clamp(vm, 0, 255) : 0;
|
||||
int vMax = item.IntParams.TryGetValue("VMax", out int vmx) ? Math.Clamp(vmx, 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;
|
||||
|
||||
// 输出变量名
|
||||
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);
|
||||
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));
|
||||
|
||||
// 转换到HSV
|
||||
using Mat hsv = new Mat();
|
||||
Cv2.CvtColor(roi, hsv, ColorConversionCodes.BGR2HSV);
|
||||
|
||||
// 创建HSV范围掩码
|
||||
using Mat mask = new Mat();
|
||||
var lower = new Scalar(hMin, sMin, vMin);
|
||||
var upper = new Scalar(hMax, sMax, vMax);
|
||||
Cv2.InRange(hsv, lower, upper, mask);
|
||||
|
||||
// 统计颜色像素数
|
||||
int colorPixelCount = Cv2.CountNonZero(mask);
|
||||
|
||||
// ROI总像素数
|
||||
int roiPixelCount = w * h;
|
||||
|
||||
// 计算面积百分比
|
||||
double areaPercent = roiPixelCount > 0
|
||||
? (double)colorPixelCount / roiPixelCount * 100.0
|
||||
: 0;
|
||||
|
||||
// 判断OK/NG
|
||||
bool isPass = areaPercent >= areaMinPercent && areaPercent <= areaMaxPercent;
|
||||
string result = isPass ? "OK" : "NG";
|
||||
|
||||
// 在原始图像上绘制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));
|
||||
|
||||
// 如果有多个较大轮廓,也画出来(面积大于最大轮廓20%的)
|
||||
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["ColorAreaPercent"] = Math.Round(areaPercent, 2);
|
||||
func.Params.ResultDoubles["ColorPixelCount"] = colorPixelCount;
|
||||
func.Params.ResultDoubles["ROIPixelCount"] = roiPixelCount;
|
||||
|
||||
// 写入判定结果到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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -33,6 +33,9 @@ namespace PLCSharp.VVMs.Vision.VisionFlowHandler
|
||||
public static DrawCommand FilledCircle(double cx, double cy, double r, Color color)
|
||||
=> new() { Shape = Type.Circle, X1 = cx, Y1 = cy, Radius = r, Color = color, Filled = true, Thickness = 0 };
|
||||
|
||||
public static DrawCommand TextBlock(double x, double y, string text, Color color, double fontSize = 12)
|
||||
=> new() { Shape = Type.Text, X1 = x, Y1 = y, Text = text, Color = color, FontSize = fontSize };
|
||||
|
||||
public static DrawCommand Polygon(System.Windows.Point[] pts, Color color, double thickness = 1)
|
||||
=> new() { Shape = Type.Polygon, Points = pts.Select(p => new Point(p.X, p.Y)).ToArray(), Color = color, Thickness = thickness };
|
||||
}
|
||||
|
||||
@ -293,6 +293,7 @@ namespace PLCSharp.VVMs.Vision
|
||||
[VisionFlowType.坐标转换] = new CoordinateTransformHandler(),
|
||||
[VisionFlowType.ROI解码] = new BarcodeDecodeHandler(),
|
||||
[VisionFlowType.微信解码] = new WeChatDecodeHandler(),
|
||||
[VisionFlowType.颜色面积] = new ColorAreaHandler(),
|
||||
|
||||
};
|
||||
[NotMapped]
|
||||
|
||||
Loading…
Reference in New Issue
Block a user