opencv實(shí)現(xiàn)圖像平移
更新時間:2022年08月01日 14:34:30 作者:老王隔壁的禿頭大寶貝
這篇文章主要為大家詳細(xì)介紹了opencv實(shí)現(xiàn)圖像平移,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了opencv實(shí)現(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)文章
深入探討C語言中局部變量與全局變量在內(nèi)存中的存放位置
本篇文章是對在C語言中局部變量與全局變量在內(nèi)存中的存放位置進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
在QT5中實(shí)現(xiàn)求兩個輸入值的和并輸出(實(shí)例)
下面小編就為大家?guī)硪黄赒T5中實(shí)現(xiàn)求兩個輸入值的和并輸出(實(shí)例)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
C讀txt到二維數(shù)組的實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄狢讀txt到二維數(shù)組的實(shí)現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12

