root = tk.Tk() root.withdraw() f_path = filedialog.askopenfilename() I0 = cv2.imread(f_path ) b, g, r = cv2.split(I0) m, n = r.shape flag = False mode = 0 def abc(x): global flag a = keyboard.KeyboardEvent(event_type='down', scan_code=2, name='1') b = keyboard.KeyboardEvent(event_type='down', scan_code=3, name='2') c = keyboard.KeyboardEvent(event_type='down', scan_code=4, name='3') if x.event_type == a.event_type and x.scan_code == a.scan_code: print("迭代式阈值选择算法") mode = 1 flag = True if x.event_type == b.event_type and x.scan_code == b.scan_code: print("大律算法") flag = True mode = 2 if x.event_type == c.event_type and x.scan_code == c.scan_code: print("三角算法") flag = True mode = 3 keyboard.hook(abc) if flag == False: time.sleep(5) # 等待5秒 if mode == 1: i_b = b.ravel() mea1_b = np.mean(i_b) mea = np.zeros(shape=(1, 1)) while True: mea1 = mea[0] i_b1 = np.where(i_b > mea1_b) mea2_b = np.mean(i_b[i_b1]) i_b2 = np.where(i_b < mea1_b) mea3_b = np.mean(i_b[i_b2]) mea1_b = (mea3_b + mea2_b) / 2 if mea1_b == mea1: break else: mea[0] = mea1_b I_B = b I_B[I_B > mea1_b] = 255 I_B[I_B < mea1_b] = 0 area_b = np.where(I_B == 255) print(mea1_b) i_r = r.ravel() mea1_r = np.mean(i_r) mea = np.zeros(shape=(1, 1)) while True: mea1 = mea[0] i_r1 = np.where(i_r > mea1_r) mea2_r = np.mean(i_r[i_r1]) i_r2 = np.where(i_r < mea1_r) mea3_r = np.mean(i_r[i_r2]) mea1_r = (mea3_r + mea2_r) / 2 if mea1_r == mea1: break else: mea[0] = mea1_r I_R = r I_R[I_R > mea1_r] = 255 I_R[I_R < mea1_r] = 0 area_r = np.where(I_R == 255) I_Rx = area_r[0] I_Ry = area_r[1] print(mea1_r)哪里出现了问题
时间: 2024-03-26 16:36:58 浏览: 131
BankException.zip_bank_deposit_withdraw
在函数 `abc(x)` 中,变量 `mode` 在函数内部被赋值,但没有使用 `global` 声明为全局变量。因此,在后面的条件语句中,`mode` 始终为 0,导致程序一直执行 `mode == 1` 的分支,而不是根据用户输入的按键执行相应的阈值选择算法。解决方法是在函数 `abc(x)` 中,将 `mode` 声明为全局变量,即在函数开头加上 `global mode`。
阅读全文