简体   繁体   English

递归函数不能按预期工作

[英]Recursive function does not work as desired

I read the attached image with cv2.imread and want to find the contours of the image object.我用cv2.imread读取了附加的图像,并想找到图像对象的轮廓。 If the threshold is too large, ie if cv2.findContours finds several outlines, the threshold should be reduced piece by piece so that only one contour is found at the end.如果阈值过大,即如果cv2.findContours找到了好几条轮廓,就应该cv2.findContours降低阈值,这样到最后只能找到一个轮廓。 That's why I wrote the recursive function thresholdloop , but unfortunately it doesn't do what it should.这就是为什么我写了递归函数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)

依恋

The problem seems to be that your function tries to modify global variables without using the global keyword.问题似乎是您的函数试图在不使用global关键字的情况下修改全局变量。 You could fix it by removing all the parameters from the function and instead doing可以通过从函数中删除所有参数修复它,而是执行

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

But instead I'd suggest using a simple while loop in the global scope itself (ie no 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)

Or like this, so you don't have to replicate the code for calculating cb inside the loop and before或者像这样,所以你不必在循环内和之前复制计算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