本程序實現經過筆記本攝像頭拍照,而後在照片的右下角處加入時間戳的水印,分爲2個函數分別實現拍照和加時間戳水印。用的時候本身先把須要的庫都安裝了,如下代碼在Win七、Python3.6裏調試經過__author__ = 'Yue Qingxuan'# -*- coding: utf-8 -*-import cv2import timeimport osfrom PIL import Image, ImageDraw, ImageFontdef TakePhoto(path): cap = cv2.VideoCapture(0) while(1): # get a frame ret, frame = cap.read() # show a frame cv2.imshow("Capture", frame) if cv2.waitKey(1) & 0xFF == ord('q'): #按字母q退出 timestr=time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) filename=path+'/{0}.jpeg'.format(timestr) #取當前時間做爲照片的文件名 cv2.imwrite(filename, frame) add_watermark(filename) break cap.release() cv2.destroyAllWindows()def add_watermark(img_file): # 建立繪畫對象 image = Image.open(img_file) draw = ImageDraw.Draw(image) myfont = ImageFont.truetype('C:/windows/fonts/Arial.ttf',size=20) fillcolor = '#ff0000' #RGB紅色 timestr=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) #格式化時間 width,height = image.size # 參數一:位置(x軸,y軸);參數二:填寫內容;參數三:字體;參數四:顏色 draw.text((width - 200, height-35), timestr, font=myfont, fill=fillcolor) image.save(img_file)if __name__ == '__main__': path="E:/OpencvVideo" if os.path.exists(path)==False: os.makedirs(path) #若是不存在就新建一個目錄 TakePhoto(path)