数字图像处理-平移

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值