opencvcropmatroi

Crop half of an image in OpenCV


How can I crop an image and only keep the bottom half of it?

I tried:

Mat cropped frame = frame(Rect(frame.cols/2, 0, frame.cols, frame.rows/2));

but it gives me an error.

I also tried:

double min, max;
Point min_loc, max_loc;
minMaxLoc(frame, &min, &max, &min_loc, &max_loc);
int x = min_loc.x + (max_loc.x - min_loc.x) / 2;
Mat croppedframe = = frame(Rect(x, min_loc.y, frame.size().width, frame.size().height / 2));

but it doesn't work as well.


Solution

  • The Rect function arguments are Rect(x, y, width, height). In OpenCV, the data are organized with the first pixel being in the upper left corner, so your rect should be:

    Mat croppedFrame = frame(Rect(0, frame.rows/2, frame.cols, frame.rows/2));