오늘은 파이썬에서 CNN을 활용하여 객체 탐지를 구현하는 방법에 대해 알아보겠습니다. 특히 YOLO와 Faster R-CNN 두 가지 방법을 중점적으로 살펴보겠습니다.
객체 탐지는 이미지나 비디오에서 특정 객체를 식별하고 그 위치를 찾아내는 기술입니다. 이는 자율주행차, 보안 시스템, 로봇 비전 등 다양한 분야에서 활용됩니다.
YOLO는 실시간 객체 탐지 시스템으로, 이미지를 한 번만 보고 객체를 탐지합니다. 빠른 속도와 높은 정확도로 유명합니다.
pip install tensorflow opencv-python
다음은 YOLO를 사용하여 객체를 탐지하는 기본 코드입니다:
import cv2
import numpy as np
# YOLO 모델 및 구성 파일 경로
yolo_net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
layer_names = yolo_net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in yolo_net.getUnconnectedOutLayers()]
# 이미지 읽기
img = cv2.imread("image.jpg")
height, width, _ = img.shape
# 이미지 전처리
blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
yolo_net.setInput(blob)
outs = yolo_net.forward(output_layers)
# 결과 처리
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
# 객체의 경계 상자 그리기
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
cv2.rectangle(img, (center_x - w // 2, center_y - h // 2), (center_x + w // 2, center_y + h // 2), (0, 255, 0), 2)
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
위 코드를 실행하면 이미지에서 객체가 탐지되어 경계 상자가 그려집니다.
Faster R-CNN은 영역 제안 네트워크(RPN)를 사용하여 객체를 탐지하는 속도와 정확도를 높인 CNN 기반 모델입니다.
pip install torch torchvision
Faster R-CNN을 사용한 코드 예시는 다음과 같습니다:
import torch
from torchvision.models.detection import fasterrcnn_resnet50_fpn
from torchvision.transforms import functional as F
# 모델 초기화
model = fasterrcnn_resnet50_fpn(pretrained=True)
model.eval()
# 이미지 읽기
img = Image.open("image.jpg")
img_tensor = F.to_tensor(img)
# 객체 탐지
with torch.no_grad():
prediction = model([img_tensor])
# 결과 처리
for element in prediction[0]['boxes']:
x1, y1, x2, y2 = element
cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (255, 0, 0), 2)
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
이 코드는 Faster R-CNN을 사용하여 이미지에서 객체를 탐지하고 경계 상자를 그립니다.