Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV Python cv2.connectedComponentsWithStats

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)?

like image 412
A. Hendry Avatar asked Jan 25 '18 00:01

A. Hendry


1 Answers

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.

like image 177
Operator77 Avatar answered Nov 08 '22 18:11

Operator77