注意:RotateRect的角度旋转正方向,顺时针。仿射变换中图片角度旋转正方向是逆时针。
#include "cv.h"
#include "opencv2/imgproc/imgproc.hpp"
#include "highgui.h"
#include "opencv.hpp"
#include "iostream"
using namespace cv;
Mat src;
int nAngle = 0;
int nMaxAngle = 360;
cv::RotatedRect rRect;
char * windowName = "Angle";
void RotateRect(int, void*);
int main(int argc, char** argv)
{
src = Mat(500, 600, CV_8UC3, cv::Scalar::all(255));
// 创建显示窗口
namedWindow(windowName);// , CV_WINDOW_AUTOSIZE
rRect = cv::RotatedRect(cv::Point2f(300, 250), cv::Size2f(100, 50), 0);
// 创建腐蚀 Trackbar
createTrackbar("Angle", windowName, &nAngle, nMaxAngle, RotateRect);
RotateRect(0, 0);
waitKey(0);
return 0;
}
void RotateRect(int, void*)
{
cv::Point2f ptC = cv::Point2f(300, 250);
src = Mat(500, 600, CV_8UC3, cv::Scalar::all(255));
rRect = cv::RotatedRect(ptC, cv::Size2f(100, 50), nAngle);
Point2f vertices[4];
rRect.points(vertices);
int nLineW = 2;
cv::line(src, vertices[0], vertices[1], cv::Scalar(255, 0, 0, 0), nLineW);
cv::line(src, vertices[1], vertices[2], cv::Scalar(0, 0, 0, 0), nLineW);
cv::line(src, vertices[2], vertices[3], cv::Scalar(0, 0, 0, 0), nLineW);
cv::line(src, vertices[3], vertices[0], cv::Scalar(0, 0, 0, 0), nLineW);
cv::circle(src, vertices[0], 4, cv::Scalar(0, 255, 0, 0), CV_FILLED);
cv::circle(src, cv::Point2f(300, 250), 4, cv::Scalar(0, 0, 255, 0), CV_FILLED);
Mat dst;
Mat rotate_matrix = getRotationMatrix2D(ptC, nAngle, 1);
warpAffine(src, dst, rotate_matrix, src.size(), 1, 0, Scalar(0));
imshow(windowName, dst);
}