plcsharp/PLCSharpWpf/VVMs/Vision/GalleryClassifier/FeatureExtractor.cs
2026-07-26 10:15:22 +08:00

105 lines
3.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#nullable enable
using OpenCvSharp;
using System;
namespace PLCSharp.VVMs.Vision.GalleryClassifier
{
/// <summary>
/// 特征提取器 —— 在原始分辨率下将 ROI 区域分成格子,提取统计特征。
/// 不缩放、不依赖 ONNX 模型,细节不丢失。
///
/// 每个格子提取 2 个特征:灰度均值 + 灰度标准差
/// 默认 8x8 格子 → 128 维特征向量
/// </summary>
public class FeatureExtractor : IDisposable
{
private readonly int _gridX;
private readonly int _gridY;
private bool _disposed;
/// <summary>特征向量维度 = gridX × gridY × 2</summary>
public int FeatureDimension => _gridX * _gridY * 2;
public FeatureExtractor(int gridX = 8, int gridY = 8)
{
_gridX = gridX > 0 ? gridX : throw new ArgumentException("gridX > 0");
_gridY = gridY > 0 ? gridY : throw new ArgumentException("gridY > 0");
}
public unsafe float[] Extract(Mat image)
{
ThrowIfDisposed();
if (image == null || image.Empty())
throw new ArgumentException("图像为空");
Mat gray;
if (image.Channels() == 1)
gray = image.Clone();
else
{
gray = new Mat();
Cv2.CvtColor(image, gray, ColorConversionCodes.BGR2GRAY);
}
try
{
int cellW = Math.Max(gray.Width / _gridX, 1);
int cellH = Math.Max(gray.Height / _gridY, 1);
float[] features = new float[_gridX * _gridY * 2];
int idx = 0;
for (int gy = 0; gy < _gridY; gy++)
{
for (int gx = 0; gx < _gridX; gx++)
{
int x = gx * cellW;
int y = gy * cellH;
int w = (gx == _gridX - 1) ? gray.Width - x : cellW;
int h = (gy == _gridY - 1) ? gray.Height - y : cellH;
int pixelCount = w * h;
if (pixelCount <= 0) { idx += 2; continue; }
float sum = 0f;
float sumSq = 0f;
for (int row = y; row < y + h; row++)
{
byte* rowPtr = (byte*)gray.DataPointer + row * gray.Step();
for (int col = x; col < x + w; col++)
{
byte v = rowPtr[col];
sum += v;
sumSq += v * v;
}
}
float mean = sum / pixelCount;
float variance = (sumSq / pixelCount) - (mean * mean);
features[idx++] = mean / 255f;
features[idx++] = MathF.Sqrt(MathF.Max(variance, 0f)) / 255f;
}
}
return features;
}
finally
{
gray?.Dispose();
}
}
public void Dispose()
{
_disposed = true;
}
private void ThrowIfDisposed()
{
if (_disposed)
throw new ObjectDisposedException(nameof(FeatureExtractor));
}
}
}