Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop half of an image in OpenCV

Tags:

opencv

crop

roi

mat

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.

like image 681
shjnlee Avatar asked Nov 30 '22 23:11

shjnlee


2 Answers

Here's a the python version for any beginners out there.

def crop_bottom_half(image):
    cropped_img = image[image.shape[0]/2:image.shape[0]]
    return cropped_img
like image 158
rajeevr22 Avatar answered Dec 04 '22 06:12

rajeevr22


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));
like image 40
Olivier Avatar answered Dec 04 '22 06:12

Olivier