c#中opencv图像平移旋转,直接能运行代码
时间: 2024-10-23 16:05:25 浏览: 9
在C#中,使用OpenCV库进行图像平移和旋转操作相对简单。首先,你需要安装OpenCVSharp NuGet包才能在.NET项目中使用它。以下是一个基本的例子展示如何对图像进行平移和旋转:
```csharp
using OpenCvSharp;
// 加载图像
Mat image = Cv2.ImRead("path_to_your_image.jpg", ImreadModes.Color);
// 平移操作
Point2f translationVector = new Point2f(50, 50); // (x, y)偏移量
Mat translatedImage = new Mat();
Cv2.WarpAffine(image, translatedImage, TranslationMatrix(translationVector), image.Size());
// 旋转操作
double angleInDegrees = 45; // 旋转角度,单位是度
Point2f center = new Point2f(image.Width / 2, image.Height / 2);
double scale = 1;
Mat rotationMatrix = GetRotationMatrix(center, angleInDegrees, scale);
Mat rotatedImage = new Mat();
Cv2.WarpAffine(image, rotatedImage, rotationMatrix, image.Size(), InterpolationTypes.Bilinear, BorderMode.Constant, new Scalar(0));
// 定义辅助函数获取旋转矩阵
static Mat TranslationMatrix(Point2f vector)
{
float[] matData = { 1, 0, -vector.X, 0, 1, -vector.Y, 0, 0, 1 };
return new Mat(new MatOfFloat(matData), 3, 3);
}
static Mat GetRotationMatrix(Point2f center, double angle, double scale = 1.0)
{
double cosa = Math.Cos(angle * Math.PI / 180);
double sina = Math.Sin(angle * Math.PI / 180);
return new Mat(
new float[][] {
{ scale * cosa, -scale * sina, center.X - scale * cosa * center.X - scale * sina * center.Y },
{ scale * sina, scale * cosa, center.Y + scale * cosa * center.X + scale * sina * center.Y },
{ 0, 0, 1 }
}, 3, 3);
}
// 保存处理后的图像
Cv2.ImWrite("translated_image.jpg", translatedImage);
Cv2.ImWrite("rotated_image.jpg", rotatedImage);
```
阅读全文