Jan Carvic Lampano
Jan Carvic Lampano

Reputation: 35

Python select ROI OpenCV

Sample Image

Hello,

I created an application in python that select the Region of Interest(ROI) of an image, record and label it. But I has a limit of one ROI per image, anyone know how to have multiple selection of ROI per image? Also on attached image, as you can see I have multiple window, I want it to be in one window with different options, what packages are use on this kind of application.

here's my code in python using opencv2. Thank you in advance for the help

  for image in filelist:
    img = cv2.imread(image)
    fromCenter = False
    r = cv2.selectROI(img, fromCenter)

    lbl = simpledialog.askstring("Image Label", "Please Enter Label")

    result = eTree.SubElement(results, "Image")

    path = eTree.SubElement(result, 'Path')
    roi = eTree.SubElement(result, 'ROI')
    label = eTree.SubElement(result, 'Label')

    path.text = str(image)
    roi.text = str(r)
    label.text = str(lbl)

    tree = eTree.ElementTree(results)
    i = i + 1
    if i == count:
        format = [('XML Files', '*.xml'), ('All Files', '*.*')]
        save = filedialog.asksaveasfilename(filetype=format, defaultextension='*.xml')
        tree.write(save, xml_declaration=True, encoding='utf-8', method="xml")

Upvotes: 1

Views: 19310

Answers (2)

saharshleo
saharshleo

Reputation: 11

For custom ROI you can use EasyROI. It supports rectangle, line, circle and polygon.

For using it:

pip install EasyROI

from EasyROI import EasyROI  
roi_helper = EasyROI()  
roi = roi_helper.draw_rectangle(frame, quantity=2)  

Upvotes: 1

kavko
kavko

Reputation: 2831

Well at least for the first part of the question, have you considered to try the cv2.createROIs() instead of cv2.createROI() ? When the image window is opened you then select your first ROI and press enter, then the second and press enter etc. And when you are finished then press the escape key. It returns x,y,w,h of each ROI. Note that you will have to change your code accordingly but it will allow you to select multiple ROI.

Input image:

enter image description here

Example:

import cv2

img = cv2.imread('rois.png')

fromCenter = False
ROIs = cv2.selectROIs('Select ROIs', img, fromCenter)

ROI_1 = img[ROIs[0][1]:ROIs[0][1]+ROIs[0][3], ROIs[0][0]:ROIs[0][0]+ROIs[0][2]]
ROI_2 = img[ROIs[1][1]:ROIs[1][1]+ROIs[1][3], ROIs[1][0]:ROIs[1][0]+ROIs[1][2]]
ROI_3 = img[ROIs[2][1]:ROIs[2][1]+ROIs[2][3], ROIs[2][0]:ROIs[2][0]+ROIs[2][2]]

cv2.imshow('1', ROI_1)
cv2.imshow('2', ROI_2)
cv2.imshow('3', ROI_3)

cv2.waitKey(0)
cv2.destroyAllWindows()

Result:

enter image description here

enter image description here

enter image description here

Upvotes: 3

Related Questions