基于C#部署YOLOv5目标检测模型 核心技术深度解析
1. 智能图像预处理:保持长宽比的缩放和填充策略
1.1 技术背景
在深度学习目标检测中,模型通常要求固定尺寸的输入(如320×320、640×640)。然而,实际应用中的图像尺寸往往是任意的,直接拉伸会导致图像变形,影响检测精度。因此需要智能的预处理策略。
1.2 算法原理
长宽比计算与决策
float hw_scale = (float)srch / srcw; // 计算高宽比
决策逻辑:
hw_scale > 1
:图像高度大于宽度(竖图)hw_scale < 1
:图像宽度大于高度(横图)hw_scale = 1
:正方形图像
竖图处理策略(高 > 宽)
if (hw_scale > 1)
{
newh = inpHeight; // 高度保持为目标高度
neww = (int)(inpWidth / hw_scale); // 按比例计算新宽度
Cv2.Resize(srcimg, dstimg, new OpenCvSharp.Size(neww, newh), 0, 0, InterpolationFlags.Area);
// 计算左右填充
left = (int)((inpWidth - neww) * 0.5);
Cv2.CopyMakeBorder(dstimg, dstimg, 0, 0, left, inpWidth - neww - left, BorderTypes.Constant);
}
数学推导:
原图尺寸: H × W
目标尺寸: inpHeight × inpWidth
高宽比: hw_scale = H / W
当 hw_scale > 1 时:
- 新高度: newh = inpHeight
- 新宽度: neww = inpWidth / hw_scale = inpWidth × W / H
- 左填充: left = (inpWidth - neww) / 2
- 右填充: inpWidth - neww - left
横图处理策略(宽 > 高)
else
{
newh = (int)(inpHeight * hw_scale); // 按比例计算新高度
neww = inpWidth; // 宽度保持为目标宽度
Cv2.Resize(srcimg, dstimg, new OpenCvSharp.Size(neww, newh), 0, 0, InterpolationFlags.Area);
// 计算上下填充
top = (int)((inpHeight - newh) * 0.5);
Cv2.CopyMakeBorder(dstimg, dstimg, top, inpHeight - newh - top, 0, 0, BorderTypes.Constant);
}
1.3 填充策略详解
BorderTypes.Constant 填充
- 使用常数值(默认为0,即黑色)填充边缘
- 不会引入额外的图像信息,避免干扰模型判断
- 在YOLOv5训练时也采用相同策略,保持一致性
居中填充算法
// 左右填充(竖图)
left = (int