メニュー 閉じる

151. PythonのOpenCVを使ってウェブカメラの顔認証してみる

みんな大好きキアヌ。

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier ('haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier ('haarcascades/haarcascade_eye.xml')

cap = cv2.VideoCapture (0)

frame_count = 0

rec_flag = False

while (1):

	ret, frame = cap.read ()

	if ret == True:

		frame_count += 1

		frame = cv2.resize (frame, (int(frame.shape[1] / 4), int(frame.shape[0] / 4)))

		gray = cv2.cvtColor (frame, cv2.COLOR_BGR2GRAY)

		faces = face_cascade.detectMultiScale (gray)

		for (x, y, w, h) in faces:
			frame = cv2.rectangle (frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
			roi_gray = gray[y:y + h, x:x + w]
			roi_color = frame[y:y + h, x:x + w]
			eyes = eye_cascade.detectMultiScale (roi_gray)
			for (ex, ey, ew, eh) in eyes:
				cv2.rectangle (roi_color, (ex,ey), (ex + ew, ey + eh), (0, 255, 0), 2)

		cv2.imshow ('Face Detection', frame)

		if rec_flag == True:
			cv2.imwrite('movie/' + str (frame_count) + '.png', frame)

		k = cv2.waitKey (1)

		if k == ord ('q'):
			break
		if k == ord ('r'):
			rec_flag = True
	else:
		break

	print (faces)


cap.release ()
cv2.destroyAllWindows ()

Posted in python