웹캠의 영상으로 부터 얼굴을 검출하여 얼굴 주변에 박스 출력하기

 

 

 

 

import cv2
import timeit

def exec_face_detect_from_webcam():
    # 모델 불러오기
    cascade = cv2.CascadeClassifier('[학습모델경로]')

    video_capture = cv2.VideoCapture(0)

    # 창 생성
    cv2.namedWindow('Video', cv2.WINDOW_NORMAL)
    # 창 크기 설정
    cv2.resizeWindow('Video', 800, 600)

    frame_count = 0
    start_time = timeit.default_timer()

    while True:
        # Grab a single frame of video
        status, frame = video_capture.read()

        if not status:
            break

        # 좌우 반전
        frame = cv2.flip(frame, 1)

        # 영상 압축
        frame = cv2.resize(frame, dsize=None, fx=1.0, fy=1.0)
        # 그레이 스케일 변환
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        # cascade 얼굴 탐지 알고리즘
        results = cascade.detectMultiScale(gray,  # 입력 이미지
                                           scaleFactor=1.1,  # 이미지 피라미드 스케일 factor
                                           minNeighbors=5,  # 인접 객체 최소 거리 픽셀
                                           minSize=(20, 20)  # 탐지 객체 최소 크기
                                           )

        for box in results:
            x, y, w, h = box
            cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 255, 255), thickness=2)

            fps = frame_count / (timeit.default_timer() - start_time)
            fps_text = 'FPS: {:.2f}'.format(fps)
            cv2.putText(frame, fps_text, (x, y - 5 ), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2)

        frame_count += 1

        # Display the resulting image
        cv2.imshow('Video', frame)

        # Hit 'q' on the keyboard to quit!
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # Release handle to the webcam
    video_capture.release()
    cv2.destroyAllWindows()


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    exec_face_detect_from_webcam()