OpenCV圖像平移

圖像平移是將圖像的全部像素座標進行水平或垂直方向移動,也就是全部像素按照給定的偏移量在水平方向上沿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實現代碼以下:ios

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'''

調用代碼以下:ui

#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;
}

運行效果以下:spa

不改變圖像大小
這裏寫圖片描述 這裏寫圖片描述
改變圖像大小
這裏寫圖片描述 這裏寫圖片描述3d

相關文章
相關標籤/搜索