3

What is the best way to get a floorplan external contour?

enter image description here

Snakes algorithm doesn't work well because some floorplans are too convex.

Dayvid Oliveira
  • 1,157
  • 2
  • 14
  • 34

1 Answers1

5

You just need to adjust the threshold of the grayScale image to include the gray dotted lines path while finding the contours, As the major part of input image is white so we can choose the threshold close to 255, say 230. And then find the contours thresholding.

You may use cv2.approxPolyDP to calculate the approximate polynomial shape, but it won't help much, so that step is optional.

The code snippet may look like this:

import cv2

img = cv2.imread("/Users/anmoluppal/Downloads/1tl6D.jpg")

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(img_gray, 230, 255, cv2.THRESH_BINARY_INV)

img_, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

largest_contour_area = 0
for cnt in contours:
    if (cv2.contourArea(cnt) > largest_contour_area):
        largest_contour_area = cv2.contourArea(cnt)
        largest_contour = cnt

epsilon = 0.001*cv2.arcLength(largest_contour,True)
approx = cv2.approxPolyDP(largest_contour,epsilon,True)

final = cv2.drawContours(img, [approx], 0, [0, 255, 0])

enter image description here

ZdaR
  • 22,343
  • 7
  • 66
  • 87
  • Awesome. Just change the 5th line so that: contours, hierarchy = cv2.findContours(...) and also largest_contour is not assigned if contours is empty. – Dayvid Oliveira Jul 16 '16 at 15:05
  • `cv2.findContours` returns 3 values in Opencv 3.1 but returned only 2 values in Opencv2.7. So that thing is version dependent, and You need to calculate the largest contour because it is possible that there may be some small conoturs formed in the image which need to be neglected. – ZdaR Jul 17 '16 at 07:27
  • Ok then. About the largest contour, I mean in the case where 'contours' is empty ... – Dayvid Oliveira Jul 17 '16 at 14:24