我正在嘗試用opencv2創建自動考勤系統,我需要從IP攝像機中獲取rtsp流,從中找到人臉并識別人臉。
我創建了不同的執行緒來抓取幀和繪制,因為人臉識別功能需要一些時間來識別人臉。
但是,僅僅創建兩個執行緒,一個用于讀幀,另一個用于繪圖,就占用了大約70%的CPU。 而創建pytorch_facenet模型又增加了80-90%的CPU使用率。
有沒有人知道如何減少CPU的使用?
我的程式:
import cv2
import threading
from facenet_pytorch import InceptionResnetV1
cap = cv2.VideoCapture("rtsp://test:[email protected]"/span>)
resnet = InceptionResnetV1(pretrained='vggface2').eval()
ret, frame = cap.read()
exit = False[/span]。
def th1()。
global ret, frame, exit
while True:
ret, frame = cap.read()
if exit:
break: break.
def th2()。
global ret, frame, exit
while True:
cv2.imshow('frame', frame)
cv2.waitKey(1)
if cv2.getWindowProperty('frame',cv2.WND_PROP_VISIBLE) < 1:
exit = True 1: 啟用了 "exit
break: exit = True.
t1 = threading.Thread(target=th1)
t1.start()
t2 = threading.Thread(target=th2)
t2.start()
uj5u.com熱心網友回復:
兩個問題。
th2在一個幾乎緊密的回圈中運行。它不會消耗整個核心的CPU,因為waitKey(1)會睡眠一段時間。執行緒之間完全沒有同步,但你需要它。你需要一個
threading.Event來通知消費者執行緒有一個新的幀。消費者執行緒必須等待,直到一個新的幀可用,因為反復顯示同一個舊的幀是毫無意義的。你可以偷懶,用waitKey(30)代替。對于顯示執行緒來說,這已經足夠好了。VideoCapture。你根本就沒有做任何錯誤檢查! 你必須檢查:
cap = cv2.VideoCapture("rtsp://test:[email protected]")
assert cap.isOpened()
...
并且
while True:
ret, frame = cap.read()
if not ret:
break
...
uj5u.com熱心網友回復:
這段代碼有效。
這第一個回圈(執行緒)將試圖以最快的速度讀取幀。 幀可以每秒更新100次或更多,但這太快了。嘗試添加
time.sleep(0.03)。而在第二個回圈中,你可以將
waitKey()的引數改為30。import time def th1()。 global ret, frame, exit while True: ret, frame = cap.read() time.sleep(0.03) if退出。 break break def th2()。 global ret, frame, exit while True: cv2.imshow('frame', frame) cv2.waitKey(30) if cv2.getWindowProperty('frame',cv2.WND_PROP_VISIBLE) < 1: exit = True 1: 啟用了 "exit break: exit = True.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/311686.html
標籤:
上一篇:不能匯入開放的cv模塊
