Anirudh Katti
Anirudh Katti

Reputation: 11

Extraction of object from image

I have used inRange function to remove all components apart from the two objects in the image. Is there any way I can extract the objects individually from the image? I tried using HoughCircle but got pretty inconsistent results.

Without inRange function(Original Image)

With HoughCircle With HoughCircle

Upvotes: 0

Views: 132

Answers (1)

Stefan Dragnev
Stefan Dragnev

Reputation: 14473

cv::findContours seems like a good fit here:

img = cv.imread('images/suawk.png')

search = cv.dilate(img, cv.getStructuringElement(cv.MORPH_RECT, (5,5)))
search = cv.cvtColor(search, cv.COLOR_BGR2GRAY)
contours, _ = cv.findContours(search, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
bboxes = [cv.boundingRect(c) for c in contours]

fig, axes = plt.subplots(1, sum(rect[2]*rect[3] > 250 for rect in bboxes))
fig.set_size_inches([12,3])
fig.tight_layout()
figi = 0
for i in range(len(contours)):
    rect = cv.boundingRect(contours[i])
    area = rect[2] * rect[3]
    if area < 250:
        continue

    obj = img[rect[1]:rect[1]+rect[3]+1, rect[0]:rect[0]+rect[2]+1, :]
    obj = cv.cvtColor(obj, cv.COLOR_BGR2RGB)
    axes[figi].imshow(obj)
    figi += 1

fig.show()

objects

I do one dilation before findContours, so that I get less fragmented contours. I throw away all contours whose bounding box is smaller than 250px in area to reduce noise.

Upvotes: 1

Related Questions