用OpenCV实现图像平移

    xiaoxiao2022-07-03  200

    图像平移是啥东西就不用讲了吧!需要注意的是图像平移有两种第一种是平移后图像大小不变,这样会损失图像的部分;第二种是平移后图像大小变化,这样原图像不会有损失。 直接上代码,大家看效果吧!代码流程如下: 读取图像→显示原图像→调用自定义的函数translateTransform,作平移后图像大小不变的平移处理并显示处理结果→调用自定义的函数translateTransformSize,作平移后图像大小变化的平移处理并显示处理结果。代码如下: 代码中所需图片下载链接:http://pan.baidu.com/s/1hsBtoMg 密码:32ps

    //opencv版本:OpenCV3.0 //VS版本:VS2013 #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/types_c.h> #include <iostream> using namespace cv; //平移后大小不变 void translateTransform(cv::Mat const& src, cv::Mat& dst, int dx, int dy) { CV_Assert(src.depth() == CV_8U); const int rows = src.rows; const int cols = src.cols; dst.create(rows, cols, src.type()); Vec3b *p; for (int i = 0; i < rows; i++) { p = dst.ptr<Vec3b>(i); for (int j = 0; j < cols; j++) { //平移后坐标映射到原图像 int x = j - dx; int y = i - dy; //保证映射后的坐标在原图像范围内 if (x >= 0 && y >= 0 && x < cols && y < rows) p[j] = src.ptr<Vec3b>(y)[x]; } } } //平移后大小变化 void translateTransformSize(cv::Mat const& src, cv::Mat& dst, int dx, int dy) { CV_Assert(src.depth() == CV_8U); const int rows = src.rows + abs(dy); //输出图像的大小 const int cols = src.cols + abs(dx); dst.create(rows, cols, src.type()); Vec3b *p; for (int i = 0; i < rows; i++) { p = dst.ptr<Vec3b>(i); for (int j = 0; j < cols; j++) { int x = j - dx; int y = i - dy; if (x >= 0 && y >= 0 && x < src.cols && y < src.rows) p[j] = src.ptr<Vec3b>(y)[x]; } } } int main(int argc, char** argv[]) { Mat srcimage, dst, dst1; srcimage = imread("25.jpg"); namedWindow("src_window"); imshow("src_window", srcimage); translateTransform(srcimage, dst, 50, 50); namedWindow("dst_window"); imshow("dst_window", dst); translateTransformSize(srcimage, dst1, 50, 50); namedWindow("dst_window1"); imshow("dst_window1", dst1); waitKey(0); }

    运行结果如下图所示运行结果截图中,dst_window显示的是平移时图像尺寸不变的平移结果,可以看见,损失了部分原图;而dst_window1是显示的是平移时图像尺寸变化的平移结果,可以看见,输出图像变大了,原图是没有损失的。

    最新回复(0)