Skip to main content
 首页 » 编程设计

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

2025年01月19日10grandyang

我使用 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) 

请您参考如下方法:

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