I have an image that contains more than one rois //non-rectangular// in a transparent image.. plz help me how to extract those rois as induvidual roi image
how to Extract rois as induvidual roi images
204 Views Asked by Bharath Kumar At
2
There are 2 best solutions below
4
On
import numpy as np
import matplotlib.pyplot as plt
!mkdir /content/test
!rm -r /content/test/*
image = cv2.imread('/content/test.png')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
canny = cv2.Canny(blurred, 120, 255, 1)
kernel = np.ones((5,5),np.uint8)
dilate = cv2.dilate(canny, kernel, iterations=1)
# Find contours
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
# Iterate thorugh contours and filter for ROI
image_number = 0
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
#cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
ROI = original[y:y+h, x:x+w]
#cv2.imwrite("/content/test/ROI_{}.png".format(image_number), ROI)
image_number += 1
## (4) Create mask and do bitwise-op
mask = np.zeros(image.shape[:2],np.uint8)
cv2.drawContours(mask, [c],-1, 255, -1)
dst = cv2.bitwise_and(image, image, mask=mask)
## Save it
#cv2.imwrite("dst.png", dst)
cv2.imwrite("/content/test/ROI_{}.png".format(image_number), dst)
image_number += 1
# cv2.imshow('canny', canny)
# cv2.imshow('image', image)
# cv2.waitKey(0)
plt.imshow(canny)
plt.imshow(image)here

contoursof the image.Result:
Now we are sure, we have detected all the contours in the image, we can save them individually.
Get the coordinates of each
contourSet the coordinates in the image
Some sample results:
roisfolder before running the code.Code: