您的位置:首页 > 运维架构

opencv中图像旋转

2014-03-19 23:40 190 查看
对于180°的旋转问题

可以使用:flip(const oclMat& a, oclMat& b, int flipCode)函数,改变第三个参数可以实现水平(0),竖直(1),水平及竖直(-1)的镜像。

图像的转置

函数:transpose(const oclMat& src, oclMat& dst)

图像的任意角度旋转

推荐阅读:http://blog.csdn.net/lyapple2008/article/details/8022418
                  http://blog.csdn.net/txdb/article/details/6443364

                  http://blog.csdn.net/lichengyu/article/details/8487467

左边这个效果(未截取完整)是参考链接3,右边的效果参考链接1、2





/// 图像旋转(任意角度)
Mat image = src;
double angle = 90.0;
float m[6];
Mat M(2,3,CV_32F,m);
Point center(static_cast<int>(image.cols/2),static_cast<int>(image.rows/2));
M = getRotationMatrix2D(center,angle,1);
Mat dstImage(image.size(),image.type());
warpAffine(image,dstImage,M,image.size());
imshow("dstImage",dstImage);


/// 图像旋转方法二
Mat rotateimage;
float alpha = 30*CV_PI/180;
float transMat[3][3] = { {cos(alpha), -sin(alpha), 0}, {sin(alpha), cos(alpha), 0}, {0, 0, 1} };
MyRotation(src, rotateimage, transMat);
imshow("rotateimage", rotateimage);

void MyRotation(Mat& src, Mat& dst, float TransMat[3][3])
{
CV_Assert(src.data);//运行时检查条件,不满足则抛出异常
CV_Assert(src.depth() != sizeof(uchar));

// 计算目标的边缘点
float left =  0;
float right =  0;
float top =  0;
float down =  0;

float x = src.cols * 1.0f;
float y = 0.0f;
float u1 = x * TransMat[0][0] + y * TransMat[0][1];
float v1 = x * TransMat[1][0] + y * TransMat[1][1];
x = src.cols * 1.0f;
y = src.rows * 1.0f;
float u2 = x * TransMat[0][0] + y * TransMat[0][1];
float v2 = x * TransMat[1][0] + y * TransMat[1][1];
x = 0.0f;
y = src.rows * 1.0f;
float u3 = x * TransMat[0][0] + y * TransMat[0][1];
float v3 = x * TransMat[1][0] + y * TransMat[1][1];

left =  min( min( min(0.0f,u1), u2 ), u3);
right =  max( max( max(0.0f,u1), u2 ), u3);
top =  min( min( min(0.0f,v1), v2 ), v3);
down =  max( max( max(0.0f,v1), v2 ), v3);

// 创建目标图像
dst.create(int(abs(right-left)), int(abs(down-top)), src.type());

CV_Assert( dst.channels() == src.channels() );
int channels = dst.channels();

int i,j;
uchar* p;
uchar* q;
for( i = 0; i < dst.rows; ++i)
{
p = dst.ptr<uchar>(i);//ptr得到任意行的首地址
for ( j = 0; j < dst.cols; ++j)
{
// 旋转
int x = (j+left)*TransMat[0][0] - (i+top)*TransMat[0][1] ; // 参见P115中间的矩阵,修改了相对应项的正负系数
int y = -(j+left)*TransMat[1][0] + (i+top)*TransMat[1][1] ;

if( (x >= 0) && (x < src.cols) && (y >= 0) && (y < src.rows) )
{
q = src.ptr<uchar>(y);
switch(channels)
{
case 1:
{
p[j] = q[x];
break;
}
case 3:
{
p[3*j] = q[3*x] ;
p[3*j+1] = q[3*x+1];
p[3*j+2] = q[3*x+2];
break;
}
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: