Skip to content

Instantly share code, notes, and snippets.

@1duo
Created July 16, 2018 22:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1duo/c868f0bccf0d1f6cd8b36086ba295e04 to your computer and use it in GitHub Desktop.
Save 1duo/c868f0bccf0d1f6cd8b36086ba295e04 to your computer and use it in GitHub Desktop.
Center crop using OpenCV.

C++ main.cpp:

#include <opencv2/core/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <string>

using namespace cv;
using namespace std;

int main(int argc, char** argv) {
    string imageName("./images.jpeg"); // by default
    if (argc > 1) {
        imageName = argv[1];
    }

    Mat image;
    image = imread(imageName.c_str(), IMREAD_COLOR);
    if (image.empty()) {
      cout <<  "Could not open or find the image" << std::endl ;
      return -1;
    }
    cout << "Initial image dimension: " << image.cols << " X " << image.rows << endl;

    namedWindow( "Display window", WINDOW_AUTOSIZE );
    imshow( "Display window", image );
    waitKey(0);

    const int cropSize = 128;
    const int offsetW = (image.cols - cropSize) / 2;
    const int offsetH = (image.rows - cropSize) / 2;
    const Rect roi(offsetW, offsetH, cropSize, cropSize);
    image = image(roi).clone();
    cout << "Cropped image dimension: " << image.cols << " X " << image.rows << endl;

    imshow( "Display window", image );
    waitKey(0);
    return 0;
}

Compile:

g++ -std=c++11 main.cpp `pkg-config --libs --cflags opencv` -o main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment