65 lines
2.3 KiB
Python
65 lines
2.3 KiB
Python
|
'''
|
|||
|
Program: MT_imgWatermark.py (Report comments/bugs to chikh@yuntech.edu.tw)
|
|||
|
Function:
|
|||
|
'''
|
|||
|
|
|||
|
import cv2 #引入OpenCV影像處理的相關套件
|
|||
|
from datetime import datetime #引入讀取機器時間相關套件
|
|||
|
import threading #引入多執行緒相關套件
|
|||
|
import time #for time.sleep()
|
|||
|
|
|||
|
threadList, imgList = [], []
|
|||
|
sem = threading.Semaphore(1)
|
|||
|
|
|||
|
#----- 設定要添加的文字:開始 -----#
|
|||
|
position = (10,40) #文字左下角的座標
|
|||
|
font = cv2.FONT_HERSHEY_COMPLEX
|
|||
|
fontScale = 0.5 #指定文字大小的比例
|
|||
|
color = (0,255,0) #以RGB三原色設定綠色文字;RGB色表可見 https://bit.ly/2ymSOJF
|
|||
|
thickness = 1 #文字的線寬
|
|||
|
#----- 設定要添加的文字:結束 -----#
|
|||
|
|
|||
|
def camCapture(ID):
|
|||
|
global imgList
|
|||
|
cap = cv2.VideoCapture(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)
|
|||
|
sem.acquire()
|
|||
|
imgList.append((ID,datetime.now().strftime("%H-%M-%S"),frame))
|
|||
|
cv2.imwrite('./opencvData/[%d] img-%s.jpg'%(imgList[-1][0],imgList[-1][1]),frame) #影像輸出為檔案儲存
|
|||
|
sem.release()
|
|||
|
cap.release() #釋放攝像頭設備
|
|||
|
|
|||
|
def procImage():
|
|||
|
global imgList
|
|||
|
while True:
|
|||
|
sem.acquire()
|
|||
|
if len(imgList) > 0:
|
|||
|
img = imgList[0][2]
|
|||
|
text = "Cam%d-%s"%(imgList[0][0],imgList[0][1])
|
|||
|
cv2.putText(img,text,position,font,fontScale,color,thickness) #在影像上添加文字
|
|||
|
cv2.imshow('Camera%d'%imgList[0][0],img) #顯示影像
|
|||
|
cv2.imwrite('./opencvData/Cam%d-%s.jpg'%(imgList[0][0],imgList[0][1]),img)
|
|||
|
imgList.pop(0)
|
|||
|
sem.release()
|
|||
|
if cv2.waitKey(1) & 0xFF in (27,81,113): break
|
|||
|
time.sleep(0.1)
|
|||
|
|
|||
|
for i in range(2):
|
|||
|
threadList.append(threading.Thread(target=camCapture,args=(i,)))
|
|||
|
threadList[i].start()
|
|||
|
|
|||
|
threadList.append(threading.Thread(target=procImage))
|
|||
|
threadList[-1].start()
|
|||
|
|
|||
|
for i in range(3):
|
|||
|
threadList[i].join() #wait for the thread specified by threadList[i] to terminate
|
|||
|
|
|||
|
cv2.destroyAllWindows() #關閉所有視窗
|