43 lines
1.9 KiB
Python
43 lines
1.9 KiB
Python
|
'''
|
|||
|
Program: MT_imgAcquisition.py (Report comments/bugs to chikh@yuntech.edu.tw)
|
|||
|
Function: 擴充imgAcquisitionSave.py成為多執行緒程式
|
|||
|
Note: 本程式以筆電搭配另一個攝像鏡頭執行較能看出多執行緒的效果
|
|||
|
'''
|
|||
|
|
|||
|
import cv2 #引入OpenCV影像處理的相關套件
|
|||
|
from datetime import datetime #引入讀取機器時間相關套件
|
|||
|
import threading #引入多執行緒相關套件
|
|||
|
|
|||
|
threadList = [] #儲存新建之多執行緒的串列
|
|||
|
|
|||
|
def camCapture(ID):
|
|||
|
cap = cv2.VideoCapture(ID) #以ID選擇哪一個攝像鏡頭
|
|||
|
i = 0
|
|||
|
while True:
|
|||
|
ret, frame = cap.read() #從攝像鏡頭讀取一幀影像
|
|||
|
cv2.imshow("Window %d"%ID,frame) #重要!若未加入ID區分,二個鏡頭擷取的影像將重疊在同一視窗上
|
|||
|
if cv2.waitKey(1) & 0xFF in (27,81,113): break #每隔1毫秒偵測是否有按鍵,若有,則讀取最末位元組內容,比對是否為<Esc>、'q'或'Q',倘符合,則退出迴圈
|
|||
|
i += 1
|
|||
|
if (i%40 == 0):
|
|||
|
i = 0 #重設i,避免持續增加i值造成溢位(overflow)
|
|||
|
cv2.imwrite('./opencvData/[%d]-img-%s.jpg'%(ID,datetime.now().strftime("%H-%M-%S")),frame) #影像輸出為檔案儲存
|
|||
|
cap.release() #釋放攝像鏡頭所佔資源
|
|||
|
|
|||
|
#------ 底下是主執行緒 ------#
|
|||
|
howManyCams = int(input("\n這部機器有幾個攝像鏡頭?=> "))
|
|||
|
if howManyCams == 0:
|
|||
|
print("\n程式無法繼續運行,sorry.")
|
|||
|
exit(0)
|
|||
|
elif howManyCams == 1:
|
|||
|
threadList.append(threading.Thread(target=camCapture,args=(0,)))
|
|||
|
threadList[0].start() #啟動執行緒
|
|||
|
threadList[0].join() #等候執行緒結束
|
|||
|
else:
|
|||
|
for i in range(2): #創建二個執行緒,每個執行緒處理單一鏡頭擷取的畫面
|
|||
|
threadList.append(threading.Thread(target=camCapture,args=(i,)))
|
|||
|
threadList[i].start() #啟動執行緒
|
|||
|
for i in range(2):
|
|||
|
threadList[i].join() #等候threadList[i]執行緒結束
|
|||
|
|
|||
|
cv2.destroyAllWindows() #關閉所有視窗
|