46 lines
1.8 KiB
C#
46 lines
1.8 KiB
C#
using OpenCvSharp;
|
|
|
|
namespace PLCSharp.VVMs.Vision.VisionFlowHandler.Processing
|
|
{
|
|
/// <summary>
|
|
/// 直方图均衡化 — 增强图像对比度。支持全局 EqualizeHist 和自适应 CLAHE。
|
|
/// </summary>
|
|
public class HistogramEqualizeHandler : IVisionFlowHandler
|
|
{
|
|
public VisionFlowType Type => VisionFlowType.直方图均衡化;
|
|
|
|
public bool Execute(VisionFunction func, VisionFlow item)
|
|
{
|
|
var src = func.Src;
|
|
if (src == null || src.Empty()) { item.Flow.FailMessage = "请先获取图片!"; return false; }
|
|
|
|
// 确保参数存在,避免 XAML 绑定报红框
|
|
if (!item.IntParams.ContainsKey("Method")) item.IntParams["Method"] = 0;
|
|
if (!item.DoubleParams.ContainsKey("ClipLimit")) item.DoubleParams["ClipLimit"] = 2.0;
|
|
if (!item.IntParams.ContainsKey("TileSize")) item.IntParams["TileSize"] = 8;
|
|
|
|
int method = item.IntParams.TryGetValue("Method", out int m) ? m : 0; // 0=EqualizeHist, 1=CLAHE
|
|
double clipLimit = item.DoubleParams.TryGetValue("ClipLimit", out double cl) ? cl : 2.0;
|
|
int tileSize = item.IntParams.TryGetValue("TileSize", out int ts) ? ts : 8;
|
|
|
|
// 灰度化
|
|
if (src.Channels() == 3)
|
|
Cv2.CvtColor(src, src, ColorConversionCodes.BGR2GRAY);
|
|
|
|
if (method == 0)
|
|
{
|
|
// 全局直方图均衡化
|
|
Cv2.EqualizeHist(src, src);
|
|
}
|
|
else
|
|
{
|
|
// 自适应直方图均衡化 (CLAHE)
|
|
using var clahe = Cv2.CreateCLAHE(clipLimit, new Size(tileSize, tileSize));
|
|
clahe.Apply(src, src);
|
|
}
|
|
|
|
item.Flow.Done = true;
|
|
return true;
|
|
}
|
|
}
|
|
} |