cpp版本
#include<opencv2/opencv.hpp>
#include<opencv2/core.hpp>
cv::Mat myTranslation(const cv::Mat& src, int dx,int dy)
{
//rows行数相当于图像高度
//cols列数,相当于图像宽度
int nrows = src.rows +abs(dy);
int ncols = src.cols +abs(dx);
cv::Mat dst(nrows, ncols, src.type());
dst.setTo(255);
//后面的at函数的两个参数是以行数,列数定义,x为当前像素所在列,y为当前像素所在行
if (src.type() == CV_8UC3) //三通道
{
for (int x = 0; x < src.cols; x++)
{
for (int y = 0; y < src.rows; y++)
{
int newX = x + dx;
int newY = y + dy;
if (newX >= dst.cols|| newX < 0 || newY >= dst.rows || newY < 0)
{
dst.at<cv::Vec3b>(y, x)[0] = 255;
dst.at<cv::Vec3b>(y, x)[1] = 255;
dst.at<cv::Vec3b>(y, x)[2] = 255;
continue;
}
dst.at<cv::Vec3b>(newY, newX)[0] = src.at<cv::Vec3b>(y, x)[0];
dst.at<cv::Vec3b>(newY, newX)[1] = src.at<cv::Vec3b>(y, x)[1];
dst.at<cv::Vec3b>(newY, newX)[2] = src.at<cv::Vec3b>(y, x)[2];
}
}
}
return dst;
}
int main()
{
cv::Mat img = cv::imread("C:/Users/Administrator/Desktop/test.jpg");
cv::Mat dst = myTranslation(img, 100, 300);
cv::imshow("dst",dst);
cv::waitKey(0);
}
python版本:
import cv2
import numpy as np
def myTranslation(src, dx, dy):
h = src.shape[0] #图片行数等于高
w = src.shape[1] #图片列数等于宽
nh = h + abs(dy)
nw = w + abs(dx)
channel = src.shape[2]
if channel == 3:
dst = 255 * np.ones((h, w, channel), src.dtype)
for dw in range(w):
for dh in range(h):
nX = dw + dx
nY = dh + dy
if nX >= dst.shape[1] or nX < 0 or nY >= dst.shape[0] or nY < 0:
continue
else:
dst[nY, nX] = src[dh, dw]
return dst
else:
return None
def main():
src = cv2.imread('C:/Users/Administrator/Desktop/test.jpg')
dst = myTranslation(src, -100, -200)
print(dst.shape[0])
cv2.imshow('dst', dst)
cv2.waitKey(0)
if __name__ == '__main__':
main()