1. 程式人生 > >Python拍照加時間戳水印

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'):
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-80, 5),'100',font=myfont,fill=fillcolor)
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)