以下是一个高性能的Threshold实现,支持Halcon式多区间阈值分割,并结合OpenCV特性进行深度优化:
using OpenCvSharp;
using System;
using System.Collections.Generic;
public static class HalconThreshold
{
/// <summary>
/// 增强型阈值分割(模拟Halcon Threshold功能)
/// </summary>
/// <param name="src">输入图像(自动处理8UC1/8UC3/32FC1)</param>
/// <param name="ranges">阈值区间列表(支持多区间)</param>
/// <param name="outputType">输出模式:0-二值图像模式,1-轮廓集合模式</param>
/// <param name="autoScale">是否自动归一化浮点图像(默认true)</param>
/// <returns>根据outputType返回Mat或List<Point[][]></returns>
public static object Threshold(
Mat src,
IEnumerable<Tuple<double, double>> ranges,
int outputType = 0,
bool autoScale = true)
{
// =============== 预处理阶段 ===============
Mat processed = PreprocessImage(src, autoScale);
// =============== 核心阈值处理 ===============
List<Mat> regions = ExecuteMultiThreshold(processed, ranges);
// =============== 结果转换 ===============
return outputType switch
{
0 => MergeBinaryMasks(regions), // 二值图像模式
1 => ExtractAllContours(regions), // 轮廓模式
_ => throw new ArgumentException("不支持的输出模式")
};
}
#region 核心实现
// 图像预处理(自动通道转换+归一化)
private static Mat PreprocessImage(Mat src, bool autoScale)
{
Mat output = new Mat();
// 通道处理
if (src.Channels() == 3) // 自动转换彩色图像为灰度
{
Cv2.CvtColor(src, output, ColorConversionCodes.BGR2GRAY);
}
else if(src.Type().Channels == 1)
{
output = src.Clone();
}
// 浮点归一化
if(autoScale && output.Depth() == MatType.CV_32F)
{
double minVal = 0, maxVal = 0;
Cv2.MinMaxLoc(output, out minVal, out maxVal);
output.ConvertTo(output, MatType.CV_8UC1, 255.0/(maxVal - minVal), -minVal*255.0/(maxVal - minVal));
}
return output;
}
// 并行多区间阈值处理
private static List<Mat> ExecuteMultiThreshold(Mat src, IEnumerable<Tuple<double, double>> ranges)
{
var regions = new List<Mat>();
byte[] lut = new byte[256]; // LUT优化缓存
foreach (var range in ranges)
{
<