裁剪并旋转图片OpenCV

时间:2012-11-29 16:02:31

标签: opencv rotation crop

我是OpenCV的新手,所以请宽容一下。 我正在做一个Android应用程序来识别正方形/矩形并裁剪它们。寻找正方形/矩形的函数将找到的对象放入向量>广场。我只是想知道如何根据存储在vector>中的点中的数据裁剪图片。正方形以及如何计算图片应旋转的角度。感谢您的帮助

3 个答案:

答案 0 :(得分:1)

周围有很多有用的帖子,我相信你可以做更好的搜索。

作物:

旋转:

计算角度:

答案 1 :(得分:1)

这篇文章引自OpenCV QA: Extract a RotatedRect area

Felix Abecassis有关旋转和偏斜图像的精彩文章。这也向您展示了如何在RotatedRect中提取数据:

您基本上只需要cv::getRotationMatrix2D来获取仿射变换的旋转矩阵,并使用cv::warpAffinecv::getRectSubPix裁剪旋转后的图像。我的申请中的相关行是:

// This is the RotatedRect, I got it from a contour for example...
RotatedRect rect = ...;
// matrices we'll use
Mat M, rotated, cropped;
// get angle and size from the bounding box
float angle = rect.angle;
Size rect_size = rect.size;
// thanks to http://felix.abecassis.me/2011/10/opencv-rotation-deskewing/
if (rect.angle < -45.) {
    angle += 90.0;
    swap(rect_size.width, rect_size.height);
}
// get the rotation matrix
M = getRotationMatrix2D(rect.center, angle, 1.0);
// perform the affine transformation on your image in src,
// the result is the rotated image in rotated. I am doing
// cubic interpolation here
warpAffine(src, rotated, M, src.size(), INTER_CUBIC);
// crop the resulting image, which is then given in cropped
getRectSubPix(rotated, rect_size, rect.center, cropped);

答案 2 :(得分:0)

Altought这个问题已经很老了,我认为需要一个不像旋转整个图像那样昂贵的答案(参见@ bytefish的回答)。你需要一个边界矩形,由于某些原因rotatedRect.boundingRect()没有为我工作,所以我不得不使用Imgproc.boundingRect(contour)。这是适用于Android的OpenCV,其他环境的操作几乎相同:

Rect roi = Imgproc.boundingRect(contour);
// we only work with a submat, not the whole image:
Mat mat = image.submat(roi); 
RotatedRect rotatedRect = Imgproc.minAreaRect(new MatOfPoint2f(contour.toArray()));
Mat rot = Imgproc.getRotationMatrix2D(rotatedRect.center, rotatedRect.angle, 1.0);
// rotate using the center of the roi
double[] rot_0_2 = rot.get(0, 2);
for (int i = 0; i < rot_0_2.length; i++) {
    rot_0_2[i] += rotatedRect.size.width / 2 - rotatedRect.center.x;
}
rot.put(0, 2, rot_0_2);
double[] rot_1_2 = rot.get(1, 2);
for (int i = 0; i < rot_1_2.length; i++) {
    rot_1_2[i] += rotatedRect.size.height / 2 - rotatedRect.center.y;
}
rot.put(1, 2, rot_1_2);
// final rotated and cropped image:
Mat rotated = new Mat();
Imgproc.warpAffine(mat, rotated, rot, rotatedRect.size);
相关问题