您的位置:首页 > 编程语言 > C语言/C++

C++ RGB图片任意角度旋转

2016-07-26 16:22 561 查看
int imgRotary(
const Mat									srcImg,//输入图片
const double								degree,//旋转角度
const bool 									clockwise,//旋转方向:顺时针或者逆时针
Mat 										&VertImg)//输出图片
{
if(!srcImg.data){
LOOGE<<"[image error!]";
return -1;
}

//
int nRet = 0;
int row, col;
int iWidth, iHeight;
int rgbmeans[3];
double redSum, greenSum, blueSum;
double total;
Mat M;
double angle, alpha, beta;
int iNewWidth, iNewHeight;
int flag;
Mat imageROI;
int x_begin, y_begin;

//
flag = -1;
if(clockwise)
flag = 1;

//角度转换
angle = degree * CV_PI / 180.;
alpha = cos(flag * angle);
beta  = sin(flag * angle);
//
iWidth = srcImg.cols;
iHeight = srcImg.rows;
total = iWidth * iHeight;

//获取rgb means
for(row = 0; row < iHeight; row++){
auto ptr = srcImg.ptr<uchar>(row);
int tr = 0, tg = 0, tb = 0;
for(col = 0; col < iWidth; col++){
tr = ptr[2];
tg = ptr[1];
tb = ptr[0];

redSum += tr;
greenSum += tg;
blueSum +=tb;

ptr += 3;
}
}
rgbmeans[0] = (int)(redSum / total);
rgbmeans[1] = (int)(greenSum / total);
rgbmeans[2] = (int)(blueSum / total);

//image copy:将原始图片首先复制到目标输出图片的中央,以防止旋转过程中内容的丢失
iNewWidth = cvRound(iWidth * fabs(alpha) + iHeight * fabs(beta));
iNewHeight = cvRound(iHeight * fabs(alpha) + iWidth * fabs(beta));//计算出目标输出图片的大小

x_begin = floor((iNewWidth - iWidth) / 2.);
y_begin = floor((iNewHeight - iHeight) / 2.);//计算图片起始复制坐标
Mat tempImg(iNewHeight, iNewWidth, CV_8UC3);//目标输出图片备份
imageROI = tempImg(Rect(x_begin, y_begin, iWidth, iHeight));
srcImg.copyTo(imageROI); //完成复制

//rotate:将tempImg进行旋转后存入VertImg
M = cv::getRotationMatrix2D(cv::Point2f(iNewWidth / 2., iNewHeight / 2.), degree, 1);
warpAffine(tempImg, VertImg, M, cv::Size(iNewWidth, iNewHeight), 1, 0, 0);

return nRet;
}


参考:C++ Mat 读取imagedata内的数据
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 图片 opencv