Files
Ayay/SHH.CameraSdk/Core/Services/ImageScaleCluster.cs
2025-12-27 14:16:50 +08:00

79 lines
2.6 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.
using OpenCvSharp;
namespace SHH.CameraSdk
{
/// <summary>
/// [图像缩放服务]
/// 实现:基于基类,专注于将原图缩放并挂载到 TargetMat
/// </summary>
public class ImageScaleCluster : BaseFrameProcessor<ScaleWorker>
{
public ImageScaleCluster(int count, ProcessingConfigManager configManager)
: base(count, "ScaleCluster", configManager)
{
}
protected override ScaleWorker CreateWorker(int id) => new ScaleWorker(this, _configManager);
}
public class ScaleWorker : BaseWorker
{
private readonly ImageScaleCluster _parent;
private readonly ProcessingConfigManager _configManager;
public ScaleWorker(ImageScaleCluster parent, ProcessingConfigManager configManager)
{
_parent = parent;
_configManager = configManager;
}
protected override void PerformAction(long deviceId, SmartFrame frame, FrameDecision decision)
{
// 1. 获取实时配置 (极快,内存读取)
var options = _configManager.GetOptions(deviceId);
// 2. 原始尺寸
int srcW = frame.InternalMat.Width;
int srcH = frame.InternalMat.Height;
// 3. 目标尺寸
int targetW = options.TargetWidth;
int targetH = options.TargetHeight;
// 4. 判断是否需要缩放
bool needResize = false;
// 场景 A: 原始图比目标大,且允许缩小
if (options.EnableShrink && (srcW > targetW || srcH > targetH))
{
needResize = true;
}
// 场景 B: 原始图比目标小,且允许放大 (通常为 False)
else if (options.EnableExpand && (srcW < targetW || srcH < targetH))
{
needResize = true;
}
// 5. 执行动作
if (needResize)
{
Mat targetMat = new Mat();
// 线性插值
Cv2.Resize(frame.InternalMat, targetMat, new Size(targetW, targetH), 0, 0, InterpolationFlags.Linear);
// 挂载
var scaleType = (srcW > targetW) ? FrameScaleType.Shrink : FrameScaleType.Expand;
frame.AttachTarget(targetMat, scaleType);
}
else
{
// [透传] 不需要缩放
// 此时 frame.TargetMat 为 null代表“无变化”
}
}
protected override void NotifyFinished(long did, SmartFrame frame, FrameDecision dec)
{
_parent.PassToNext(did, frame, dec);
}
}
}