Ask Your Question

How to crop an image using C/C++ ?

asked 2015-12-11 09:40:14 -0500

u9009 gravatar image

updated 2015-12-11 11:34:06 -0500

I tried this example:

#include <opencv2/opencv.hpp>
#include <highgui.h>

int main(int argc, char* argv[])
    cv::Mat img = cv::imread(argv[1]);
    if (img.empty())
        std::cout << "!!! imread() failed to open target image" << std::endl;
        return -1;        

    /* Set Region of Interest */

    int offset_x = 129;
    int offset_y = 129;

    cv::Rect roi;
    roi.x = offset_x;
    roi.y = offset_y;
    roi.width = img.size().width - (offset_x*2);
    roi.height = img.size().height - (offset_y*2);

    /* Crop the original image to the defined ROI */

    cv::Mat crop = img(roi);
    cv::imshow("crop", crop);

    cv::imwrite("noises_cropped.png", crop);

    return 0;

but when I launch it some window appears and it can't rewrite existing image, it can write to another one, but I don't need it, I want it to do silently - without windows, and better to rewrite existing image. C++ is preferable.

edit retag flag offensive close merge delete


  • unfortunately, you don't seem to know, what you're doing in general. (that's not bad, just unfortunate, we all start like that...)
  • please do not include outdated c-api headers, like highgui.h (if it does not end in .hpp, it's not c++ [here])
  • if you don't like the window showing up, just comment the imshow() and waitKey() lines
  • your offset calculation is a bit dangerous. roi.width = img.size().width - (offset_x*2); might lead to negative values(say, for images smaller than 2*129)

  • again, you're slightly obscure about the problem, - what is it exactly, now ?

berak gravatar imageberak ( 2015-12-11 11:56:17 -0500 )edit

The window was the main problem, and now I can rewrite the image, thanks a lot.

u9009 gravatar imageu9009 ( 2015-12-11 12:14:14 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2015-12-11 12:29:22 -0500

kaushikmit gravatar image

If you want it to write it to another file, then you can use something like this inside the loop

    stringstream ssfn;
    ssfn << filenumber << ".png";
    filename = ssfn.str();

and for writing it to that file

crop  = frame(roi);

If you want to write to the same file name

catch(Exception e){}
crop  = frame(roi);
edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower


Asked: 2015-12-11 09:40:14 -0500

Seen: 57,410 times

Last updated: Dec 11 '15