Python OpenCV

OpenCV YOLO 및 Haar Cascade를 활용한 객체 검출

PyExplorer 2025. 3. 12. 09:26
728x90

YOLO 및 Haar Cascade를 활용한 객체 검출

1. 개요

객체 검출(Object Detection)은 이미지 또는 영상에서 특정 객체를 찾아내는 기술로, 다양한 분야에서 활용됩니다. OpenCV를 사용하면 간단하게 객체 검출을 구현할 수 있으며, 이번 포스팅에서는 YOLO(You Only Look Once)Haar Cascade를 활용하여 객체 검출을 수행하는 방법을 설명하겠습니다.

YOLO는 실시간 객체 탐지에 적합한 딥러닝 기반 알고리즘이며, Haar Cascade는 비교적 가벼운 연산을 통해 특정 패턴을 감지하는 방식입니다. 각각의 특징과 사용법을 예제 코드와 함께 알아보겠습니다.

2. Haar Cascade를 이용한 객체 검출

2.1 Haar Cascade란?

Haar Cascade는 OpenCV에서 제공하는 전통적인 객체 검출 방법으로, 사전 학습된 XML 파일을 활용하여 얼굴, 눈, 자동차 등의 객체를 탐지할 수 있습니다.

이 방법은 비교적 빠르지만 정확도가 딥러닝 기반 모델(YOLO, SSD 등)에 비해 낮을 수 있습니다. 하지만 특정 객체(예: 얼굴) 검출에는 여전히 유용하게 사용됩니다.

2.2 Haar Cascade를 이용한 얼굴 검출 예제

import cv2

def detect_faces(image_path, cascade_path):
    # Haar Cascade 모델 불러오기
    face_cascade = cv2.CascadeClassifier(cascade_path)

    # 이미지 읽기
    img = cv2.imread(image_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 얼굴 검출
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

    # 검출된 얼굴 주변에 사각형 표시
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)

    # 결과 출력
    cv2.imshow('Face Detection', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# 실행 예제
cascade_path = 'haarcascade_frontalface_default.xml'
image_path = 'face.jpg'
detect_faces(image_path, cascade_path)

2.3 코드 설명

  • CascadeClassifier를 이용해 Haar Cascade 모델을 로드합니다.
  • 이미지를 흑백(gray)으로 변환하여 검출 성능을 향상시킵니다.
  • detectMultiScale() 메서드를 사용해 얼굴을 검출합니다.
  • 검출된 얼굴 영역을 cv2.rectangle()을 이용해 시각화합니다.

3. YOLO를 이용한 객체 검출

3.1 YOLO란?

YOLO(You Only Look Once)는 CNN(Convolutional Neural Network)을 활용한 객체 탐지 모델로, 한 번의 신경망 연산만으로 객체 위치와 클래스 정보를 동시에 예측할 수 있습니다. YOLO는 빠르고 정확한 탐지 능력을 갖추고 있어 실시간 객체 검출에 자주 사용됩니다.

YOLO 모델은 OpenCV에서 cv2.dnn 모듈을 이용하여 쉽게 사용할 수 있습니다.

3.2 YOLO 모델 다운로드

YOLO를 실행하기 위해 사전 학습된 가중치 파일과 설정 파일이 필요합니다. OpenCV에서 사용할 YOLO 파일은 아래에서 다운로드할 수 있습니다.

위 파일들을 같은 폴더에 저장한 후 아래 코드를 실행하면 YOLO를 이용한 객체 검출을 수행할 수 있습니다.

3.3 YOLO를 이용한 객체 검출 코드

import cv2
import numpy as np

def load_yolo():
    net = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg')
    layer_names = net.getLayerNames()
    output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
    return net, output_layers

def detect_objects(image_path):
    net, output_layers = load_yolo()
    classes = [line.strip() for line in open('coco.names')]

    # 이미지 로드
    img = cv2.imread(image_path)
    height, width, channels = img.shape

    # YOLO 입력 설정
    blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), swapRB=True, crop=False)
    net.setInput(blob)

    # 객체 탐지 수행
    detections = net.forward(output_layers)

    # 검출 결과 처리
    for output in detections:
        for detection in output:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > 0.5:
                center_x, center_y, w, h = (detection[:4] * [width, height, width, height]).astype(int)
                x, y = center_x - w // 2, center_y - h // 2
                cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
                cv2.putText(img, classes[class_id], (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

    # 결과 출력
    cv2.imshow('YOLO Object Detection', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# 실행 예제
image_path = 'example.jpg'
detect_objects(image_path)

3.4 코드 설명

  • cv2.dnn.readNet()을 이용해 YOLO 모델을 불러옵니다.
  • blobFromImage()를 사용해 이미지를 YOLO 모델 입력 형태로 변환합니다.
  • net.forward()를 통해 객체 탐지를 수행한 후, 감지된 객체에 대해 bounding box를 그립니다.

4. 결론

이번 포스팅에서는 OpenCV를 활용한 객체 검출 기법으로 Haar Cascade와 YOLO를 비교하며 살펴보았습니다. Haar Cascade는 특정 객체(예: 얼굴) 탐지에 효과적이며, YOLO는 다양한 객체를 빠르고 정확하게 탐지할 수 있습니다. 각각의 장점을 이해하고, 적절한 상황에서 활용하는 것이 중요합니다.