OpenCV Python cv2.connectedComponentsWithStats
Asked Answered
A

1

9

Is it by design that you must pass cv2.connectedComponentsWithStats a white-on-black image as opposed to a black-on-white image? I get different results doing one versus the other.

Example Code:

import os
import cv2

root = r'pth/to/img'
fl = r'img.png'

src = os.path.join( root, fl )

img = cv2.imread( src, 0 )
img_inv = cv2.bitwise_not( img )

cv2.imshow( 'Black-on-White', img )
cv2.waitKey(0)

cv2.imshow( 'White-on-Black', img_inv )
cv2.waitKey(0)

bw_nlbls, bw_lbls, bw_stats, _ = cv2.connectedComponentsWithStats( img )
wb_nlbls, wb_lbsl, wb_stats, _ = cv2.connectedComponentsWithStats( img_inv )

bw = 'Black-On-White'
wb = 'White-On-Black'

print( bw )
print( '-'*len(bw) )
print()
print('Number of Components: ', bw_nlbls)
print()
print( wb )
print( '-'*len(wb) )
print()
print('Number of Components: ', wb_nlbls)

Output:

Black-on-White
ImageBW

White-on-Black
ImageWB

Black-On-White
--------------

Number of Components:  3

White-On-Black
--------------

Number of Components:  6

I'm assuming by the output that:

  1. For the Black-on-White image, black is taken as the background, white as foreground, and the 3 components are the background, the white around the numbers, and the white inside the number 4.

  2. For the White-on-Black image, black is still background and white foreground, but now there are 6 components (the background and five numbers).

Seems logical, but could we add this to the documentation for future users? Could we add the functionality to allow the user to choose what "color" they want represented as background (white or black)?

Amal answered 25/1, 2018 at 0:16 Comment(4)
The related algorithms are working for white on black. For your image, 5 number,1background, total 6 componentsHeliostat
Oops, yes. I meant to say 6 in #2 above. (background plus five numbers for a total of six). Does anyone know how to do a pull request to update the OpenCV documentation?Amal
@Silencer correctedAmal
This question helped me understand perfectly what the connectedComponentsWithStats() function does, ty for posting.Unveiling
J
1

Connected component actually works on background-foreground property, where the black colour is considered as background and white as foreground. This is actually a standard and if you ask me also seems natural. Its the duty of the user to do appropriate inversion if they want to do connected component labelling of black(background) region.

Jumbled answered 22/12, 2020 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.