天天看点

OpenCV 对一张图片进行缩放

pyrUp( tmp, dst, Size( tmp.cols2, tmp.rows2 ) 函数 pyrUp 接收了3个参数:

  • tmp: 当前图像, 初始化为原图像 src 。
  • dst: 目的图像( 显示图像,为输入图像的两倍)
  • Size( tmp.cols2, tmp.rows2 ) : 目的图像大小, 既然我们是向上采样, pyrUp 期待一个两倍于输入图像( tmp )的大小。
  • tmp: 当前图像, 初始化为原图像 src 。
  • dst: 目的图像( 显示图像,为输入图像的一半)
  • Size( tmp.cols/2, tmp.rows/2 ) :目的图像大小, 既然我们是向下采样, pyrDown 期待一个一半于输入图像( tmp)的大小。
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

using namespace cv;
using namespace std;

/// 全局变量
Mat src, dst, tmp;

int main(int argc, char** argv)
{
    /// 指示说明
    cout << "\n 缩放示例  \n"  << endl;
    cout << "------------------ \n" << endl;
    cout << " * [u] -> 图片放大2倍  \n" << endl;
    cout << " * [d] -> 图片缩小一半 \n" << endl;
    cout << " * [ESC] -> 关闭程序 \n \n" << endl;

    ///  尺寸必须能被 2^{n} 整除
    src = imread("M:/img/1.png");
    if (!src.data) {
        cout << " 没有数据!——退出程序 \n" << endl;
        return -1;
    }

    tmp = src;
    dst = tmp;

    /// 创建显示窗口
    namedWindow("原图", cv::WINDOW_AUTOSIZE);
    imshow("原图", dst);

    /// 循环
    while (true) {
        int c;
        c = waitKey(10);

        if ((char)c == 27) {
            break;
        }

        if ((char)c == 'u') { // 键盘按下u执行
            pyrUp(tmp, dst, Size(tmp.cols * 2, tmp.rows * 2));
            cout << "** 放大: 图片 x 2 \n" << endl;
        }
        else if ((char)c == 'd') { // 键盘按下d执行
            pyrDown(tmp, dst, Size(tmp.cols / 2, tmp.rows / 2));
            cout << "** 缩小: 图片/ 2 \n" << endl;
        }

        imshow("原图", dst);
        tmp = dst;  // 最后,将输入图像 tmp 更新为当前显示图像, 这样后续操作将作用于更新后的图像。
    }
    return 0;
}