如何获得弯曲(手绘)矩形的透视转换?
这就是我想要的:
但我得到了:
这是我的代码:
Rect boundingBox(boundingRect(countours[largest_contour_index]));
vector<Point> not_a_rect_shape;
not_a_rect_shape.push_back(boundingBox.tl());
not_a_rect_shape.push_back(Point(boundingBox.tl().x, boundingBox.br().y));
not_a_rect_shape.push_back(boundingBox.br());
not_a_rect_shape.push_back(Point(boundingBox.br().x, boundingBox.tl().y));
RotatedRect box = minAreaRect(cv::Mat(not_a_rect_shape));
Point2f pts[4];
box.points(pts);
cv::Point2f src_vertices[4];
src_vertices[0] = not_a_rect_shape[0];
src_vertices[1] = not_a_rect_shape[1];
src_vertices[2] = not_a_rect_shape[3];
src_vertices[3] = not_a_rect_shape[2];
Point2f dst_vertices[4];
dst_vertices[0] = Point(0, 0);
dst_vertices[1] = Point(box.boundingRect().width-1, 0);
dst_vertices[2] = Point(0, box.boundingRect().height-1);
dst_vertices[3] = Point(box.boundingRect().width-1, box.boundingRect().height-1);
Mat warpAffineMatrix = getAffineTransform(src_vertices, dst_vertices);
cv::Mat rotated;
cv::Size size(box.boundingRect().width, box.boundingRect().height);
warpAffine(src, rotated, warpAffineMatrix, size, INTER_LINEAR, BORDER_CONSTANT);
imshow("rotated.jpg", rotated);
P.S。我使用的所有矩形都是手绘的。也许,它只适用于直角矩形吗?
答案 0 :(得分:0)
您正在使用仿射变换来解决透视问题。仿射变换仅模拟旋转,平移和缩放(垂直和水平),因此使用这种变换无法解决您的问题。请改用透视变换。
编辑:嘿,请使用cv::getPerspectiveTransform
和cv::WarpPerspective
查看this nice tutorial,同时使用您方案中的4个角。它可以解决你的问题!