UnboundLocalError排查:Aadhaar掩码代码变量未定义问题
问题排查:Aadhaar掩码Python代码的UnboundLocalError错误
问题背景
这段用于Aadhaar卡号掩码的Python代码执行时触发UnboundLocalError,提示local variable 'final_image' referenced before assignment;尝试修改final_image后,又出现local variable 'x' referenced before assignment错误。
原始代码
def aadhar_mask_and_ocr(thres_image, resized_image): d = pytesseract.image_to_data(thres_image, output_type=pytesseract.Output.DICT) keys = list(d.keys()) number_pattern = r"(?<!\d)\d{4}(?!\d)" n_boxes = len(d['text']) c = 0 temp = [] UID = [] for i in range(n_boxes): if int(d['conf'][i]) > 20: if re.match(number_pattern, d['text'][i]): if c<2: (x, y, w, h) = (d['left'][i], d['top'][i], d['width'][i], d['height'][i]) final_image = cv2.rectangle(resized_image, (x, y), (x + w, y + h), (255, 255, 255), -1) temp.append(d['text'][i]) c+=1 elif (c>=2) and (d['text'][i] in temp): (x, y, w, h) = (d['left'][i], d['top'][i], d['width'][i], d['height'][i]) final_image = cv2.rectangle(resized_image, (x, y), (x + w, y + h), (255, 255, 255), -1) elif c==2: UID = temp + [ d['text'][i]] c+=1 else: continue final_image = cv2.resize(final_image, None, fx=0.33, fy=0.33) return final_image, UID # Command-line argument # ap = argparse.ArgumentParser() # ap.add_argument("-i", "--image", required = True, # help = "Path to the image to be scanned") # args = vars(ap.parse_args()) image = cv2.imread('/content/img1.jpeg') thres_image, resized_image = preprocessing(image) masked_image, UID = aadhar_mask_and_ocr(thres_image, resized_image)
报错信息
UnboundLocalError Traceback (most recent call last) <ipython-input-44-231e4bfbf02b> in <module> 7 8 thres_image, resized_image = preprocessing(image) ----> 9 masked_image, UID = aadhar_mask_and_ocr(thres_image, resized_image) 10 11 print('Masked digits in given image. Displaying...') <ipython-input-43-131f3ed0ec89> in aadhar_mask_and_ocr(thres_image, resized_image) 23 else: 24 continue ---> 25 final_image = cv2.resize(final_image, None, fx=0.33, fy=0.33) 26 return final_image, UID UnboundLocalError: local variable 'final_image' referenced before assignment
错误原因分析
final_image未定义错误:
只有当循环中识别到符合条件的数字(置信度>20且匹配4位数字模式)时,final_image才会被赋值。如果没有任何符合条件的识别结果,循环结束后final_image从未被初始化,执行cv2.resize时就会触发未定义错误。x未定义错误(修改后出现):
大概率是修改final_image时,误改了代码分支逻辑,导致某个需要使用x的分支没有先对x,y,w,h进行赋值,比如新增的分支直接调用cv2.rectangle但没先从d中提取坐标。
解决方案
1. 初始化final_image
在函数开头就将final_image初始化为resized_image的副本,确保无论循环是否触发赋值,变量都存在:
final_image = resized_image.copy() # 用copy避免修改原图像
2. 确保所有坐标变量的赋值逻辑覆盖
所有调用cv2.rectangle的分支必须先完成x,y,w,h的赋值,避免遗漏。
3. 优化条件判断逻辑
调整分支顺序,避免逻辑漏洞,比如将c==2的判断放在c>=2之前,防止逻辑被覆盖。
修改后的完整代码
import cv2 import pytesseract import re def aadhar_mask_and_ocr(thres_image, resized_image): # 初始化final_image为输入图像的副本,避免未赋值错误 final_image = resized_image.copy() d = pytesseract.image_to_data(thres_image, output_type=pytesseract.Output.DICT) number_pattern = r"(?<!\d)\d{4}(?!\d)" n_boxes = len(d['text']) c = 0 temp = [] UID = [] for i in range(n_boxes): # 跳过置信度低的识别结果 if int(d['conf'][i]) <= 20: continue # 匹配4位数字段 if not re.match(number_pattern, d['text'][i]): continue if c < 2: # 提取坐标并掩码 x, y, w, h = d['left'][i], d['top'][i], d['width'][i], d['height'][i] cv2.rectangle(final_image, (x, y), (x + w, y + h), (255, 255, 255), -1) temp.append(d['text'][i]) c += 1 elif c == 2: # 收集UID第三段 UID = temp + [d['text'][i]] c += 1 elif c >= 2 and d['text'][i] in temp: # 掩码重复出现的前两段数字 x, y, w, h = d['left'][i], d['top'][i], d['width'][i], d['height'][i] cv2.rectangle(final_image, (x, y), (x + w, y + h), (255, 255, 255), -1) final_image = cv2.resize(final_image, None, fx=0.33, fy=0.33) return final_image, UID # 测试代码 image = cv2.imread('/content/img1.jpeg') thres_image, resized_image = preprocessing(image) masked_image, UID = aadhar_mask_and_ocr(thres_image, resized_image)
内容的提问来源于stack exchange,提问作者Vinay Kumar
相关产品推荐
相关产品推荐

