웹캠 영상을 모니터에서 확인하는 것은 잘 안된다.. 향후 성공하면 추가!
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()
'공부 > Python' 카테고리의 다른 글
[Python] 파이썬 패키지/라이브러리 버전 정보 확인하기 (0) | 2023.10.17 |
---|---|
[Python] 파이썬 여러 라이브러리 .txt 파일 이용하여 한번에 설치하기 (0) | 2023.09.06 |
[Python] 파이썬 라이브러리 splitfolders 사용하여 train/val/test 데이터 나누기 (0) | 2023.08.08 |
[Python/Matplotlib] 파이썬 plt 그래프 그리기 (0) | 2023.07.11 |
[Python/Pandas] csv 파일 판다스 데이터프레임으로 불러오기 / 내보내기 (0) | 2023.07.04 |