Oxygen Chrome

공부/Python

[Python] 웹캠으로 영상 입력받아 움직임 감지하기

aribae 2023. 8. 24. 13:57

웹캠 영상을 모니터에서 확인하는 것은 잘 안된다.. 향후 성공하면 추가!

import cv2

# 움직임을 감지하는 함수
def detect_motion(prev_frame, current_frame, threshold=1000):
    # 두 프레임 간의 차이 계산
    frame_delta = cv2.absdiff(prev_frame, current_frame)
    gray_frame = cv2.cvtColor(frame_delta, cv2.COLOR_BGR2GRAY)
    thresh = cv2.threshold(gray_frame, 25, 255, cv2.THRESH_BINARY)[1]
    
    # 이진화된 이미지에서 윤곽 찾기
    contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    motion_detected = False
    for contour in contours:
        if cv2.contourArea(contour) > threshold:
            motion_detected = True
            break
            
    return motion_detected

if __name__ == "__main__":
    # 웹캠 초기화
    cap = cv2.VideoCapture(0)
    
    # 첫 번째 프레임 읽기
    ret, prev_frame = cap.read()
    
    motion_started = False
    
    while True:
        # 현재 프레임 읽기
        ret, current_frame = cap.read()
        
        # 움직임 감지
        motion = detect_motion(prev_frame, current_frame)
        
        if motion and not motion_started:
            print("움직임 시작")
            motion_started = True
        elif not motion and motion_started:
            print("움직임 끝")
            motion_started = False
        
        prev_frame = current_frame.copy()
        
        # 'q' 키를 누르면 종료
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    # 웹캠 해제
    cap.release()
    cv2.destroyAllWindows()