OpenCV 的AffineTransform(傳說中的仿射變換)
阿新 • • 發佈:2018-11-01
為了讓資料集能夠有旋轉不變形,希望在caffe訓練處好結果,我對採集的資料集進行了一個仿射變換。
利用opencv可以比較方便的實現這個事情。
我的資料集還有一些點標註。標註需要在圖片旋轉的同時把關鍵點也旋轉到合適的位置。
Mat affineTransform(Mat src, std::vector<float>& v)
{
Mat rot_mat(2, 3, CV_32FC1);
Mat dst = Mat::zeros(src.rows, src.cols, src.type());
/** Rotating the image after Warp */
/// Compute a rotation matrix with respect to the center of the image
Point center = Point(dst.cols / 2, dst.rows / 2);
double scale = 0.7;
double angle = rand()%720;
/// Get the rotation matrix with the specifications above
rot_mat = getRotationMatrix2D(center, angle, scale);
double a11 = rot_mat.at<double>(0,0);
double a12 = rot_mat.at<double>(0,1);
double a21 = rot_mat.at<double>(1,0);
double a22 = rot_mat.at<double>(1,1);
double b11 = rot_mat.at<double>(0,2);
double b12 = rot_mat.at<double>(1,2);
/// Rotate the warped image
warpAffine(src, dst, rot_mat, dst.size());
int ftx = v[0]*src.cols;;
int fty = v[1]*src.rows;
int bnx = v[2]*src.cols;
int bny = v[3]*src.rows;
//calculation of new label
float cftx = (ftx*a11+fty*a12+b11)/src.cols;
float cfty = (ftx*a21+fty*a22+b12)/src.rows;
float cbnx = (bnx*a11+bny*a12+b11)/src.cols;
float cbny = (bnx*a21+bny*a22+b12)/src.rows;
//write vector
v.erase(v.begin(),v.end());
v.push_back(cftx);v.push_back(cfty);
v.push_back(cbnx);v.push_back(cbny);
return dst;
}
函式傳入的vector裡面是某些點(我自己做實驗的時候需要的一些關鍵點。。)利用rotationMatrix可以計算出仿射變換之後的點座標。
Mat affineTransform(Mat src, std::vector<float>& v)
{
Mat rot_mat(2, 3, CV_32FC1);
Mat dst = Mat::zeros(src.rows, src.cols, src.type());
/** Rotating the image after Warp */
/// Compute a rotation matrix with respect to the center of the image
Point center = Point(dst.cols / 2, dst.rows / 2);
double scale = 0.7;
double angle = rand()%720;
/// Get the rotation matrix with the specifications above
rot_mat = getRotationMatrix2D(center, angle, scale);
double a11 = rot_mat.at<double>(0,0);
double a12 = rot_mat.at<double>(0,1);
double a21 = rot_mat.at<double>(1,0);
double a22 = rot_mat.at<double>(1,1);
double b11 = rot_mat.at<double>(0,2);
double b12 = rot_mat.at<double>(1,2);
/// Rotate the warped image
warpAffine(src, dst, rot_mat, dst.size());
int ftx = v[0]*src.cols;;
int fty = v[1]*src.rows;
int bnx = v[2]*src.cols;
int bny = v[3]*src.rows;
//calculation of new label
float cftx = (ftx*a11+fty*a12+b11)/src.cols;
float cfty = (ftx*a21+fty*a22+b12)/src.rows;
float cbnx = (bnx*a11+bny*a12+b11)/src.cols;
float cbny = (bnx*a21+bny*a22+b12)/src.rows;
//write vector
v.erase(v.begin(),v.end());
v.push_back(cftx);v.push_back(cfty);
v.push_back(cbnx);v.push_back(cbny);
return dst;
}
函式傳入的vector裡面是某些點(我自己做實驗的時候需要的一些關鍵點。。)利用rotationMatrix可以計算出仿射變換之後的點座標。