Connected Components returns an error

Hello, everyone!
I am trying 2 create a watershed algorithm and encountered a following error:

Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\pythonProject\", line 15, in <module>
    ret, marks = cv.connectedComponents(sure_bg)
cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\connectedcomponents.cpp:5632: error: (-215:Assertion failed) iDepth == CV_8U || iDepth == CV_8S in function 'cv::connectedComponents_sub1'

Here is the code:

import cv2 as cv
import numpy as np
image = cv.imread(r'C:\\Users\User\Desktop\im.png')
low_cube = (120,50,50)
high_cube = (155,255,255)
hsv_im = cv.cvtColor(image, cv.COLOR_BGR2HSV)
hsv_mask = cv.inRange(hsv_im, low_cube, high_cube)
cnt, _ = cv.findContours(hsv_mask, cv.RETR_CCOMP, cv.CHAIN_APPROX_NONE)
c = max(cnt, key=cv.contourArea)
#cv.drawContours(image, c, -1, (0,0,255), thickness=3)
dist = cv.distanceTransform(hsv_mask, cv.DIST_L2, 5)
_, res = cv.threshold(dist, 0.4*dist.max(), 255, cv.THRESH_BINARY)
sure_bg = cv.dilate(res, np.ones((3,3)), iterations=3)
unknown = cv.subtract(sure_bg, res)
ret, marks = cv.connectedComponents(sure_bg)

I wonder if anyone helps…

please check sure_bg.dtype (must be 0 or 1, but obviously isnt)

1 Like

what do you mean(0 or 1)? It’s float32

ah, right, the underlying c++ api uses integer types like that…
what you need is np.uint8 or np.int8

yea, probably from the distanceTransform already

You mean, I need to change the dtype of the hsv_msk variable?
If yes, how to do this?..(

no, not that one … :wink:

which exactly then? I didn’t got it

connectedComponents needs uint8 input

1 Like

oh, yea, that works! Thanks a lot!