递归函数不能按预期工作

时间:2018-02-09 14:28:44

标签: python recursion

我用cv2.imread阅读附件图像,想要找到图像对象的轮廓。如果阈值太大,即如果cv2.findContours找到几个轮廓,则应逐个减小阈值,以便在结尾处仅找到一个轮廓。 这就是我编写递归函数thresholdloop的原因,但不幸的是它没有做到它应该做的事情。

import cv2   

b = cv2.imread("test.tiff")

thresh_factor = 140


imgray_b = cv2.cvtColor(b,cv2.COLOR_BGR2GRAY)
ret_b,thresh_b = cv2.threshold(imgray_b,thresh_factor,255,0)

_, cb, _ = cv2.findContours(thresh_b, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)


def thresholdloop(cb, thresh_factor, X):

    while X == False:
        if len(cb) > 1:
            thresh_factor = thresh_factor - 5
            ret_b, thresh_b = cv2.threshold(imgray_b, thresh_factor, 255, 0)
            _, cb, _ = cv2.findContours(thresh_b, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
            X = False
            return thresholdloop(cb, thresh_factor, X)
        else:
            X = True

X = False
thresholdloop(cb, thresh_factor, X)

Attachment

1 个答案:

答案 0 :(得分:1)

问题似乎是您的函数尝试在不使用global关键字的情况下修改全局变量。你可以通过从函数中删除所有参数来修复它,而不是

def thresholdloop():
    global ret_b
    global cb
    global thresh_b
    global thresh_factor
    # rest of function

但我建议在全局范围内使用简单的while循环(即没有函数)

# after first calculation of cb
while len(cb) > 1:
    thresh_factor = thresh_factor - 5
    ret_b, thresh_b = cv2.threshold(imgray_b, thresh_factor, 255, 0)
    _, cb, _ = cv2.findContours(thresh_b, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)

或者像这样,所以你不必复制用于在循环内和之前计算cb的代码

b = cv2.imread("test.tiff")
thresh_factor = 145  # + 5
imgray_b = cv2.cvtColor(b,cv2.COLOR_BGR2GRAY)
while True:
    thresh_factor = thresh_factor - 5
    ret_b, thresh_b = cv2.threshold(imgray_b, thresh_factor, 255, 0)
    _, cb, _ = cv2.findContours(thresh_b, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
    if len(cb) == 1:
        break