OpenCV仿射变换——平移
OpenCV仿射变换——平移
- OpenCV仿射变换——平移
-
- 公式及原理
- OpenCV函数
- 实现代码
- 代码执行效果
公式及原理
定义原坐标为(x,y),平移后(xoffect,yoffset)后的坐标为(x*,y* ):
也就是说,原来在(x,y)位置的像素值,被平移到(x’,y’ )位置处,为方便计算机运算,可以写成矩阵样式:
在OpenCV中的防射变换矩阵M就是:
OpenCV函数
通过cv::getAffineTransform函数得到变换矩阵
cv::Mat getAffineTransform(cv::InputArray src, cv::InputArray dst)
输入
InputArray src:表示输入的三个点
InputArray dstL:表示输出的三个点
返回
cv::Mat对象
通过cv::warpAffine得到平移或旋转的cv::Mat对象
void warpAffine(InputArray src, OutputArray dst, InputArray M, Size dsize, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar());
src : Source image.
**dst **: Destination image that has the size dsize and the same type as src .
M –:2\times 3 transformation matrix.
dsize : Size of the destination image.
flags : Combination of interpolation methods (see resize() ) and the optional flag WARP_INVERSE_MAP that means that M is the inverse transformation ( \texttt{dst}\rightarrow\texttt{src} ).
borderMode : Pixel extrapolation method (see borderInterpolate() ). When borderMode=BORDER_TRANSPARENT , it means that the pixels in the destination image corresponding to the “outliers” in the source image are not modified by the function.
borderValue – Value used in case of a constant border. By default, it is 0.
无返回值
实现代码
#include<iostream>
#include<opencv2/core.hpp>
#include<opencv2/imgproc.hpp>
#include<opencv2/highgui.hpp>
int main() {
cv::Mat src = cv::imread("D:\\Windows\\WorkSpace\\imageTest\\OIP.jpg",cv::IMREAD_COLOR);
if (src.empty()) {
std::cout << "failed to read image." << std::endl;
return EXIT_FAILURE;
}
cv::Point2f pt1[3], pt2[3];
float xoffset = src.cols / 5;
float yoffset = src.rows / 3;
pt1[0] = cv::Point2f(0, 0);// 0 0
pt1[1] = cv::Point2f(xoffset, 0);// x 0
pt1[2] = cv::Point2f(0, yoffset);// 0 y
pt2[0] = cv::Point2f(xoffset, yoffset);// x y
pt2[1] = cv::Point2f(xoffset * 2, yoffset);// 2x y
pt2[2] = cv::Point2f(xoffset, yoffset * 2);// x 2y
//生成只有平移的防射矩阵
cv::Mat M;
M = cv::getAffineTransform(pt1, pt2);
std::cout << M << std:: endl;
int col = src.cols;
int row = src.rows;
//std::cout << src.size() << std::endl;
//生成新的显示结果的矩阵(图)
cv::Mat dst = cv::Mat::zeros(col + xoffset, row + yoffset, CV_32FC1);
//std::cout << dst.size() << std::endl;
//平移
cv::warpAffine(src, dst, M, dst.size());
cv::namedWindow("平移前", cv::WINDOW_AUTOSIZE);
cv::imshow("平移前", src);
cv::namedWindow("平移后", cv::WINDOW_AUTOSIZE);
cv::imshow("平移后", dst);
cv::waitKey(0);
}