625 lines
28 KiB
C#
625 lines
28 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.Text;
|
||
|
||
namespace FpCollect.Agent.Analysis;
|
||
|
||
/// <summary>
|
||
/// 指纹纹型自动分类结果。
|
||
/// </summary>
|
||
/// <param name="Pattern">纹型:"斗形纹" / "箕形纹" / "弧形纹" / "无法识别"。</param>
|
||
/// <param name="RidgeCount">核心点与最近三角点连线间的嵴线计数。</param>
|
||
/// <param name="CoreX">核心点 X(像素坐标;无核心时为 −1)。</param>
|
||
/// <param name="CoreY">核心点 Y(像素坐标;无核心时为 −1)。</param>
|
||
/// <param name="OrientationPreview">分块方向样本(640×640 时恰为 40×40 块),每项为 [块中心x, 块中心y, θ弧度],空块不输出。</param>
|
||
/// <param name="Notes">关键中间结果摘要(中文):有效块比例、一致性、核心/三角数量与坐标、判型依据、计数详情。</param>
|
||
public record FpResult(string Pattern, int RidgeCount, double CoreX, double CoreY, List<double[]> OrientationPreview, string Notes);
|
||
|
||
/// <summary>
|
||
/// 指纹纹型自动分类 + 嵴线计数 —— 经典指纹分析流水线的纯托管实现(无第三方库、无 unsafe):
|
||
/// ① 预处理(对比度拉伸 + 3×3 中值滤波)
|
||
/// ② 分块方向场(Sobel 梯度协方差法)+ 一次向量平滑
|
||
/// ③ Poincaré index 奇异点检测(核心 Core / 三角 Delta)
|
||
/// ④ 纹型判定(弧形/箕形/斗形)
|
||
/// ⑤ 核心—三角连线过均值交叉嵴线计数
|
||
/// 输入为行优先 8bit 灰度(采集仪 640×640,背景≈220 亮,纹线≈暗)。
|
||
/// 热路径全部使用一维数组与 for 循环(无 LINQ),640×640 全流程目标 < 300ms。
|
||
/// </summary>
|
||
public static class FpClassifier
|
||
{
|
||
// ---------------- 可调参数(联调时优先动这里) ----------------
|
||
|
||
/// <summary>方向场分块边长(像素)。640/16 = 40×40 块,恰好满足前端 40×40 方向叠加。</summary>
|
||
private const int BlockSize = 16;
|
||
|
||
/// <summary>允许的最小输入尺寸:不足 3×3 个方向块时 Poincaré 邻域无法构成,直接判退化。</summary>
|
||
private const int MinImageSize = 3 * BlockSize;
|
||
|
||
/// <summary>允许的最大输入尺寸(防 width*height 整型溢出与异常大图)。</summary>
|
||
private const int MaxImageSize = 8192;
|
||
|
||
/// <summary>块内灰度标准差低于此值视为平坦块(背景/无效区),方向置空。</summary>
|
||
private const double FlatBlockStd = 6.0;
|
||
|
||
/// <summary>对比度拉伸判定:2%~98% 分位灰度差不足此值视为全黑/全白/近均匀图。</summary>
|
||
private const int MinContrastRange = 8;
|
||
|
||
/// <summary>
|
||
/// Poincaré index 核心判定下限(弧度)。经典理论(Maltoni《Handbook of Fingerprint Recognition》):
|
||
/// 箕形核心 Δ≈+180°、斗形中心 Δ≈+360°、三角 Δ≈−180°;任务书区间 (180°,270°]/[−270°,−180°)
|
||
/// 以 ±180° 为中心但开边界恰在理想值上,离散 8 邻域实测常落在 180° 两侧并需覆盖斗形 360°,
|
||
/// 故实现取 ±10% 容差并覆盖到 ±360°(任务书区间为本区间的子集),阈值集中在此便于联调收紧。
|
||
/// </summary>
|
||
private const double CoreIndexMin = 0.9 * Math.PI; // ≈162°
|
||
private const double CoreIndexMax = 2.2 * Math.PI; // ≈396°(覆盖斗形中心 +360°)
|
||
|
||
/// <summary>有效方向块占比低于此值时,方向场整体不可用 → "无法识别"。</summary>
|
||
private const double MinValidBlockRatio = 0.20;
|
||
|
||
/// <summary>Poincaré 8 邻域绕行偏移(顺时针,首尾相接绕块一周):dx 序列。</summary>
|
||
private static readonly int[] RingDx = { -1, 0, 1, 1, 1, 0, -1, -1 };
|
||
|
||
/// <summary>Poincaré 8 邻域绕行偏移(顺时针):dy 序列。</summary>
|
||
private static readonly int[] RingDy = { -1, -1, -1, 0, 1, 1, 1, 0 };
|
||
|
||
/// <summary>奇异点(候选簇代表):像素坐标 + 实测 Poincaré 指数(度)。</summary>
|
||
private readonly record struct SingP(double X, double Y, double IndexDeg);
|
||
|
||
// ---------------- 主流程 ----------------
|
||
|
||
/// <summary>
|
||
/// 对一幅灰度指纹图做纹型分类与嵴线计数。
|
||
/// 返回 null 当且仅当输入退化(数据为空 / 尺寸过小 / 全黑全白近均匀)。
|
||
/// </summary>
|
||
public static FpResult? Classify(byte[] gray, int width, int height)
|
||
{
|
||
// ---- 0. 输入合法性检查(退化输入返回 null)----
|
||
if (gray == null || width < MinImageSize || height < MinImageSize
|
||
|| width > MaxImageSize || height > MaxImageSize)
|
||
return null;
|
||
if (gray.Length < width * height)
|
||
return null;
|
||
|
||
// ---- 1. 预处理:2%~98% 分位对比度拉伸 + 3×3 中值滤波 ----
|
||
byte[]? stretched = StretchContrast(gray, width, height);
|
||
if (stretched == null)
|
||
return null; // 直方图退化:全黑 / 全白 / 近均匀
|
||
byte[] img = MedianFilter3x3(stretched, width, height);
|
||
|
||
// ---- 2. Sobel 梯度(全图一次计算,供分块协方差复用)----
|
||
int[] gx = new int[width * height];
|
||
int[] gy = new int[width * height];
|
||
Sobel(img, width, height, gx, gy);
|
||
|
||
// ---- 3. 分块方向场 + 一次 3×3 向量平滑(π 周期)----
|
||
int cols = (width + BlockSize - 1) / BlockSize; // 640 → 40
|
||
int rows = (height + BlockSize - 1) / BlockSize; // 640 → 40
|
||
double?[,] field = BuildOrientation(img, gx, gy, width, height, cols, rows, out double avgCoherence);
|
||
double?[,] smooth = SmoothOrientation(field, cols, rows);
|
||
|
||
int validBlocks = 0;
|
||
for (int by = 0; by < rows; by++)
|
||
for (int bx = 0; bx < cols; bx++)
|
||
if (smooth[bx, by].HasValue)
|
||
validBlocks++;
|
||
double validRatio = validBlocks / (double)(cols * rows);
|
||
|
||
// ---- 4. Poincaré index 奇异点检测(核心/三角,含连通聚类去重)----
|
||
DetectSingularities(smooth, cols, rows, out List<SingP> cores, out List<SingP> deltas);
|
||
|
||
// ---- 5. 纹型判定 ----
|
||
// 任务书映射:核心0→弧形纹;核心≥1且三角≥2→斗形纹;核心≥1三角1→箕形纹;全无→无法识别。
|
||
// "全无"解读为方向场整体不可用(有效块比例过低,什么奇异点都无从谈起),
|
||
// 否则核心0三角0恰是弧形纹的固有形态,会与"核心0→弧形纹"自相矛盾。
|
||
string pattern;
|
||
string reason;
|
||
if (validRatio < MinValidBlockRatio)
|
||
{
|
||
pattern = "无法识别";
|
||
reason = $"有效方向块仅{validRatio:P0},方向场不可用(全无有效信息)";
|
||
}
|
||
else if (cores.Count == 0)
|
||
{
|
||
pattern = "弧形纹";
|
||
reason = deltas.Count == 0
|
||
? "未检出核心与三角(弧形纹方向场无奇异点)"
|
||
: $"未检出核心点(另检出{deltas.Count}个可疑三角,按无核心处理)";
|
||
}
|
||
else if (deltas.Count >= 2)
|
||
{
|
||
pattern = "斗形纹";
|
||
reason = $"核心{cores.Count}个且三角{deltas.Count}个";
|
||
}
|
||
else if (deltas.Count == 1)
|
||
{
|
||
pattern = "箕形纹";
|
||
reason = "核心≥1且三角1个";
|
||
}
|
||
else
|
||
{
|
||
// 核心≥1但三角 0:非任务书覆盖情形,按结构常识兜底——
|
||
// 斗形纹常有并列双核心;单核心无三角多为三角被裁到图像外或漏检(箕形纹)。
|
||
pattern = cores.Count >= 2 ? "斗形纹" : "箕形纹";
|
||
reason = $"未检出三角点,按核心数{cores.Count}推测(置信度低)";
|
||
}
|
||
|
||
// 多核心时取最靠图像中心者作为代表核心(任务书约定)
|
||
double coreX = -1, coreY = -1;
|
||
bool hasCore = cores.Count > 0;
|
||
if (hasCore)
|
||
{
|
||
double hw = width * 0.5, hh = height * 0.5;
|
||
double bestD = double.MaxValue;
|
||
for (int i = 0; i < cores.Count; i++)
|
||
{
|
||
double d = (cores[i].X - hw) * (cores[i].X - hw) + (cores[i].Y - hh) * (cores[i].Y - hh);
|
||
if (d < bestD) { bestD = d; coreX = cores[i].X; coreY = cores[i].Y; }
|
||
}
|
||
}
|
||
|
||
// ---- 6. 嵴线计数:核心 → 最近三角连线,过均值交叉法 ----
|
||
int ridgeCount = 0;
|
||
string countNote;
|
||
if (hasCore && deltas.Count > 0)
|
||
{
|
||
// 斗形纹双三角(或多三角)取离核心最近的一个连线
|
||
double bestDist = double.MaxValue;
|
||
double dx0 = 0, dy0 = 0;
|
||
for (int i = 0; i < deltas.Count; i++)
|
||
{
|
||
double d = Math.Sqrt((deltas[i].X - coreX) * (deltas[i].X - coreX)
|
||
+ (deltas[i].Y - coreY) * (deltas[i].Y - coreY));
|
||
if (d < bestDist) { bestDist = d; dx0 = deltas[i].X; dy0 = deltas[i].Y; }
|
||
}
|
||
ridgeCount = CountRidgesAlongLine(img, width, height, coreX, coreY, dx0, dy0,
|
||
out int crossings, out double lineLen);
|
||
countNote = $"核心({coreX:0},{coreY:0})→最近三角({dx0:0},{dy0:0}):线长{lineLen:0}px、均值交叉{crossings}次、嵴线≈{ridgeCount}条";
|
||
}
|
||
else if (hasCore)
|
||
{
|
||
countNote = "未检出三角点,无法连线计数(记0)";
|
||
}
|
||
else
|
||
{
|
||
countNote = "无核心点,嵴线计数记0";
|
||
}
|
||
|
||
// ---- 7. 方向场预览([块中心x, 块中心y, θ弧度],空块不输出)----
|
||
List<double[]> preview = BuildPreview(smooth, cols, rows);
|
||
|
||
// ---- 8. Notes:关键中间结果摘要(中文)----
|
||
var sb = new StringBuilder(320);
|
||
sb.Append($"图{width}×{height},块{BlockSize}px→{cols}×{rows};");
|
||
sb.Append($"有效方向块{validBlocks}({validRatio:P0}),平均一致性{avgCoherence:0.00};");
|
||
sb.Append("核心").Append(cores.Count).Append("个");
|
||
AppendPoints(sb, cores);
|
||
sb.Append(",三角").Append(deltas.Count).Append("个");
|
||
AppendPoints(sb, deltas);
|
||
sb.Append(";判定:").Append(reason).Append(';').Append(countNote).Append('。');
|
||
if (validRatio < 0.40 && pattern != "无法识别")
|
||
sb.Append("提示:有效块比例偏低,结果置信度下降。");
|
||
string notes = sb.ToString();
|
||
|
||
return new FpResult(pattern, ridgeCount, coreX, coreY, preview, notes);
|
||
}
|
||
|
||
// ---------------- 步骤 1:预处理 ----------------
|
||
|
||
/// <summary>
|
||
/// 对比度拉伸:统计直方图,取 2% 与 98% 累积分位为 lo/hi,线性映射到 [0,255] 并截断。
|
||
/// 分位拉伸优于全局 min/max 之处:少量椒盐极值不会吞掉整个动态范围。
|
||
/// 返回 null 表示直方图退化(全黑/全白/近均匀,hi−lo 不足 MinContrastRange)。
|
||
/// </summary>
|
||
private static byte[]? StretchContrast(byte[] src, int w, int h)
|
||
{
|
||
int total = w * h;
|
||
int[] hist = new int[256];
|
||
for (int i = 0; i < total; i++)
|
||
hist[src[i]]++;
|
||
|
||
// 累积直方图上找分位点
|
||
long acc = 0;
|
||
int lo = 0, hi = 255;
|
||
long loCut = (long)(total * 0.02);
|
||
long hiCut = (long)(total * 0.98);
|
||
for (int v = 0; v < 256; v++)
|
||
{
|
||
acc += hist[v];
|
||
if (acc >= loCut) { lo = v; break; }
|
||
}
|
||
acc = 0;
|
||
for (int v = 0; v < 256; v++)
|
||
{
|
||
acc += hist[v];
|
||
if (acc >= hiCut) { hi = v; break; }
|
||
}
|
||
if (hi <= lo + MinContrastRange)
|
||
return null; // 对比度不足:全黑 / 全白 / 近均匀
|
||
|
||
// 构建 LUT 一次查表,避免逐像素乘除
|
||
int range = hi - lo;
|
||
var lut = new byte[256];
|
||
for (int v = 0; v < 256; v++)
|
||
{
|
||
int t = (v - lo) * 255 / range;
|
||
lut[v] = (byte)(t < 0 ? 0 : (t > 255 ? 255 : t));
|
||
}
|
||
var dst = new byte[total];
|
||
for (int i = 0; i < total; i++)
|
||
dst[i] = lut[src[i]];
|
||
return dst;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 3×3 中值滤波:抑制椒盐噪声与传感器毛刺,同时不像均值滤波那样抹平嵴线边缘。
|
||
/// 边缘处理:采样坐标 clamp 到图像内(复制边缘像素),保证输出与输入同尺寸。
|
||
/// 9 元素用插入排序取中位(409600 像素 × 约 25 次比较,实测远低于性能预算)。
|
||
/// </summary>
|
||
private static byte[] MedianFilter3x3(byte[] src, int w, int h)
|
||
{
|
||
var dst = new byte[w * h];
|
||
var win = new byte[9]; // 循环外一次分配,循环内复用(避免 GC 压力)
|
||
for (int y = 0; y < h; y++)
|
||
{
|
||
int yUp = y > 0 ? y - 1 : 0;
|
||
int yDn = y < h - 1 ? y + 1 : h - 1;
|
||
for (int x = 0; x < w; x++)
|
||
{
|
||
int xL = x > 0 ? x - 1 : 0;
|
||
int xR = x < w - 1 ? x + 1 : w - 1;
|
||
win[0] = src[yUp * w + xL]; win[1] = src[yUp * w + x]; win[2] = src[yUp * w + xR];
|
||
win[3] = src[y * w + xL]; win[4] = src[y * w + x]; win[5] = src[y * w + xR];
|
||
win[6] = src[yDn * w + xL]; win[7] = src[yDn * w + x]; win[8] = src[yDn * w + xR];
|
||
dst[y * w + x] = Median9(win);
|
||
}
|
||
}
|
||
return dst;
|
||
}
|
||
|
||
/// <summary>9 元素插入排序,返回中位数(win 会被原地排序,属预期复用)。</summary>
|
||
private static byte Median9(byte[] a)
|
||
{
|
||
for (int i = 1; i < 9; i++)
|
||
{
|
||
byte v = a[i];
|
||
int j = i - 1;
|
||
while (j >= 0 && a[j] > v) { a[j + 1] = a[j]; j--; }
|
||
a[j + 1] = v;
|
||
}
|
||
return a[4];
|
||
}
|
||
|
||
// ---------------- 步骤 2:Sobel 梯度 ----------------
|
||
|
||
/// <summary>
|
||
/// Sobel 算子求全图梯度:Gx 响应 x 方向灰度变化、Gy 响应 y 方向变化。
|
||
/// 图像外圈 1 像素梯度置 0(数组默认值),对分块统计影响可忽略。
|
||
/// 结果用 int 数组(单像素最大 |9×255|=2295),供方向场协方差复用。
|
||
/// </summary>
|
||
private static void Sobel(byte[] img, int w, int h, int[] gx, int[] gy)
|
||
{
|
||
for (int y = 1; y < h - 1; y++)
|
||
{
|
||
int rowU = (y - 1) * w;
|
||
int rowC = y * w;
|
||
int rowD = (y + 1) * w;
|
||
for (int x = 1; x < w - 1; x++)
|
||
{
|
||
int p00 = img[rowU + x - 1], p01 = img[rowU + x], p02 = img[rowU + x + 1];
|
||
int p10 = img[rowC + x - 1], p12 = img[rowC + x + 1];
|
||
int p20 = img[rowD + x - 1], p21 = img[rowD + x], p22 = img[rowD + x + 1];
|
||
// Gx = [[-1,0,1],[-2,0,2],[-1,0,1]],Gy = [[-1,-2,-1],[0,0,0],[1,2,1]]
|
||
gx[rowC + x] = (p02 + 2 * p12 + p22) - (p00 + 2 * p10 + p20);
|
||
gy[rowC + x] = (p20 + 2 * p21 + p22) - (p00 + 2 * p01 + p02);
|
||
}
|
||
}
|
||
}
|
||
|
||
// ---------------- 步骤 3:分块方向场 ----------------
|
||
|
||
/// <summary>
|
||
/// 分块方向场(Hong 等人经典梯度协方差法):块内累加
|
||
/// Gxx=ΣGx²、Gyy=ΣGy²、Gxy=ΣGxGy,
|
||
/// θ = 0.5·atan2(2·Gxy, Gxx−Gyy)
|
||
/// (梯度协方差主轴角取半,得到 π 周期的嵴线主方向)。
|
||
/// 空块判定(方向置 null):块内像素不足半块(边缘裁切)、灰度标准差过低
|
||
/// (平坦背景 ≈220 亮区无纹线)、梯度能量为 0。
|
||
/// 同时输出平均一致性 coherence = √((Gxx−Gyy)²+4Gxy²)/(Gxx+Gyy) ∈ [0,1],
|
||
/// 表示块内方向"共识"强度,作为整体置信度写入 Notes。
|
||
/// </summary>
|
||
private static double?[,] BuildOrientation(byte[] img, int[] gx, int[] gy,
|
||
int w, int h, int cols, int rows,
|
||
out double avgCoherence)
|
||
{
|
||
var field = new double?[cols, rows];
|
||
double coherenceSum = 0;
|
||
int validCount = 0;
|
||
|
||
for (int by = 0; by < rows; by++)
|
||
{
|
||
for (int bx = 0; bx < cols; bx++)
|
||
{
|
||
int x0 = bx * BlockSize, y0 = by * BlockSize;
|
||
int x1 = Math.Min(x0 + BlockSize, w);
|
||
int y1 = Math.Min(y0 + BlockSize, h);
|
||
long gxx = 0, gyy = 0, gxy = 0;
|
||
double sum = 0, sumSq = 0;
|
||
int n = 0;
|
||
for (int y = y0; y < y1; y++)
|
||
{
|
||
int row = y * w;
|
||
for (int x = x0; x < x1; x++)
|
||
{
|
||
int i = row + x;
|
||
int sx = gx[i], sy = gy[i];
|
||
gxx += (long)sx * sx;
|
||
gyy += (long)sy * sy;
|
||
gxy += (long)sx * sy;
|
||
int v = img[i];
|
||
sum += v;
|
||
sumSq += (double)v * v;
|
||
n++;
|
||
}
|
||
}
|
||
|
||
double mean = n > 0 ? sum / n : 0;
|
||
double std = Math.Sqrt(Math.Max(0, sumSq / Math.Max(1, n) - mean * mean));
|
||
|
||
if (n < BlockSize * BlockSize / 2 || std < FlatBlockStd || (gxx + gyy) == 0)
|
||
{
|
||
field[bx, by] = null; // 空块:平坦/无效,方向无意义
|
||
continue;
|
||
}
|
||
|
||
field[bx, by] = 0.5 * Math.Atan2(2.0 * gxy, gxx - gyy);
|
||
|
||
double dxx = gxx - gyy;
|
||
double denom = gxx + gyy;
|
||
coherenceSum += Math.Sqrt(dxx * dxx + 4.0 * gxy * gxy) / denom;
|
||
validCount++;
|
||
}
|
||
}
|
||
avgCoherence = validCount > 0 ? coherenceSum / validCount : 0;
|
||
return field;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 方向场平滑(一次 3×3 邻块圆均值):方向是 π 周期量,不能直接算术平均,
|
||
/// 必须倍角后做向量平均:θ' = 0.5·atan2(Σsin2θ, Σcos2θ),仅累加邻域内非空块。
|
||
/// 平滑可压制 Sobel 噪声引起的局部方向抖动,使 Poincaré 绕行更稳定;
|
||
/// 代价是轻微钝化奇异点,但 3×3 平滑下 ±180° 的指数仍可靠检出。
|
||
/// </summary>
|
||
private static double?[,] SmoothOrientation(double?[,] field, int cols, int rows)
|
||
{
|
||
var result = new double?[cols, rows];
|
||
for (int by = 0; by < rows; by++)
|
||
{
|
||
for (int bx = 0; bx < cols; bx++)
|
||
{
|
||
double? cur = field[bx, by];
|
||
if (cur == null) { result[bx, by] = null; continue; }
|
||
|
||
double sin2 = 0, cos2 = 0;
|
||
int cnt = 0;
|
||
for (int dy = -1; dy <= 1; dy++)
|
||
{
|
||
int ny = by + dy;
|
||
if (ny < 0 || ny >= rows) continue;
|
||
for (int dx = -1; dx <= 1; dx++)
|
||
{
|
||
int nx = bx + dx;
|
||
if (nx < 0 || nx >= cols) continue;
|
||
double? t = field[nx, ny];
|
||
if (t == null) continue;
|
||
double d2 = 2.0 * t.Value;
|
||
sin2 += Math.Sin(d2);
|
||
cos2 += Math.Cos(d2);
|
||
cnt++;
|
||
}
|
||
}
|
||
// cnt ≥ 1(至少含自身);向量平均,模长过小(邻域方向对冲)时保留原方向
|
||
if (cnt > 1 && (Math.Abs(sin2) > 1e-12 || Math.Abs(cos2) > 1e-12))
|
||
result[bx, by] = 0.5 * Math.Atan2(sin2, cos2);
|
||
else
|
||
result[bx, by] = cur;
|
||
}
|
||
}
|
||
return result;
|
||
}
|
||
|
||
// ---------------- 步骤 4:Poincaré 奇异点检测 ----------------
|
||
|
||
/// <summary>
|
||
/// Poincaré index 检测:对每个内部块,取其 3×3 邻域方向按顺时针绕块一周,
|
||
/// 相邻方向差经 π 周期解卷绕(wrap 到 (−90°,90°])后累加得 Δ。
|
||
/// 理想值:箕形核心 +180°、斗形中心 +360°、三角 −180°;判定区间见 CoreIndexMin/Max 注释
|
||
/// (任务书区间 (180°,270°]/[−270°,−180°) 为其子集)。
|
||
/// 噪声会使同一奇异点在相邻块重复触发,故同类型候选按 8 连通聚类,
|
||
/// 每簇取 |Δ| 最大者(最接近理想奇异结构的块)为代表,坐标换算为块中心像素位置。
|
||
/// </summary>
|
||
private static void DetectSingularities(double?[,] field, int cols, int rows,
|
||
out List<SingP> cores, out List<SingP> deltas)
|
||
{
|
||
var coreCands = new List<(int Bx, int By, double Idx)>();
|
||
var deltaCands = new List<(int Bx, int By, double Idx)>();
|
||
|
||
var ring = new double[8];
|
||
for (int by = 1; by < rows - 1; by++)
|
||
{
|
||
for (int bx = 1; bx < cols - 1; bx++)
|
||
{
|
||
// 8 邻域方向必须全部有效,否则绕行序列断裂,index 不可信
|
||
bool ok = true;
|
||
for (int k = 0; k < 8; k++)
|
||
{
|
||
double? t = field[bx + RingDx[k], by + RingDy[k]];
|
||
if (t == null) { ok = false; break; }
|
||
ring[k] = t.Value;
|
||
}
|
||
if (!ok) continue;
|
||
|
||
// 绕行一周累计角度变化(含回到起点的一步)
|
||
double acc = 0;
|
||
for (int k = 0; k < 8; k++)
|
||
acc += WrapHalfPi(ring[(k + 1) & 7] - ring[k]);
|
||
|
||
if (acc > CoreIndexMin && acc <= CoreIndexMax)
|
||
coreCands.Add((bx, by, acc));
|
||
else if (acc < -CoreIndexMin && acc >= -CoreIndexMax)
|
||
deltaCands.Add((bx, by, acc));
|
||
}
|
||
}
|
||
|
||
cores = ClusterCandidates(coreCands);
|
||
deltas = ClusterCandidates(deltaCands);
|
||
}
|
||
|
||
/// <summary>把角度差解卷绕到 (−π/2, π/2](方向场为 π 周期量)。</summary>
|
||
private static double WrapHalfPi(double a)
|
||
{
|
||
const double half = Math.PI / 2;
|
||
while (a > half) a -= Math.PI;
|
||
while (a <= -half) a += Math.PI;
|
||
return a;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 候选奇异块 8 连通聚类:同一真实奇异点常在相邻多个块触发,逐簇取 |Δ| 最大者为代表,
|
||
/// 坐标 (bx+0.5)·BlockSize 即块中心像素位置。
|
||
/// 候选规模通常仅几个到几十个,O(n²) 邻接查找足够。
|
||
/// </summary>
|
||
private static List<SingP> ClusterCandidates(List<(int Bx, int By, double Idx)> cands)
|
||
{
|
||
var result = new List<SingP>();
|
||
if (cands.Count == 0) return result;
|
||
|
||
var done = new bool[cands.Count];
|
||
var stack = new Stack<int>();
|
||
var members = new List<int>();
|
||
for (int i = 0; i < cands.Count; i++)
|
||
{
|
||
if (done[i]) continue;
|
||
stack.Clear();
|
||
members.Clear();
|
||
stack.Push(i);
|
||
done[i] = true;
|
||
while (stack.Count > 0)
|
||
{
|
||
int c = stack.Pop();
|
||
members.Add(c);
|
||
int cbx = cands[c].Bx, cby = cands[c].By;
|
||
for (int j = 0; j < cands.Count; j++)
|
||
{
|
||
if (done[j]) continue;
|
||
if (Math.Abs(cands[j].Bx - cbx) <= 1 && Math.Abs(cands[j].By - cby) <= 1)
|
||
{
|
||
done[j] = true;
|
||
stack.Push(j);
|
||
}
|
||
}
|
||
}
|
||
// 簇代表:|Δ| 最大者(最"深"的奇异块)
|
||
int best = members[0];
|
||
for (int m = 1; m < members.Count; m++)
|
||
if (Math.Abs(cands[members[m]].Idx) > Math.Abs(cands[members[best]].Idx))
|
||
best = members[m];
|
||
int bx = cands[best].Bx, by = cands[best].By;
|
||
result.Add(new SingP((bx + 0.5) * BlockSize, (by + 0.5) * BlockSize,
|
||
cands[best].Idx * 180.0 / Math.PI));
|
||
}
|
||
return result;
|
||
}
|
||
|
||
// ---------------- 步骤 6:嵴线计数 ----------------
|
||
|
||
/// <summary>
|
||
/// 核心—三角连线嵴线计数(方向场垂直采样法的退化实用形态):
|
||
/// 沿连线每 1 像素双线性采样灰度,求序列均值 μ,二值化后统计亮↔暗交叉次数 crossings。
|
||
/// 一条嵴线(暗带)被直线穿过产生"入+出"两次交叉,故 ridgeCount = round(crossings/2)。
|
||
/// 这正是人工指纹分析中 Henry 法"连接核心与三角数嵴线"的数字化版本。
|
||
/// </summary>
|
||
private static int CountRidgesAlongLine(byte[] img, int w, int h,
|
||
double x0, double y0, double x1, double y1,
|
||
out int crossings, out double lineLen)
|
||
{
|
||
double dx = x1 - x0, dy = y1 - y0;
|
||
lineLen = Math.Sqrt(dx * dx + dy * dy);
|
||
crossings = 0;
|
||
if (lineLen < 2)
|
||
return 0; // 两点过近,采样无意义
|
||
|
||
int steps = Math.Max(2, (int)Math.Round(lineLen)); // 每 1 像素一个采样
|
||
var samples = new double[steps + 1];
|
||
double sum = 0;
|
||
for (int s = 0; s <= steps; s++)
|
||
{
|
||
double t = (double)s / steps;
|
||
double v = SampleBilinear(img, w, h, x0 + dx * t, y0 + dy * t);
|
||
samples[s] = v;
|
||
sum += v;
|
||
}
|
||
double mean = sum / (steps + 1);
|
||
|
||
bool prev = samples[0] > mean;
|
||
for (int s = 1; s <= steps; s++)
|
||
{
|
||
bool cur = samples[s] > mean;
|
||
if (cur != prev) { crossings++; prev = cur; }
|
||
}
|
||
return (int)Math.Round(crossings / 2.0, MidpointRounding.AwayFromZero);
|
||
}
|
||
|
||
/// <summary>双线性插值采样(越界坐标 clamp 到图像内),避免取整采样导致的锯齿误交叉。</summary>
|
||
private static double SampleBilinear(byte[] img, int w, int h, double x, double y)
|
||
{
|
||
if (x < 0) x = 0; else if (x > w - 1) x = w - 1;
|
||
if (y < 0) y = 0; else if (y > h - 1) y = h - 1;
|
||
int x0 = (int)x, y0 = (int)y;
|
||
int x1 = x0 < w - 1 ? x0 + 1 : x0;
|
||
int y1 = y0 < h - 1 ? y0 + 1 : y0;
|
||
double fx = x - x0, fy = y - y0;
|
||
double p00 = img[y0 * w + x0], p10 = img[y0 * w + x1];
|
||
double p01 = img[y1 * w + x0], p11 = img[y1 * w + x1];
|
||
return p00 * (1 - fx) * (1 - fy) + p10 * fx * (1 - fy)
|
||
+ p01 * (1 - fx) * fy + p11 * fx * fy;
|
||
}
|
||
|
||
// ---------------- 步骤 7:方向场预览 ----------------
|
||
|
||
/// <summary>
|
||
/// 输出非空块方向样本供前端可视化叠加:每项 [块中心x, 块中心y, θ(弧度)]。
|
||
/// θ 为与 x 轴夹角、π 周期(前端画对称短线段即可,如 (x±cosθ·L, y±sinθ·L))。
|
||
/// </summary>
|
||
private static List<double[]> BuildPreview(double?[,] field, int cols, int rows)
|
||
{
|
||
var list = new List<double[]>(cols * rows);
|
||
for (int by = 0; by < rows; by++)
|
||
{
|
||
for (int bx = 0; bx < cols; bx++)
|
||
{
|
||
double? t = field[bx, by];
|
||
if (t == null) continue;
|
||
list.Add(new[] { (bx + 0.5) * BlockSize, (by + 0.5) * BlockSize, t.Value });
|
||
}
|
||
}
|
||
return list;
|
||
}
|
||
|
||
// ---------------- Notes 辅助 ----------------
|
||
|
||
/// <summary>把奇异点列表拼成 "(x,y,Δ±n°)、…" 形式(最多列 3 个,其余汇总计数)。</summary>
|
||
private static void AppendPoints(StringBuilder sb, List<SingP> pts)
|
||
{
|
||
if (pts.Count == 0) { sb.Append("(无)"); return; }
|
||
sb.Append('[');
|
||
int n = Math.Min(pts.Count, 3);
|
||
for (int i = 0; i < n; i++)
|
||
{
|
||
if (i > 0) sb.Append('、');
|
||
sb.Append($"({pts[i].X:0},{pts[i].Y:0},Δ{pts[i].IndexDeg:+0;-0;0}°)");
|
||
}
|
||
if (pts.Count > n) sb.Append($"等{pts.Count}处");
|
||
sb.Append(']');
|
||
}
|
||
}
|