组合算法:GetRotationMatrix2D + WarpAffine
GetRotationMatrix2D 参数
- center:旋转中心点,默认图像中心
- angle:旋转角度
- 范围:-360 ~ 360
- 正负效果:正数逆时针、负数顺时针
- scale:缩放系数
- 默认:1.0
- 范围:0.1 ~ 2.0
WarpAffine:执行仿射旋转变换
使用场景
倾斜文本矫正、不规则倾斜工件摆正。
public override Mat Execute(Mat src)
{
Mat dst = new Mat();
Point2f center = new Point2f(src.Cols / 2f, src.Rows / 2f);
// 1. 获取旋转矩阵
Mat rotationMat = Cv2.GetRotationMatrix2D(center, Angle, Scale);
Size outputSize = src.Size();
if (AutoExpandCanvas)
{
Point2f[] pts = new Point2f[]
{
new Point2f(0, 0),
new Point2f(src.Width, 0),
new Point2f(0, src.Height),
new Point2f(src.Width, src.Height)
};
Rect rect = Cv2.BoundingRect(pts);
outputSize = new Size(rect.Width, rect.Height);
// 修正中心点
rotationMat.Set(0, 2, rotationMat.Get<double>(0, 2) + (rect.Width / 2f - center.X));
rotationMat.Set(1, 2, rotationMat.Get<double>(1, 2) + (rect.Height / 2f - center.Y));
}
// 2. 执行仿射变换
Cv2.WarpAffine(src, dst, rotationMat, outputSize, InterpolationFlag);
rotationMat.Dispose();
return dst;
}
若文章对您有帮助,可以激励一下我哦,祝您平安幸福!
| 微信 | 支付宝 |
|---|---|
![]() |
![]() |

