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
Asked
Active
Viewed 146 times
2 Answers
1
- Find the
contours
of the image.
import cv2
img = cv2.imread("gzgSI.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh,
cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
cv2.drawContours(img, [cnt], 0, (0, 255, 0), 3)
Result:
Now we are sure, we have detected all the contours in the image, we can save them individually.
- Make sure you have created
rois
folder before running the code.
Code:
import cv2
img = cv2.imread("gzgSI.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh,
cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
for i, cnt in enumerate(contours):
x, y, width, height = cv2.boundingRect(cnt)
roi = img[y:y+height, x:x+width]
cv2.imwrite("rois/roi{}.png".format(i), roi)

Ahmet
- 7,527
- 3
- 23
- 47
-
ty ahx... swear i already solved it in a same way )) – Bharath Kumar Oct 08 '20 at 16:20
1
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

Bharath Kumar
- 893
- 9
- 8
-
-
another help plzzz... if possibe ahx plz uh https://stackoverflow.com/q/64267283/8814904 – Bharath Kumar Oct 08 '20 at 17:03
-
-