【发布时间】:2020-03-26 06:10:35
【问题描述】:
我的图片;
要求:
我无法理解轴是如何决定使图像始终水平的。
算法:
- 阅读图片
- 寻找外部轮廓
- 绘制轮廓
- 使用外部轮廓检测 minArearect(边界框对我没有帮助)
- 获取旋转矩阵并旋转图像
- 从旋转后的图像中提取所需的补丁
我的代码:
//read the image
img = imread("90.jpeg")
cv::Mat contourOutput = img.clone();
// detect external contour(images will have noise, although example images doesn't have)
std::vector<std::vector<cv::Point> > contours;
cv::findContours(contourOutput, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
int largest_area = 0;
int largest_contour_index = 0;
for (size_t i = 0; i < contours.size(); i++) {
double area = contourArea(contours[i]);
// copy the largest contour index
if (area > largest_area) {
largest_area = area;
largest_contour_index = i;
}
}
//draw contours
drawContours(img, contours, largest_contour_index, Scalar(255, 0, 0),
2);
// detect minimum area rect to get the angle and centre
cv::RotatedRect box = cv::minAreaRect(cv::Mat(contours[largest_contour_index]));
// take the box angle
double angle = box.angle;
if (angle < -45) {
box.angle += 90;
}
angle = box.angle;
// create rotation matrix
cv::Mat rot_mat = cv::getRotationMatrix2D(box.center, angle, 1);
// Apply the transformation
cv::Mat rotated;
cv::warpAffine(img, rotated, rot_mat, img.size(), cv::INTER_CUBIC);
cv::Size box_size = box.size;
if (box.angle < -45.)
std::swap(box_size.width, box_size.height);
// get the cropped image
cv::Mat cropped;
cv::getRectSubPix(rotated, box_size, box.center, cropped);
// Display the image
namedWindow("image2", WINDOW_NORMAL);
imshow("image2", cropped);
waitKey(0);
【问题讨论】:
-
你需要角度还是旋转中心,或者有什么问题?看看我的回答:stackoverflow.com/questions/34237253/…
-
我得到了角度,但我不知道如何总是使它成为 180 度(水平到 x 轴):( 因为我的图像角度不断变化。我是这方面的新手我从 1 天起就被困住了!请帮忙
-
如果角度为 10 度,则将图像和框旋转 170 度。如果是 33.3,则旋转 146.7,以此类推
-
我让它像那样工作!但是我如何推断何时交换 box.width 和 box.height。我是否必须再次找到轮廓并绘制 boundingrect 来裁剪?这与使 minAreaRect 水平的问题有关
标签: c++ image opencv image-processing image-rotation