圖像平移是將圖像的所有像素坐標進行水平或垂直方向移動,也就是所有像素按照給定的偏移量在水平方向上沿x軸、垂直方向上沿y軸移動。這種操作分為兩種,一種是圖像大小不改變,這樣最后原圖像中會有一部分不在圖像中。還有一種就是圖像大小改變。這樣可以保全原圖像的內容。其公式如下:
\[ \begin{bmatrix} x\\ y\\ 1 \end{bmatrix} \ = \begin{bmatrix} 1 & 0 & dx \\ 0 & 1 &dy \\ 0 & 0 & 1 \end{bmatrix} \ \begin{bmatrix} x0\\ y0\\ 1 \end{bmatrix} \ \]
從實現角度講,其實就是拷貝原圖像中的一部分到新圖像中,用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;
}
運行效果如下:
不改變圖像大小
改變圖像大小