[英]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.