2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

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

Posted at

画像を小さくしたり、大きくしたりしたいけど、正方形なら 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)
20190220114225.png

変換後画像 (500x500)
20190220114236.png

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?