|
OpenCV图像平移
图像平移是将图像的所有像素坐标进行水平或垂直方向移动,也就是所有像素按照给定的偏移量在水平方向上沿x轴、垂直方向上沿y轴移动。这种操作分为两种,一种是图像大小不改变,这样最后原图像中会有一部分不在图像中。还有一种就是图像大小改变。这样可以保全原图像的内容。其公式如下:
OpenCV图像平移
从实现角度讲,其实就是拷贝原图像中的一部分到新图像中,用OpenCV实现代码如下: - Mat imgTranslate(Mat &matSrc, int xOffset, int yOffset, bool bScale)
- {
- // 判断是否改变图像大小,并设定被复制ROI
- int nRows = matSrc.rows;
- int nCols = matSrc.cols;
- int nRowsRet = 0;
- int nColsRet = 0;
- Rect rectSrc;
- Rect rectRet;
- if (bScale)
- {
- nRowsRet = nRows + abs(yOffset);
- nColsRet = nCols + abs(xOffset);
- rectSrc.x = 0;
- rectSrc.y = 0;
- rectSrc.width = nCols;
- rectSrc.height = nRows;
- }
- else
- {
- nRowsRet = matSrc.rows;
- nColsRet = matSrc.cols;
- if (xOffset >= 0)
- {
- rectSrc.x = 0;
- }
- else
- {
- rectSrc.x = abs(xOffset);
- }
- if (yOffset >= 0)
- {
- rectSrc.y = 0;
- }
- else
- {
- rectSrc.y = abs(yOffset);
- }
- rectSrc.width = nCols - abs(xOffset);
- rectSrc.height = nRows - abs(yOffset);
- }
- // 修正输出的ROI
- if (xOffset >= 0)
- {
- rectRet.x = xOffset;
- }
- else
- {
- rectRet.x = 0;
- }
- if (yOffset >= 0)
- {
- rectRet.y = yOffset;
- }
- else
- {
- rectRet.y = 0;
- }
- rectRet.width = rectSrc.width;
- rectRet.height = rectSrc.height;
- // 复制图像
- Mat matRet(nRowsRet, nColsRet, matSrc.type(), Scalar(0));
- matSrc(rectSrc).copyTo(matRet(rectRet));
- return matRet;
- }
- ... prompt'''
复制代码调用代码如下: - #include "opencv2/core/core.hpp"
- #include "opencv2/imgproc/imgproc.hpp"
- #include "opencv2/highgui/highgui.hpp"
- #include <iostream>
- #include <string>
- using namespace cv;
- int main()
- {
- std::string strPath = "D:\\我的文档\\My Pictures\\OpenCV\";
- Mat matSrc = imread(strPath + "熊猫.jpg");
- // 判断是否真确读取数据
- if (matSrc.empty())
- return 1;
- // 平移图像
- Mat matScale_0 = imgTranslate(matSrc, 50, 50, false);
- Mat matScale_1 = imgTranslate(matSrc, -50, -50, false);
- Mat matScale_2= imgTranslate(matSrc, 50, 50, true);
- Mat matScale_3 = imgTranslate(matSrc, -50, -50, true);
-
- // 保存图像
- imwrite(strPath + "0.jpg", matScale_0);
- imwrite(strPath + "1.jpg", matScale_1);
- imwrite(strPath + "2.jpg", matScale_2);
- imwrite(strPath + "3.jpg", matScale_3);
- // 显示图像
- imshow("src", matSrc);
- imshow("ret_0", matScale_0);
- imshow("ret_1", matScale_1);
- imshow("ret_2", matScale_2);
- imshow("ret_3", matScale_3);
- waitKey();
- return 0;
- }
复制代码运行效果如下: 不改变图像大小
OpenCV图像平移
OpenCV图像平移
改变图像大小
OpenCV图像平移
OpenCV图像平移
|
|