1

I have this image:

This is the image I want to work on

I want to extract the rectangular extension highlighted below from the whole ROI.

Rectangluar extensions to extract

3
  • This will be an answer.
    – shimo
    Dec 28, 2019 at 8:25
  • No this does't work for me as the rectangles are the part of whole object and doesn't lie at edge so edge detection doesn't differentiate the wanted rectangles with the object. Dec 28, 2019 at 11:06
  • 3
    Welcome to stackoverflow. This isn't a free code writing service. Neither is it a replacement for tutorials or web searches. Please read How to Ask. Then edit your question and add the code you've tried so far. What happens when you run it? What did you expect to happen instead? Any errors?
    – Robert
    Dec 28, 2019 at 17:11

1 Answer 1

2

Here's a simple approach using morphological operations + contour filtering with cv2.contourArea()


Otsu's threshold -> morphological closing + invert -> result

Code

import cv2

# Load image, convert to grayscale, Otsu's threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Create kernel and morph close 
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9,9))
close = 255 - cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=5)

# Find contours and filter using contour area
cnts = cv2.findContours(close, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area > 100 and area < 25000:
        cv2.drawContours(image, [c], -1, (36,255,12), 4)

cv2.imshow('thresh', thresh)
cv2.imshow('close', close)
cv2.imshow('image', image)
cv2.waitKey()

Not the answer you're looking for? Browse other questions tagged or ask your own question.