1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| import numpy as np import cv2 import time import datetime from PIL import Image
cap = cv2.VideoCapture(0)
''' 人脸识别 ''' def getface(img): face_cascade = cv2.CascadeClassifier( 'C:/ProgramData/Anaconda3/envs/pra/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier( 'C:/ProgramData/Anaconda3/envs/pra/Lib/site-packages/cv2/data/haarcascade_eye.xml') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) img = christmas(img, x, y, w, h) return img
def christmas(img, x, y, w, h): im = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) mark = Image.open("hat/111.png") height = int(w * 987 / 1024) mark = mark.resize((w, height)) layer = Image.new('RGBA', im.size, (0, 0, 0, 0)) layer.paste(mark, (x, y - height + 100)) out = Image.composite(layer, im, layer) img = cv2.cvtColor(np.asarray(out), cv2.COLOR_RGB2BGR) return img
videoWriter = cv2.VideoWriter('testwrite.avi', cv2.VideoWriter_fourcc(*'MJPG'), 15, (1000, 563))
while (cap.isOpened()): ret, frame = cap.read() if ret == True: img = cv2.resize(frame, (1000, 563))
img = getface(img) cv2.imshow('frame', img) videoWriter.write(img) if cv2.waitKey(10) & 0xFF == ord('q'): print("退出视频") break else: break
cap.release() videoWriter.release() cv2.destroyAllWindows()
|