Python拍照加时间戳水印

本程序实现通过笔记本摄像头拍照,然后在照片的右下角处加入时间戳的水印,分为2个函数分别实现拍照和加时间戳水印。
用的时候自己先把需要的库都安装了,以下代码在Win7、Python3.6里调试通过

__author__ = 'Yue Qingxuan'
# -*- coding: utf-8 -*-
import cv2
import time
import os
from PIL import Image, ImageDraw, ImageFont

def 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)