opencv實現(xiàn)圖像平移
本文實例為大家分享了opencv實現(xiàn)圖像平移的具體代碼,供大家參考,具體內(nèi)容如下
圖像平移指的是沿水平方向或垂直方向進(jìn)行圖像的移動。
平移變換公式:
對于原始圖像而言,正變換矩陣:
對于目標(biāo)圖像而言,逆變換矩陣:
代碼:
#include<opencv2/imgproc.hpp> #include<opencv2/highgui.hpp> #include<opencv2/core.hpp> #include<iostream> #include<stdlib.h> using namespace std; using namespace cv; ? Mat imgTranslation1(Mat& src, int xOffset, int yOffset); Mat imgTranslation2(Mat& src, int xOffset, int yOffset); int main() { ?? ?Mat src = imread("C:\\Users\\H\\Desktop\\niao.bmp"); ?? ?if (src.empty()) ?? ?{ ?? ??? ?cout << "請檢查圖像是否存在..." << endl; ?? ??? ?return -1; ?? ?} ?? ?pyrDown(src, src); ?? ?cout << "原圖尺寸\trows:" << src.rows << "\tcols: " << src.cols << endl; ? ?? ?int xOffset = 50, yOffset = 80; ?? ? ?? ?Mat dst1 = imgTranslation1(src, xOffset, yOffset); ?? ?imshow("dst1", dst1); ?? ?cout << "平移不改變尺寸\trows: " << dst1.rows << "\tcols: " << dst1.cols << endl; ?? ? ?? ?Mat dst2 = imgTranslation2(src, xOffset, yOffset); ?? ?imshow("dst2", dst2); ?? ?cout << "平移改變尺寸\trows: " << dst2.rows << "\tcols: " << dst2.cols << endl; ?? ?waitKey(0); ?? ?system("pause"); ?? ?return 0; } ? 圖像的平移 ,大小不變 Mat imgTranslation1(Mat& src, int xOffset, int yOffset) { ?? ?int nrows = src.rows; ?? ?int ncols = src.cols; ?? ?Mat dst(src.size(), src.type()); ?? ?for (int i = 0; i < nrows; i++) ?? ?{ ?? ??? ?for (int j = 0; j < ncols; j++) ?? ??? ?{ ?? ??? ??? ?映射變換 ?? ??? ??? ?int x = j - xOffset; ?? ??? ??? ?int y = i - yOffset; ?? ??? ??? ?邊界判斷 ?? ??? ??? ?if (x >= 0 && y >= 0 && x < ncols && y < nrows) ?? ??? ??? ?{ ?? ??? ??? ??? ?dst.at<Vec3b>(i, j) = src.ptr<Vec3b>(y)[x]; ?? ??? ??? ?} ?? ??? ?} ?? ?} ?? ?return dst; } //圖像平移大小改變 Mat imgTranslation2(Mat& src, int xOffset, int yOffset) { ?? ?int nrows = src.rows + abs(yOffset); ?? ?int ncols = src.cols + abs(xOffset); ?? ?Mat dst(nrows, ncols, src.type()); ?? ?for (int i = 0; i < nrows; i++) ?? ?{ ?? ??? ?for (int j = 0; j < ncols; j++) ?? ??? ?{ ?? ??? ??? ?int x = j - xOffset; ?? ??? ??? ?int y = i - yOffset; ?? ??? ??? ?if (x >= 0 && y >= 0 && x < ncols && y < nrows) ?? ??? ??? ?{ ?? ??? ??? ??? ?dst.at<Vec3b>(i, j) = src.ptr<Vec3b>(y)[x]; ?? ??? ??? ?} ?? ??? ?} ?? ?} ?? ?return dst; }
結(jié)果展示:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于C++使用std::chrono獲取當(dāng)前秒級/毫秒級/微秒級/納秒級時間戳問題
這篇文章主要介紹了C++使用std::chrono獲取當(dāng)前秒級/毫秒級/微秒級/納秒級時間戳,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07C++數(shù)據(jù)結(jié)構(gòu)鏈表基本操作示例過程
這篇文章主要為大家介紹了C++數(shù)據(jù)結(jié)構(gòu)鏈表基本操作的示例過程有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2021-11-11vscode?采用C++17版本進(jìn)行編譯的實現(xiàn)
本文主要介紹了vscode?采用C++17版本進(jìn)行編譯,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01C++機(jī)房預(yù)約系統(tǒng)實現(xiàn)流程實例
這篇文章主要介紹了C++機(jī)房預(yù)約系統(tǒng)實現(xiàn)流程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-10-10