旋转后的图像恢复水平

一幅图中的目标各种角度不一,想将这些小目标都摆到水平。那么就要知道旋转矩阵,然后求逆矩阵变换回去就可以。比如A旋转成了图B,求得旋转矩阵H,求H的逆矩阵M就可以由B变回A。

但是往往现实中不知道A是什么样,只给出了B,求A是什么样。我以为这是很简单的问题,写完了才知道不是我以为那样。

旋转后的图像恢复水平_第1张图片我的结果类似这样,将其中一些目标放到右边这样水平,大致就是这意思。

//旋转恢复,即恢复旋转之前的状态
/*
input:box-------------小目标的最小外接矩形
      boxlongside-----box的长边
	  boxshortside----box的短边
output:standardobj----用来存放恢复旋转的图片
*/
int cnnAlgae::ratateDebugImgs(RotatedRect &box,float &boxlongside,float &boxshortside,vector &standardobj)
{
	//想要的最终的结果 长宽
	double Angle;
	if(box.size.width>box.size.height)
	{
		Angle =-1*box.angle;
	}
	else
	{
		Angle =90-1*box.angle;
	}
	Point2f center22(boxlongside/2.0, boxshortside/2.0);
	Mat rot = getRotationMatrix2D(center22, Angle, 1.0);

	//得到第一次旋转后的矩形
	//竟然可能超出边界
	Rect therect=box.boundingRect();
	int rmax=therect.y+therect.height;
	int cmax=therect.x+therect.width;
	//超出边界的要补充图像长/宽 后续补充

	//第一次旋转后的结果 长宽变了 中心点调整
	//轮廓最小外接矩形的正矩形才是旋转过后的大小,注意不是轮廓的正矩形
	rot.at(0, 2) += (therect.width/ 2.0 - center22.x);
	rot.at(1, 2) += (therect.height/ 2.0 - center22.y);

	//solution 3:by self
	double costheta=rot.ptr(0)[0];
	double sintheta=rot.ptr(1)[0];
	double tx=rot.ptr(0)[2];
	double ty=rot.ptr(1)[2];
	double txaffine=-1*tx*costheta-ty*sintheta;
	double tyaffine=-1*ty*costheta+tx*sintheta;
	Mat affinematrix(2,3,CV_64FC1);
	affinematrix.ptr(0)[0]=costheta;
	affinematrix.ptr(0)[1]=sintheta;
	affinematrix.ptr(0)[2]=txaffine;
	affinematrix.ptr(1)[0]=-1*sintheta;
	affinematrix.ptr(1)[1]=costheta;
	affinematrix.ptr(1)[2]=tyaffine;


	for(int j=0;j!=srcgrayimgs.size();j++)
	{
		Mat objgray(therect.height,therect.width,CV_8UC1,Scalar(0));
		for(int r=therect.y;r!=rmax;r++)
		{
			for(int c=therect.x;c!=cmax;c++)
			{
				if(r<0 || c<0 || r>2047 || c>2447)
				{
					continue;
				}
				objgray.ptr(r-therect.y)[c-therect.x]=(srcgrayimgs[j]).ptr(r)[c];
			}
		}
		Mat Rotatedback;//恢复旋转后的图片
		//imwrite("problem.jpg",objgray);
		warpAffine(objgray, Rotatedback, affinematrix, Size(boxlongside, boxshortside));
		//imwrite("problemrotate.jpg",Rotatedback);
		standardobj.push_back(Rotatedback);
	}


	return 0;
}

完毕。亲测OK。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

旋转后的图像恢复水平_第2张图片

你可能感兴趣的:(opencv)