如何在 opencv 中使用 Skimage 轮廓?

How to use Skimage contours in opencv?

我正在使用 skimage 进行分水岭处理,因为它可以提供更好的结果。但是一旦找到轮廓,使用 opencv 就可以更容易地找到轮廓属性。

我用它从 skimage 分水岭中找到轮廓:

contours = measure.find_contours(watershed(-distance, markers, mask=th4), 0.8)

绘制轮廓我用这个:

cv2.drawContours(rimg6, [A.astype(np.int32)], -1, (0,255,0), 4)

由于 skimage 提供实数,而 opencv 仅适用于整数,我使用它来将轮廓转换为整数:

A = np.floor(contours[0])
A = A.astype(int)

轮廓图对 [A.astype(np.int32)] 没有任何作用,当我使用 A.astype(np.int32)(我的意思是没有括号)时,我得到这个错误:

OpenCV(4.1.2) /io/opencv/modules/imgproc/src/drawing.cpp:2509: error: (-215:Assertion failed) npoints > 0 in function 'drawContours'

我该怎么办?

OpenCV 轮廓在每个点周围都有一组额外的括号(不知道为什么,一直都是这样)。

这是一个简短的演示脚本,展示了一种从 skimage 轮廓转换为 OpenCV 轮廓的方法。

import cv2
import numpy as np
from skimage import measure

# create empty image
blank = np.zeros((100,100), np.uint8);

# ------------The following lines of code were taken from here-----------
# https://scikit-image.org/docs/dev/auto_examples/edges/plot_contours.html#sphx-glr-auto-examples-edges-plot-contours-py

# Construct some test data
x, y = np.ogrid[-np.pi:np.pi:100j, -np.pi:np.pi:100j]
r = np.sin(np.exp((np.sin(x)**3 + np.cos(y)**2)))

# Find contours at a constant value of 0.8
contours = measure.find_contours(r, 0.8)

# ----------end of code copying--------------

# convert to opencv contour and draw
for con in contours:
    cv_contour = [];
    for point in con:
        intify = [int(point[0]), int(point[1])];
        cv_contour.append([intify]); # extra pair of brackets because ¯\_(ツ)_/¯ it's OpenCV

    # convert to numpy and draw
    cv_contour = np.array(cv_contour);
    cv2.drawContours(blank, [cv_contour.astype(int)], -1, (255), -1);

# resize bigger
blank = cv2.resize(blank, (300,300));
cv2.imshow("Blank", blank);
cv2.waitKey(0);