从原图中截取cv::RotatedRect minRect区域为新的cv::Mat,不对原图进行变换
时间: 2024-01-06 07:04:50 浏览: 77
python+OpenCV实现全景图像拼接和图像黑边处理
3星 · 编辑精心推荐
好的,您可以通过以下步骤来实现从原图中截取 cv::RotatedRect minRect 区域为新的 cv::Mat,而不对原图进行任何变换:
1. 获取最小矩形的四个顶点坐标:
```c++
cv::Point2f vertices[4];
minRect.points(vertices);
```
2. 计算最小矩形的宽度和高度:
```c++
float width = minRect.size.width;
float height = minRect.size.height;
```
3. 将最小矩形的顶点坐标按照左上、右上、右下、左下的顺序排序:
```c++
// 找到最小矩形的左上角和右下角顶点坐标
int leftTopIndex = 0;
for (int i = 1; i < 4; ++i) {
if (vertices[i].x + vertices[i].y < vertices[leftTopIndex].x + vertices[leftTopIndex].y) {
leftTopIndex = i;
}
}
int rightBottomIndex = 0;
for (int i = 1; i < 4; ++i) {
if (vertices[i].x + vertices[i].y > vertices[rightBottomIndex].x + vertices[rightBottomIndex].y) {
rightBottomIndex = i;
}
}
// 找到最小矩形的右上角和左下角顶点坐标
int rightTopIndex = (leftTopIndex + 1) % 4;
int leftBottomIndex = (rightBottomIndex + 1) % 4;
// 按照左上、右上、右下、左下的顺序存储顶点坐标
cv::Point2f sortedVertices[4];
sortedVertices[0] = vertices[leftTopIndex];
sortedVertices[1] = vertices[rightTopIndex];
sortedVertices[2] = vertices[rightBottomIndex];
sortedVertices[3] = vertices[leftBottomIndex];
```
4. 计算最小矩形的旋转角度:
```c++
float angle = minRect.angle;
```
5. 创建一个新的 cv::Mat 对象,大小为最小矩形的宽度和高度:
```c++
cv::Mat dst(height, width, CV_8UC3, cv::Scalar(0, 0, 0));
```
6. 构建仿射变换矩阵,将最小矩形变换为水平矩形:
```c++
// 计算仿射变换矩阵
cv::Point2f srcPoints[4];
srcPoints[0] = sortedVertices[0];
srcPoints[1] = sortedVertices[1];
srcPoints[2] = sortedVertices[2];
srcPoints[3] = sortedVertices[3];
cv::Point2f dstPoints[4];
dstPoints[0] = cv::Point2f(0, 0);
dstPoints[1] = cv::Point2f(width - 1, 0);
dstPoints[2] = cv::Point2f(width - 1, height - 1);
dstPoints[3] = cv::Point2f(0, height - 1);
cv::Mat transform = cv::getAffineTransform(srcPoints, dstPoints);
// 将最小矩形变换为水平矩形
cv::Mat rotated;
cv::warpAffine(src, rotated, transform, cv::Size(width, height));
```
7. 在新的 cv::Mat 中截取最小矩形区域:
```c++
cv::Rect rect(0, 0, width, height);
cv::Mat result = rotated(rect);
```
这样就可以得到一个新的 cv::Mat 对象 result,它包含了原图中最小矩形的区域,而且不对原图进行任何变换。
阅读全文