OpenCVを使って画像を縮小、拡大してみる。

画像を小さくしたり、大きくしたりしたいけど、正方形なら cv::resize を
使えばいいのだけど 長方形の画像などでは縦横比を維持したまま縮小、拡大したい。

//画面をだすよ
void display(cv::Mat image) {
    //名前をつける
    std::string windowName = "windowName";
    cv::namedWindow(windowName);
    //画面出た!!
    cv::imshow(windowName, image);
    //なにかキーをおして~
    cv::waitKey(1000 * 10);
    //整理整頓
    cv::destroyWindow(windowName);
}

//
// ここから
//
int main(int argc, char** argv) {

    //500x500の画像に変換
    int width = 500;

    cv::Mat convert_mat, work_mat;
    //前処理 余った余白は黒で埋める
    work_mat = cv::Mat::zeros(cv::Size(width, width), CV_8UC3);
    //画面読み込み
    cv::Mat target_mat= cv::imread("starry_night.jpg");

    //縦横どっちか長い方は?
    int big_width = target_mat.cols > target_mat.rows ? target_mat.cols : target_mat.rows;
    //割合
    double ratio = ((double)width / (double)big_width);

    //リサイズ
    cv::resize(target_mat, convert_mat, cv::Size(), ratio, ratio, cv::INTER_NEAREST);

    //中心をアンカーにして配置
    cv::Mat Roi1(work_mat, cv::Rect((width - convert_mat.cols) / 2, (width - convert_mat.rows) / 2, 
    convert_mat.cols, convert_mat.rows));
    convert_mat.copyTo(Roi1);

    target_mat = work_mat.clone();

    //画面へ
    display(target_mat);
    return 0;
}

変換前画像 (752x600) f:id:treehitsuji:20190220114225p:plain

変換後画像 (500x500) f:id:treehitsuji:20190220114236p:plain