2

I am having trouble detecting contours in this image

Class Diagram Image

I want to detect all border contours in the diagram but so far my program is only detecting the image border as shown in this image

Ignore the 0 in the center that is just to show that it is contour 0.

I am not sure where the problem lies in my code as it can detect contours in images with a black background.

filename = sys.argv[1]
t = int(sys.argv[2])
img = cv2.imread(filename)

resized = imutils.resize(img, width=300)
ratio = img.shape[0] / float(resized.shape[0])

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
(t, binary) = cv2.threshold(blur, t, 255, cv2.THRESH_BINARY)

_ ,cnts, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

for (i,c) in enumerate(cnts):
    M = cv2.moments(c)
    if M["m00"] != 0:
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])
    else:
        cX, cY = 0, 0
    (x,y,w,h) = cv2.boundingRect(c)
    area = cv2.contourArea(c)
    cv2.rectangle(img, (x, y), (x + w, y + h),(0, 255, 255), 2)
    print("Object %d has dimensions x=%d, y=%d, w=%d, h=%d area=%d" % (i,x,y,w,h,int(w*h)))
    cv2.putText(img, str(i), (cX, cY),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
TQA
  • 267
  • 3
  • 12

2 Answers2

1

If you don't want to invert your image, you can use cv2.THRESH_BINARY_INV instead.

(t, binary) = cv2.threshold(blur, t, 255, cv2.THRESH_BINARY_INV)
Mairkur
  • 177
  • 1
  • 15
0

I am note sure where the problem lies in my code as it can detect contours in images with a black background.

This is almost definitly your problem. From the OpenCV tutorial

In OpenCV, finding contours is like finding white object from black background. So remember, object to be found should be white and background should be black.

This SO Q/A shows you how to invert your image.

You definitely need to be detecting white on black, as discussed here

GPPK
  • 6,546
  • 4
  • 32
  • 57