Programming, Python, Tutorials

Select ROI or Multiple ROIs [Bounding box] in OPENCV python.

Select ROI in Python DEMO

In this tutorial, we will learn how to Graphically select a Region of interest (ROI) in an image and save it.

There are two functions which can be used to select ROI or ROIs in OPENCV.

  1. “cv2.selectROI” which can be used to select a single ROI bounding box.
  2. cv2.selectROIs” which is used when you want to select multiple ROI from an image.

Selecting Single ROI bounding Box in OpenCV [python].

Select ROI in python

Selecting a single ROI is useful when you are sure you have to crop a single subject/ ROI from the image.

Click and drag the mouse to make bounding box on the image . Press enter to finish selecting ROI and resume the program.

Steps to crop a single single subject from an image.

  1. Import the necessary libraries.
    • import cv2
    • import numpy
  2. Read the image by using “imread” function.
    • img_raw=cv2.imread(img_path)
  3. Pass the image in “SelectROI” function.
    • roi=cv2.selectROI(img_raw)
  4. save the selected rectangle point (roi) in a variable.
    • roi variable will save xy coordinate of left top corner and bottom right corner point of bounding box
  5. Use the rectangle points to crop.
    • roi_cropped=img_raw[int(roi[1]):int(roi[1]+roi[3]), int(roi[0]):int(roi[0]+roi[2])]
  6. Display the Cropped ROI
    • cv2.imshow(“ROI”,roi_cropped)
  7. Save the cropped ROI.
    • cv2.imwrite(“roi.jpeg”,roi_croppped)

Select ROI code [Python Code]

Selecting Multiple ROI bounding box

Multiple ROI selection in OpenCV pyhton

Selecting Multiple ROIs is useful when you have multiple subjects to select from an image.

Use the “selectROIs” function will save selected ROIs rectangle point in a array which can be accessed by using indexing.

Click and drag the mouse to make a bounding box on the image. Press enter every time you select a bounding box this will save your selections in ROIs variable, once you are done selecting press escape to resume the program.

Select Multiple ROIs [Python Code]

Additionally You can use :

By default the bounding box is created from the top left corner but you can also use fromCenter= true argument to start bounding box from the center.

You can disable the cross hair by using showCrosshair= false argument .

Check Out how to Extract Text from Images.– Click Here