上面的回答过于复杂,会占用你的CPU。你的问题不是任意旋转,而是“通过90、180、270度旋转Opencv矩阵”。
更新于2017年6月30日:
OpenCV支持此功能,但未记录文档:
https://github.com/opencv/opencv/blob/master/modules/core/include/opencv2/core.hpp#L1041
void rotate(InputArray src, OutputArray dst, int rotateCode);
使用
enum RotateFlags {
ROTATE_90_CLOCKWISE = 0,
ROTATE_180 = 1,
ROTATE_90_COUNTERCLOCKWISE = 2,
};
原始答案和任意角度旋转:
您也可以使用翻转和转置操作来实现此功能,例如对于90度顺时针旋转:
transpose(matSRC, matROT);
flip(matROT, matROT,1); //transpose+flip(1)=CW
等等其他指令自己想出来(思考=学习),通过从文档中介绍的转置和翻转操作形式来介绍自己。
void rot90(cv::Mat &matImage, int rotflag){
if (rotflag == 1){
transpose(matImage, matImage);
flip(matImage, matImage,1);
} else if (rotflag == 2) {
transpose(matImage, matImage);
flip(matImage, matImage,0);
} else if (rotflag ==3){
flip(matImage, matImage,-1);
} else if (rotflag != 0){
cout << "Unknown rotation flag(" << rotflag << ")" << endl;
}
}
所以你要这样调用它,并注意矩阵是通过引用传递的。
cv::Mat matImage;
//Load in sensible data
rot90(matImage,3); //Rotate it
//Note if you want to keep an original unrotated version of
// your matrix as well, just do this
cv::Mat matImage;
//Load in sensible data
cv::Mat matRotated = matImage.clone();
rot90(matImage,3); //Rotate it
任意角度旋转
顺便提一下,以下是如何进行任意角度旋转的方法,我预计这种方法会比普通旋转昂贵50倍。请注意,这种旋转方式会包含黑色填充,并且边缘将被旋转到图像原始大小之外。
void rotate(cv::Mat& src, double angle, cv::Mat& dst){
cv::Point2f ptCp(src.cols*0.5, src.rows*0.5);
cv::Mat M = cv::getRotationMatrix2D(ptCp, angle, 1.0);
cv::warpAffine(src, dst, M, src.size(), cv::INTER_CUBIC);
}
对于一个旋转角度为10.5度的调用,显然是:
cv::Mat matImage, matRotated;
//Load in data
rotate(matImage, 10.5, matRotated);
我觉得非常了不起的是,这些极为基础的功能并不是OpenCV的一部分,而OpenCV确实有一些本地的东西,比如人脸检测(性能可疑,不太稳定)。令人惊叹。
干杯!