iT邦幫忙

0

If.. else 的邏輯問題 (Python)

各位前輩好, 小弟最近在研究人臉辨識的專案
最近寫了一個UI介面有個邏輯問題卡關
部分的代碼如下

 if recording:
            ret, frame = cap.read()
            frame,name = frf.recognize(frame, face_detector, face_encoder, encoding_dict)
            imgbytes = cv2.imencode('.png', frame)[1].tobytes()  # ditto
            window['image'].update(data=imgbytes)

            # 顯示 PASS 或 NG, 送訊號開鎖或off
            if name == 'unknown':
                # 紅燈
                window['NG'].update(visible=True)
                window['PASS'].update(visible=False)
            else:
                # 綠燈
                window['PASS'].update(visible=True)
                window['NG'].update(visible=False)
            # 燈號亮後 10 秒熄滅
            # if window['PASS'].visible==True or window['NG'].visible==True:
            #     time.sleep(10)
            #     window['PASS'].update(visible=False)
            #     window['NG'].update(visible=False)

想要的結果是:當辨識失敗, 設定的 NG 燈號會亮起, 反之成功則 PASS 燈號亮起
後面註解的是我想要在亮起後的 10 秒沒有其他動作的話就使兩個燈號 False,
但是條件設定成某個燈號亮起就倒數 10 秒的話會讓整個程式卡住, 因為直接進入這個 if 了, 請教各位前輩有沒有其他適合的條件, 或是相關的建議呢? 非常感謝!

對這問題的直覺是,該用到 state machine這機制的時候。
參考一下: https://ithelp.ithome.com.tw/articles/10225343 對這原理的說明,也早已有 python 的這方面的套件或實作之例。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

2
海綿寶寶
iT邦大神 1 級 ‧ 2021-08-10 10:42:09
最佳解答

主程式會連續執行 20 秒
開始執行後5秒會將狀態改為 Off

簡單寫個範例如下

你可以改成你要的版本
然後就會發現有其他複雜的地方要處理

import threading
import time

name = 'unknown'
light = 'Off'

def job():
	global light
	for i in range(5):
		print("Count thread:", i)
		time.sleep(1)
	light = 'Off'

if name == 'unknown':
	light = 'NG'
	t = threading.Thread(target = job)
	t.start()
else:
	light = 'PASS'
	t = threading.Thread(target = job)
	t.start()

for i in range(20):
  print("Main thread:", i, "Status:", light)
  time.sleep(1)

t.join()

print("Done.")
jihong620 iT邦新手 5 級 ‧ 2021-08-11 10:08:10 檢舉

謝謝你的範例!我再好好研究一下

2
lion_inin
iT邦新手 1 級 ‧ 2021-08-09 08:38:24

您想說的是,當燈亮起後,一定會進入倒數10秒這個程序裡,導致程式暫停10秒不能做更新對吧?

有一個辦法,就是多執行緒,你可以操作看看。

jihong620 iT邦新手 5 級 ‧ 2021-08-09 09:02:56 檢舉

謝謝, 我研究看看!

我要發表回答

立即登入回答