连接组件清理cv2.arcLength OpenCv:断言失败

时间:2013-02-28 10:08:26

标签: python opencv image-processing

我正在尝试在OpencCV 2.3.4 Python API中实现连接组件噪声消除,如Learning OpenCV中的第287页所述

我已经计算了轮廓的长度,我得到了一个神秘的断言错误。

OpenCV Error: Assertion failed (curve.checkVector(2) >= 0 && (curve.depth() == CV_32F || curve.depth() == CV_32S)) in unknown function, file ..\..\..\OpenCV-2.4.3\modules\imgproc\src\contours.cpp, line 1886

这是我的代码:

import cv2
import os
import numpy as np
import cPickle

CVCONTOUR_APPROX_LEVEL = 2
CVCLOSE_ITR = 1

def main():
    mask = cv2.imread('input.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
    findConnectedComponents(mask)

def findConnectedComponents(mask,
                            poly1Hull0 = 1,
                            perimScale = 4,
                            num = None,
                            bbs = None,
                            centers = None):
    cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.array(0), iterations=CVCLOSE_ITR)
    cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.array(0), iterations=CVCLOSE_ITR)

    contours = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    #the Pickle trick solves some strange type errors
    tmp = cPickle.dumps(contours)    
    contours = cPickle.loads(tmp)

    for contour in contours:
        perimeter = cv2.arcLength(np.array(contour), True)

if __name__ == '__main__':
    main()
    print 'done'

任何想法错误意味着什么以及如何绕过它?

1 个答案:

答案 0 :(得分:2)

1 - cv2.findContours()为您提供两个输出,轮廓和层次结构。您只指定了轮廓。所以改变行如下(这是主要错误):

contours,hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

2 - contours是numpy数组的列表。每个阵列都是轮廓。所以当你将轮廓传递给cv2.arcLength()时,你不需要再将它变成一个numpy数组。 (这不是错误,而是不必要的操作),所以改变该行如下:

   for contour in contours:
        perimeter = cv2.arcLength(contour, True)

现在尝试使用您的代码并检查它是否有效!!!

有关OpenCV轮廓操作的更多详细信息, visit here.