python - 递归函数无法按预期工作

标签 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

最佳答案

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

关于python - 递归函数无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48708038/

相关文章:

python - 使用递归组合字典中的值

java - 澄清二叉搜索树中的有序遍历

java - 了解 Java 递归代码以检查树是否是有效的二叉搜索树

python - 搜索算法但针对函数

python - 在 Python Dataflow/Apache Beam 上启动 CloudSQL 代理

python - 使用 Selenium Python 通过值属性查找元素

java - Java 中的高级递归

python - 如何将 tuple1 if ... else tuple2 传递给 str.format?

python - 使用 If 条件时 Python 中的 NoneType 错误

c - 在 C 中对 char 数组进行操作的递归函数中的段错误