import cv2

import os


# 비디오 파일 경로

video_path = 'C:/Users/HP/Downloads/Best of Russian Driving Fails 2019.mp4'


# 비디오 파일 로드

cap = cv2.VideoCapture(video_path)


# 사용자가 제공한 분류기 파일의 경로

cascade_file_path = 'C:/Users/HP/Downloads/haarcascade_car.xml'


# 분류기 파일의 경로가 존재하는지 확인

if not os.path.isfile(cascade_file_path):

    print("Error: Cascade classifier file not found.")

    exit()


# 차량 검출을 위한 OpenCV의 기본적인 Classifier 로드

car_cascade = cv2.CascadeClassifier(cascade_file_path)


if not cap.isOpened():

    print("Error: Could not open video.")

    exit()


# 비디오 파일의 각 프레임에서 객체를 검출하여 표시

while cap.isOpened():

    ret, frame = cap.read()

    if not ret:

        print("End of video.")

        break


    # 그레이스케일 변환

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


    # 차량 검출

    cars = car_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))


    # 차량 주위에 사각형 그리기

    for (x, y, w, h) in cars:

        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)


    # 결과 이미지 출력

    cv2.imshow('Vehicle Detection', frame)


    # 'q' 키를 누르면 종료

    if cv2.waitKey(1) & 0xFF == ord('q'):

        break


# 자원 해제

cap.release()

cv2.destroyAllWindows()



댓글(0) 먼댓글(0) 좋아요(0)
좋아요
공유하기 북마크하기찜하기