cv2.connectedComponents not detecting components

前端 未结 1 988
生来不讨喜
生来不讨喜 2021-01-04 10:00

I am on Ubuntu, python 2.7. Working with OpenCV.

I was trying to understand exactly what the function cv2.connectedComponents is doing. This is the image:

相关标签:
1条回答
  • 2021-01-04 10:41

    This is because cv2.connectedComponents() considers only the white portion as a component. Hence you are getting a single component.

    You have to invert your image. You can do so by using cv2.bitwise_not() function.

    CODE:

    import cv2
    import numpy as np
    
    img = cv2.imread('cc.png', 0)
    ret, thresh = cv2.threshold(img, 127, 255, 0)
    
    #---- Inverting the image here ----
    img = cv2.bitwise_not(thresh)     
    _, markers = cv2.connectedComponents(img)
    print np.amax(markers)
    

    RESULT:

    19
    
    0 讨论(0)
提交回复
热议问题