繁体   English   中英

递归函数不能按预期工作

[英]Recursive function does not work as desired

我用cv2.imread读取了附加的图像,并想找到图像对象的轮廓。 如果阈值过大,即如果cv2.findContours找到了好几条轮廓,就应该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)

依恋

问题似乎是您的函数试图在不使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM