Python/Basic/chick_python_exam/Unit1_basic/EXEcode/imgAcquisitionSave.py
2024-06-27 15:41:10 +08:00

27 lines
1.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'''
Program: imgAcquisitionSave.py (Report comments/bugs to chikh@yuntech.edu.tw)
Function: 開啟攝影鏡頭擷取動態影像,每隔一段時間把攝得的影像存檔,檔名內嵌擷取時間
Notes: 1) 請先安裝opencv套件記得以管理者的權限開啟終端機視窗在命令列鍵入的指令為
pip install opencv-python
2) 本程式碼所在目錄夾另建opencvData子目錄以容納輸出的圖像檔案
'''
import cv2 #引入OpenCV (computer vision)影像處理的相關套件
from datetime import datetime #引入讀取機器時間相關套件
cap = cv2.VideoCapture(0) #選擇攝像鏡頭同學把括弧內數字設成0或1試試看效果
i = 0
while True:
ret, frame = cap.read() #從攝像鏡頭讀取一幀影像若讀取成功ret將紀錄True(若失敗ret將紀錄False)
cv2.imshow("frame",frame) #顯示影像
if cv2.waitKey(1) & 0xFF in (27,81,113): break #每隔1毫秒偵測是否有按鍵若有則讀取最末位元組內容比對是否為<Esc>、'q'或'Q'(ASCII碼分別為27,81,113),倘符合,則退出迴圈
i += 1
if (i%40 == 0): #每40幀影像存檔一次
i = 0 #重設i避免持續增加i值造成溢位(overflow)
cv2.imwrite("./opencvData/img-%s.jpg"%datetime.now().strftime("%H-%M-%S"),frame) #影像輸出為檔案儲存
#if (i%10 == 0): cv2.imwrite('./opencvData/image%d.jpg'%(i//10),frame) #影像輸出為檔案儲存
cap.release() #釋放攝像鏡頭所佔資源
cv2.destroyAllWindows() #關閉所有視窗