仿射變換保證物體形狀的“平直性”和“平行性”。透視變換不能保證物體形狀的“平行性”。仿射變換是透視變換的特殊形式。
將透視變換寫成3*3矩陣形式,即為M;
以下面這張圖為例,實現仿射變換,包括旋轉,平移,縮放,剪切,以圖像中心為變換中心;
仿射變換
旋轉(逆時針旋轉30度)
Mat M=Mat::eye(3,3, CV_32FC1);
float alpha=PI/6;
float tx=0;
float ty=0;
float scale=1;
M.at<float>(0, 0) = cos(alpha);
M.at<float>(0, 1) = sin(alpha);
M.at<float>(0, 2) = (1-cos(alpha))*center.x - sin(alpha)* center.y;
M.at<float>(1, 0) = -sin(alpha);
M.at<float>(1, 1) = cos(alpha);
M.at<float>(1, 2) = sin(alpha)* center.x +(1-cos(alpha))*center.y;
M.at<float>(2, 0) = 0;
M.at<float>(2, 1) = 0;
M.at<float>(2, 2) = 1;
平移(水平和垂直方向各向右平移20個像素)
Mat M=Mat::eye(3,3, CV_32FC1); float alpha=0; float tx=20; float ty=20; float scale=0; M.at<float>(0, 0) = cos(alpha); M.at<float>(0, 1) = sin(alpha); M.at<float>(0, 2) = (1-cos(alpha))*center.x - sin(alpha)* center.y + tx; M.at<float>(1, 0) = -sin(alpha); M.at<float>(1, 1) = cos(alpha); M.at<float>(1, 2) = sin(alpha)* center.x +(1-cos(alpha))*center.y + ty; M.at<float>(2, 0) = 0; M.at<float>(2, 1) = 0; M.at<float>(2, 2) = 1;
縮放(圖像縮小1/2)
Mat M=Mat::eye(3,3, CV_32FC1); float alpha=0; float tx=0; float ty=0; float scale=0.5; M.at<float>(0, 0) = cos(alpha) * scale; M.at<float>(0, 1) = sin(alpha) * scale; M.at<float>(0, 2) = (1-cos(alpha)* scale)*center.x - sin(alpha)* center.y* scale + tx; M.at<float>(1, 0) = -sin(alpha) * scale; M.at<float>(1, 1) = cos(alpha)* scale; M.at<float>(1, 2) = sin(alpha)* center.x* scale +(1-cos(alpha)* scale)*center.y + ty; M.at<float>(2, 0) = 0; M.at<float>(2, 1) = 0; M.at<float>(2, 2) = 1;
錯切變換(剪切變換):
Mat M=Mat::eye(3,3, CV_32FC1); float alpha=PI/12; float tx=0; float ty=0; float scale=1; M.at<float>(0, 0) = 1; M.at<float>(0, 1) = sin(alpha); M.at<float>(0, 2) = (1-cos(alpha))*center.x - sin(alpha)* center.y; M.at<float>(1, 0) = 0; M.at<float>(1, 1) = 1; M.at<float>(1, 2) = sin(alpha)* center.x +(1-cos(alpha))*center.y; M.at<float>(2, 0) = 0; M.at<float>(2, 1) = 0; M.at<float>(2, 2) = 1;
透視變換(透視變換不保證平行性)
Mat M=Mat::eye(3,3, CV_32FC1); float alpha=0; float tx=0; float ty=0; float scale=1; M.at<float>(0, 0) = cos(alpha); M.at<float>(0, 1) = sin(alpha); M.at<float>(0, 2) =(1-cos(alpha))*center.x - sin(alpha)* center.y + tx; M.at<float>(1, 0) = -sin(alpha); M.at<float>(1, 1) = cos(alpha); M.at<float>(1, 2) =sin(alpha)* center.x +(1-cos(alpha))*center.y + ty; M.at<float>(2, 0) = 0.001; M.at<float>(2, 1) = 0.001; M.at<float>(2, 2) = 1;
上述操作使用同一個opencv接口函數:warpPerspective(srcImg, dstImg, M, Size(width, height));