Attention! This forum will be made read-only by Dec-20. Please migrate to Most of existing active users should've received invitation by e-mail.
Ask Your Question

How to save a rectangular ROI?

asked 2014-02-28 06:39:42 -0500

Serrano P. gravatar image

updated 2014-02-28 08:12:54 -0500

I have extracted contours with cv2.findContours from a binary mask which I created using a segmentation algorithm. Each contour corresponds to an object in the image that I want to a save to a separate image file.

How can I get a rectangular region of interest (ROI) from a set of points (e.g. contour) and save that ROI to a separate image?

I use Python, but if you can post the answer for C++, that's also appreciated.

edit retag flag offensive close merge delete

4 answers

Sort by » oldest newest most voted

answered 2014-03-04 03:40:42 -0500

Serrano P. gravatar image


The OpenCV-Python interface uses NumPy arrays for image objects. So in Python you can do it as follows.

First use cv2.boundingRect to get the bounding rectangle for a set of points (i.e. contours):

x, y, width, height = cv2.boundingRect(contours[i])

You can then use NumPy indexing to get your ROI from the image:

roi = img[y:y+height, x:x+width]

And save the ROI to a new file:

cv2.imwrite("roi.png", roi)
edit flag offensive delete link more


And for realtime processing of images, such as in robotics and surveillance, you can pass the ROI image directly on to the next stage, such as cascade classifier, etc.

Will Stewart gravatar imageWill Stewart ( 2014-03-04 04:31:21 -0500 )edit

TypeError: slice indices must be integers or None or have an __index__ method

Raki gravatar imageRaki ( 2018-08-29 09:02:31 -0500 )edit

answered 2014-02-28 07:07:03 -0500

Haris gravatar image

updated 2014-02-28 07:08:30 -0500

You could use boundingRect() to get bounding box for a contour. See tutorial here

Using the above bounding Rect you can save the image like

   Rect R=boundingRect(contour[i]); // Get bounding box for contour i
   Mat ROI=src(R); //Set ROI on source image
   imwrite("cropped.jpg",ROI); //save ROI image
edit flag offensive delete link more



In Java, the call is to;

public Mat(Mat m, Rect roi)

Will Stewart gravatar imageWill Stewart ( 2014-02-28 15:25:15 -0500 )edit

Thanks for providing the C++ solution! I posted the Python solution myself.

Serrano P. gravatar imageSerrano P. ( 2014-03-04 03:42:21 -0500 )edit

answered 2018-01-14 23:38:28 -0500

hanifalisohag gravatar image

you can easily crop the image in python by using

roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]]

In order to get the two points you can call cv2.setMouseCallback("image", mouse_crop). The function is something like this

def mouse_crop(event, x, y, flags, param):
    # grab references to the global variables
    global x_start, y_start, x_end, y_end, cropping

    # if the left mouse button was DOWN, start RECORDING
    # (x, y) coordinates and indicate that cropping is being
    if event == cv2.EVENT_LBUTTONDOWN:
        x_start, y_start, x_end, y_end = x, y, x, y
        cropping = True

    # Mouse is Moving
    elif event == cv2.EVENT_MOUSEMOVE:
        if cropping == True:
            x_end, y_end = x, y

    # if the left mouse button was released
    elif event == cv2.EVENT_LBUTTONUP:
        # record the ending (x, y) coordinates
        x_end, y_end = x, y
        cropping = False # cropping is finished

        refPoint = [(x_start, y_start), (x_end, y_end)]

        if len(refPoint) == 2: #when two points were found
            roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]]
            cv2.imshow("Cropped", roi)

You can get details from here : Mouse Click and Cropping using Python

edit flag offensive delete link more


Why in a name would you revivie a dead topic of 2014?

StevenPuttemans gravatar imageStevenPuttemans ( 2018-01-15 04:21:55 -0500 )edit

answered 2014-03-01 04:58:05 -0500

York gravatar image

C++ version:

function—Mat roi(image,Rect(20,20,60,60)); that means selecting roi (20,20,60,60) a rectangle you know

edit flag offensive delete link more


York, what would it be for a Rect that already exists in a variable - pls update to show how a variable is passed into this, and you'll start receiving uparrow credits (I'll be the first!)

Will Stewart gravatar imageWill Stewart ( 2014-03-01 08:04:30 -0500 )edit

aoh~get it…just passing by ,sorry for my ignorance ps:credits !who care — —

York gravatar imageYork ( 2014-03-02 00:46:15 -0500 )edit
Login/Signup to Answer

Question Tools


Asked: 2014-02-28 06:39:42 -0500

Seen: 38,730 times

Last updated: Jan 14 '18