平移、旋轉、縮放、翻轉、剪切等變換都屬於仿射變換,而仿射變換又是透視變換的一種。所有仿射變換都可以用三個點到另外三個點去描述,而透視變換需要四個點。我們拍攝的圖像裏面,一般矩形的物體(例如紙張)都會變形,如果要轉回規整的矩形,就要使用透視變換。
在本教程中,使用的原圖都是:
一、翻轉
Mat src = new Mat(img_word);
Mat map_x = new Mat(src.Size(), MatType.CV_32FC1);
Mat map_y = new Mat(src.Size(), MatType.CV_32FC1);
for (int i = 0; i < src.Width; i++)
{
for (int j = 0; j < src.Height; j++)
{
map_x.Set(j, i, (float)(src.Width - i));
map_y.Set(j, i, (float)j);
}
}
Mat result = new Mat();
Cv2.Remap(src, result, map_x, map_y);
result.SaveImage(img_result);
效果如下:
二、旋轉
Mat src = new Mat(img_word);
Mat M = Cv2.GetRotationMatrix2D(new Point2f(src.Width / 2, src.Height / 2), 30, 1);
Mat result = new Mat();
Cv2.WarpAffine(src, result, M, src.Size());
result.SaveImage(img_result);
效果如下:
三、縮放
Mat src = new Mat(img_word);
Mat result = new Mat();
Cv2.Resize(src, result, new OpenCvSharp.Size(src.Width / 2, src.Height / 2));
result.SaveImage(img_result);
效果如下:
四、平移
Mat src = new Mat(img_word);
Mat map_x = new Mat(src.Size(), MatType.CV_32FC1);
Mat map_y = new Mat(src.Size(), MatType.CV_32FC1);
for (int i = 0; i < src.Width - 100; i++)
{
for (int j = 0; j < src.Height; j++)
{
map_x.Set(j, i, (float)(i + 100));
map_y.Set(j, i, (float)j);
}
}
Mat result = new Mat();
Cv2.Remap(src, result, map_x, map_y);
result.SaveImage(img_result);
效果如下:
五、剪切
Mat src = new Mat(img_word);
Mat M = Cv2.GetAffineTransform(new Point2f[] { new Point2f(0, 0), new Point2f(0, src.Height), new Point2f(src.Width, src.Height) },
new Point2f[] { new Point2f(40, 40), new Point2f(0, src.Height), new Point2f(src.Width, src.Height) });
Mat result = new Mat();
Cv2.WarpAffine(src, result, M, new OpenCvSharp.Size(src.Width + 50, src.Height));
result.SaveImage(img_result);
效果如下:
六、透視變換
Mat src = new Mat(img_word);
Mat M = Cv2.GetPerspectiveTransform(new Point2f[] { new Point2f(0, 0), new Point2f(src.Width, 0), new Point2f(0, src.Height), new Point2f(src.Width, src.Height) },
new Point2f[] { new Point2f(40, 40), new Point2f(src.Width - 40, 40), new Point2f(0, src.Height), new Point2f(src.Width, src.Height) });
Mat result = new Mat();
Cv2.WarpPerspective(src, result, M, new OpenCvSharp.Size(src.Width, src.Height));
result.SaveImage(img_result);
效果如下: