使用opencv3在生成连接组件时出现错误

时间:2019-11-08 11:10:40

标签: python-3.x image-processing opencv3.0

我想使用功能cv2.connectedComponentsWithStats 获得连接性

from skimage import io
from skimage.color import rgb2gray
img1 = io.imread('Bingo/25.jpg', as_gray=True)

from scipy import ndimage

def sobel_filters(img):
    Kx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], np.float32)
    Ky = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]], np.float32)

    Ix = ndimage.filters.convolve(img, Kx)
    Iy = ndimage.filters.convolve(img, Ky)

    G = np.hypot(Ix, Iy)
    G = G / G.max() * 255
    theta = np.arctan2(Iy, Ix)
    return G


e=sobel_filters(img1)
threshold = 70

# make all pixels < threshold black
binarized = 1.0 * (e > threshold)
connectivity = 4 # or whatever you prefer

output = cv2.connectedComponentsWithStats(binarized, connectivity,cv2.CV_32S)

但是我遇到了错误

error: (-215:Assertion failed) iDepth == CV_8U || iDepth == CV_8S in function 'cv::connectedComponents_sub1'

我应该做些什么才能使其正确?

1 个答案:

答案 0 :(得分:0)

您需要将图像数据类型转换为uint8

尝试

bin_uint8 = (binarized * 255).astype(np.uint8)
output = cv2.connectedComponentsWithStats(bin_uint8, connectivity,cv2.CV_32S)