[파이썬] 딥러닝을 활용한 실시간 객체 추적

object_tracking

딥러닝은 최신 기술이며 컴퓨터 비전 분야에서 다양한 응용 프로그램에 활용됩니다. 이 중에서도 객체 추적은 매우 중요한 작업으로, 실시간으로 동작하는 시스템에 많이 사용됩니다. 객체 추적은 주어진 이미지 또는 비디오에서 움직이는 객체를 검출하고, 추적해줌으로써 활용됩니다.

이번 기술 블로그에서는 Python과 딥러닝 라이브러리인 OpenCV를 사용하여 실시간 객체 추적을 구현하는 방법을 알아보겠습니다.

요구 사항

코드 구현

먼저 필요한 라이브러리를 설치합니다.

pip install opencv-python
pip install opencv-contrib-python

다음은 실시간 객체 추적을 위한 코드입니다.

import cv2

def main():
    # 객체 분류 라벨
    labels = [
        'background', 'aeroplane', 'bicycle', 'bird', 'boat',
        'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable',
        'dog', 'horse', 'motorbike', 'person', 'pottedplant',
        'sheep', 'sofa', 'train', 'tvmonitor'
    ]

    # 딥러닝 모델 로드
    net = cv2.dnn.readNetFromCaffe('models/MobileNetSSD_deploy.prototxt',
                                   'models/MobileNetSSD_deploy.caffemodel')

    # 웹카메라 캡처
    cap = cv2.VideoCapture(0)

    while True:
        ret, frame = cap.read()

        # 프레임 크기 조절 및 전처리
        frame_resized = cv2.resize(frame, (300, 300))
        blob = cv2.dnn.blobFromImage(frame_resized, 0.007843, (300, 300), 127.5)

        # 객체 추적
        net.setInput(blob)
        detections = net.forward()

        for i in range(detections.shape[2]):
            confidence = detections[0, 0, i, 2]

            # 신뢰도 설정
            if confidence > 0.5:
                class_id = int(detections[0, 0, i, 1])

                # 객체 위치 추출
                x = int(detections[0, 0, i, 3] * frame.shape[1])
                y = int(detections[0, 0, i, 4] * frame.shape[0])
                w = int(detections[0, 0, i, 5] * frame.shape[1])
                h = int(detections[0, 0, i, 6] * frame.shape[0])

                # 객체 그리기
                cv2.rectangle(frame, (x, y), (w, h), (255, 0, 0), 2)
                cv2.putText(frame, labels[class_id], (x, y + 30),
                            cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)

        # 영상 출력
        cv2.imshow('Real-time Object Detection', frame)

        # 종료 조건
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # 메모리 해제
    cap.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()

실행

위의 코드를 실행하면 웹캠이 실행되며, 웹캠으로부터 실시간으로 들어오는 영상에서 객체를 추적하고 사각형으로 표시해줍니다. 추적하고자 하는 객체의 클래스를 수정하여 원하는 결과를 얻을 수 있습니다.

이제 딥러닝을 활용한 실시간 객체 추적을 구현하는 방법을 알게 되었습니다. 이를 응용하여 자율주행, 보안 시스템 등 다양한 분야에서 활용할 수 있습니다. 딥러닝은 계속해서 발전하고 있으며, 보다 정확하고 효율적인 객체 추적 기술을 개발하기 위한 연구도 지속적으로 진행되고 있습니다.