角度输出范围[0, 90]
cv::Mat sample(cv::Size(320, 256), CV_8UC3, cv::Scalar::all(0));
cv::RotatedRect r1(cv::Point(40, 50), cv::Size2f(50, 30), 2);
cv::RotatedRect r2(cv::Point(150, 50), cv::Size2f(50, 30), 10);
cv::RotatedRect r3(cv::Point(40, 110), cv::Size2f(50, 30), 90);
cv::RotatedRect r4(cv::Point(140, 150), cv::Size2f(50, 30), 130);
cv::RotatedRect r5(cv::Point(230, 120), cv::Size2f(50, 30), -20);
cv::RotatedRect r6(cv::Point(220, 200), cv::Size2f(50, 30), -50);
std::vector<cv::RotatedRect> r{ r1, r2, r3, r4, r5, r6 };
for (int i = 0; i < r.size(); ++i)
{
//绘制旋转矩形
cv::Point2f vertices[4];
r[i].points(vertices);
for (int i = 0; i < 4; i++)
cv::line(sample, vertices[i], vertices[(i + 1) % 4], cv::Scalar(0, 255, 0), 2);
}
//cv::imwrite("0.jpg", sample);
//cv::Mat src = cv::imread("0.jpg", cv::IMREAD_COLOR);
cv::Mat gray;
cv::cvtColor(sample, gray, cv::COLOR_BGR2GRAY);
cv::Mat binary = gray > 100;
//Find all image contours
std::vector<std::vector<cv::Point> > contours;
cv::findContours(binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
//For each contour
std::vector<cv::RotatedRect> areas;
for (auto contour : contours)
{
//Find it's rotated rect
auto box = cv::minAreaRect(contour);
//绘制旋转矩形
cv::Point2f vertices[4];
box.points(vertices);
for (int i = 0; i < 4; i++)
cv::line(sample, vertices[i], vertices[(i + 1) % 4], cv::Scalar(255, 255, 0), 2);
std::string text = "w: " + std::to_string((int)box.size.width) + " h: " +
std::to_string((int)box.size.height) + " a: " + std::to_string(box.angle).substr(0, 2);
cv::putText(sample, text, box.center - cv::Point2f(25, 0), cv::FONT_HERSHEY_SIMPLEX, 0.4, cv::Scalar(0, 0, 255));
std::cout << "angle: " << box.angle << std::endl;
std::cout << std::endl;
}
cv::resize(sample, sample, cv::Size(), 2, 2);
cv::imwrite("oo.jpg", sample);
图像坐标为左上角,上图中,图像x轴与边缘重合的为w。另外一边为h。角度没有顺时针和逆时针,都在[0~90],顺时针旋转的角度即为多少°