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

OpenCV 的AffineTransform(传说中的仿射变换)

2015-04-26 21:47 246 查看
为了让数据集能够有旋转不变形,希望在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可以计算出仿射变换之后的点坐标。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: