5

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.

shjnlee
  • 221
  • 2
  • 6
  • 20

3 Answers3

11

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
rajeevr22
  • 128
  • 5
  • 2
    `img[int(img.shape[0]/2):int(img.shape[0])]` in the case that the height and/or width is an odd number. – Spectric Mar 30 '21 at 22:13
6

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));
Olivier
  • 921
  • 10
  • 19
  • Can you pls add the code to get left half and right half of the image. – sreenath Sep 11 '19 at 19:15
  • @sreenath `Mat halfLeft = frame(Rect(0, 0, frame.cols/2, frame.rows));` `Mat halfRight = frame(Rect(frame.cols/2, 0, frame.cols/2, frame.rows));` – Olivier Sep 12 '19 at 12:18
4

To quickly copy paste:

image = YOURIMAGEHERE #note: image needs to be in the opencv format
height, width, channels = image.shape
croppedImage = image[int(height/2):height, 0:width] #this line crops

Explanation:

In OpenCV to select a part of an image,you can simply select the start and end pixels from the image. The meaning is:

image[yMin:yMax, xMin:xMax]

In human speak: yMin = top | yMax = bottom | xMin = left | xMax = right |

" : " means from the value on the left of the : to the value on the right

To keep the bottom half we simply do [int(yMax/2):yMax, xMin:xMax] which means from half the image to to the bottom. x is 0 to the max width.

Keep in mind that OpenCV starts from the top left of an image and increasing the Y value means downwards.

To get the width and height of an image you can do image.shape which gives 3 values:

yMax,xMax, amount of channels of which you probably won't use the channels. To get just the height and width you can also do:

height, width = image.shape[0:2]

This is also known as getting the Region of Interest or ROI

Osi
  • 406
  • 3
  • 13