[python] 파이썬을 사용한 객체 탐지 및 추적

이번 글에서는 파이썬을 사용하여 객체를 탐지하고 추적하는 방법에 대해 알아보겠습니다. 객체 탐지와 추적은 컴퓨터 비전의 중요한 주제로, 다양한 응용 프로그램에서 사용되고 있습니다. 이를 위해 OpenCV와 dlib 라이브러리를 사용하여 작업할 것입니다.

1. OpenCV 설치

먼저, 객체 탐지와 추적을 위해 OpenCV 라이브러리를 설치해야 합니다. 파이썬에서는 pip를 사용하여 쉽게 설치할 수 있습니다.

pip install opencv-python

2. dlib 설치

dlib는 영상 처리 및 기계 학습에 사용되는 라이브러리로, 얼굴 탐지 및 추적에 많이 사용됩니다. 다음 명령을 사용하여 dlib를 설치하세요.

pip install dlib

3. 객체 탐지

객체 탐지를 위해 먼저 이미지 또는 비디오에서 객체를 탐지해야 합니다. 이를 위해 먼저 OpenCV를 사용하여 이미지 또는 비디오를 읽어옵니다.

import cv2

# 이미지 또는 비디오 읽어오기
image = cv2.imread('image.jpg')
video = cv2.VideoCapture('video.mp4')

이미지 또는 비디오를 읽어온 후, 객체를 탐지하기 위해 사전 학습된 모델을 사용할 수 있습니다. 예를 들어, 사람을 탐지하기 위해 YOLOv3 모델을 사용할 수 있습니다.

# YOLOv3 모델 로드
net = cv2.dnn.readNetFromDarknet('yolov3.cfg', 'yolov3.weights')

# 클래스 이름 로드
with open('coco.names', 'r') as f:
    classes = f.read().splitlines()

로드한 모델과 클래스 이름을 사용하여 객체를 탐지합니다.

# 이미지나 비디오에서 객체 탐지
blob = cv2.dnn.blobFromImage(image, 1/255, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
output_layers = net.getUnconnectedOutLayersNames()
outputs = net.forward(output_layers)

# 각각의 객체에 대해 경계 상자 그리기
for detection in outputs:
    for detect in detection:
        scores = detect[5:]
        class_id = np.argmax(scores)
        confidence = scores[class_id]
        if confidence > 0.5:
            center_x = int(detect[0] * width)
            center_y = int(detect[1] * height)
            w = int(detect[2] * width)
            h = int(detect[3] * height)
            x = center_x - w/2
            y = center_y - h/2
            cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
            cv2.putText(image, classes[class_id], (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2)

4. 객체 추적

객체 추적은 탐지된 객체를 연속적으로 추적하는 작업입니다. dlib 라이브러리에서 제공하는 correlation_tracker를 사용하여 객체 추적을 할 수 있습니다.

import dlib

# 객체 추적을 위한 처음 프레임 설정
tracker = dlib.correlation_tracker()
tracker.start_track(image, dlib.rectangle(x, y, x+w, y+h))

# 프레임을 읽어오면서 객체 추적
while True:
    ret, frame = video.read()
    if not ret:
        break
    
    tracker.update(frame)
    pos = tracker.get_position()
    x, y, w, h = int(pos.left()), int(pos.top()), int(pos.width()), int(pos.height())
    
    cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
    cv2.putText(frame, 'Object', (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2)
    
    cv2.imshow('Object Tracking', frame)
    if cv2.waitKey(1) == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

이처럼 OpenCV와 dlib를 사용하여 객체 탐지와 추적을 할 수 있습니다. 객체 탐지와 추적은 컴퓨터 비전 기술의 핵심이므로, 다양한 응용 프로그램에서 유용하게 활용될 수 있습니다.

참고 자료: