2

I have a problem with connectedComponents (or connectedComponentsWithStats) which is an opencv (3.3.0) function in Python (2.7.12). A simple code is the following :

import numpy as np
import cv2

img = np.zeros((4,4), dtype = np.uint8)
img[1,1] = 255
img[2,2] = 255
output = cv2.connectedComponents(img, 4)
print output[1]

It returns

[[0 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 0]]

which is strange since I asked for connected components with connectivity 4 (not 8). So the two pixels in (1, 1) and (2, 2) are not connected and should give two different connected components, labelled 1 and 2 for instance.

Did I make a mistake ?

Adrian
  • 23
  • 5

1 Answers1

3

replacing

output = cv2.connectedComponents(img, 4)

by

output = cv2.connectedComponents(img, connectivity=4)

will give you

[[0 0 0 0]
 [0 1 0 0]
 [0 0 2 0]
 [0 0 0 0]]

Alternatively provide all 3 arguments

output =  cv2.connectedComponents(img, 4, cv2.CV_32S)

I'm not 100% why. I'll leave that to the Python experts out there. From my understanding cv2.connectedComponents(img, 4) should work just fine. But it doesn't

Piglet
  • 27,501
  • 3
  • 20
  • 43