
목차 ▽열기
1. 개요
Object Detection(객체 탐지)은 이미지에서 객체를 식별하고, 위치를 파악하는 컴퓨터 비전 기술입니다.
이 글에서는 Hugging Face의 transformers 라이브러리의 pipeline을 활용하여
도로 이미지 속 자동차, 신호등, 보행자 등을 감지하는 방법을 자세히 살펴보겠습니다.
주요 내용
- transformers의 pipeline을 이용한 Object Detection
- matplotlib를 활용한 객체 시각화
- 모델의 결과 해석 및 Fine-Tuning 확장
2. Object Detection이란?
Object Detection(객체 탐지)은 이미지 속에서 특정 물체가 어디에 위치하는지 박스로 표시하고,
해당 객체가 무엇인지 분류하는 기술입니다.
Object Detection의 주요 개념
- Classification (분류): 이미지에 특정 객체가 포함되어 있는지 예측
- Localization (위치 탐색): 이미지 내 객체의 위치를 Bounding Box로 표시
- Detection (탐지): 이미지 속 여러 개의 객체를 동시에 탐색
활용 예시
- 자율주행 차량 - 보행자, 차량, 신호등 탐지
- CCTV 영상 분석 - 침입 탐지, 교통량 분석
- 스포츠 경기 분석 - 선수 위치 및 공의 이동 경로 분석
3. Object Detection 코드 구현
이제 Python을 사용하여 Object Detection 모델을 실행하고,
도로 사진 속 객체들을 감지하는 과정을 살펴보겠습니다.
3-1. pipeline을 활용한 모델 실행
Hugging Face의 transformers 라이브러리는 다양한 AI 모델을 손쉽게 활용할 수 있도록 pipeline을 제공합니다.
먼저, pipeline("object-detection")을 사용하여 Object Detection 모델을 로드합니다.
from transformers import pipeline
# 객체 탐지(Object Detection) 모델 로드
model = pipeline("object-detection")
# 분석할 이미지 파일 (도로 사진)
image_path = '도로사진.jpg'
# 모델을 사용하여 객체 탐지 수행
result = model(image_path)
# 탐지된 객체 리스트 출력
print(result)
출력
[{'score': 0.8258874416351318,
'label': 'truck',
'box': {'xmin': 475, 'ymin': 194, 'xmax': 516, 'ymax': 221}},
{'score': 0.9929500818252563,
'label': 'car',
'box': {'xmin': 153, 'ymin': 468, 'xmax': 321, 'ymax': 625}},
{'score': 0.937700092792511,
'label': 'traffic light',
'box': {'xmin': 529, 'ymin': 163, 'xmax': 557, 'ymax': 186}},
{'score': 0.9528058767318726,
'label': 'truck',
'box': {'xmin': 421, 'ymin': 201, 'xmax': 455, 'ymax': 232}},
{'score': 0.9967544674873352,
'label': 'traffic light',
'box': {'xmin': 350, 'ymin': 295, 'xmax': 571, 'ymax': 357}},
{'score': 0.9984515905380249,
'label': 'traffic light',
'box': {'xmin': 782, 'ymin': 296, 'xmax': 1018, 'ymax': 363}},
{'score': 0.7857056260108948,
'label': 'car',
'box': {'xmin': 762, 'ymin': 294, 'xmax': 786, 'ymax': 317}},
{'score': 0.9964152574539185,
'label': 'motorcycle',
'box': {'xmin': 663, 'ymin': 500, 'xmax': 730, 'ymax': 587}},
{'score': 0.9896963834762573,
'label': 'car',
'box': {'xmin': 550, 'ymin': 192, 'xmax': 581, 'ymax': 215}},
{'score': 0.6902872920036316,
'label': 'car',
'box': {'xmin': 429, 'ymin': 196, 'xmax': 452, 'ymax': 211}},
{'score': 0.9012615084648132,
'label': 'car',
'box': {'xmin': 423, 'ymin': 202, 'xmax': 454, 'ymax': 232}},
{'score': 0.9920904636383057,
'label': 'car',
'box': {'xmin': 270, 'ymin': 214, 'xmax': 309, 'ymax': 241}},
{'score': 0.9286350011825562,
'label': 'car',
'box': {'xmin': 319, 'ymin': 296, 'xmax': 351, 'ymax': 344}},
{'score': 0.7509833574295044,
'label': 'car',
'box': {'xmin': 476, 'ymin': 194, 'xmax': 515, 'ymax': 220}},
{'score': 0.990738570690155,
'label': 'traffic light',
'box': {'xmin': 0, 'ymin': 292, 'xmax': 137, 'ymax': 357}},
{'score': 0.9046427011489868,
'label': 'car',
'box': {'xmin': 394, 'ymin': 203, 'xmax': 430, 'ymax': 225}},
{'score': 0.9982653260231018,
'label': 'traffic light',
'box': {'xmin': 654, 'ymin': 160, 'xmax': 747, 'ymax': 187}},
{'score': 0.938798725605011,
'label': 'car',
'box': {'xmin': 149, 'ymin': 347, 'xmax': 189, 'ymax': 416}},
{'score': 0.9560864567756653,
'label': 'truck',
'box': {'xmin': 248, 'ymin': 344, 'xmax': 351, 'ymax': 434}},
{'score': 0.7842751145362854,
'label': 'car',
'box': {'xmin': 499, 'ymin': 227, 'xmax': 540, 'ymax': 264}},
{'score': 0.9875442981719971,
'label': 'car',
'box': {'xmin': 248, 'ymin': 344, 'xmax': 348, 'ymax': 433}},
{'score': 0.7373068332672119,
'label': 'traffic light',
'box': {'xmin': 34, 'ymin': 201, 'xmax': 42, 'ymax': 218}},
{'score': 0.9899991154670715,
'label': 'car',
'box': {'xmin': 37, 'ymin': 347, 'xmax': 157, 'ymax': 454}},
{'score': 0.9827091693878174,
'label': 'car',
'box': {'xmin': 331, 'ymin': 215, 'xmax': 364, 'ymax': 241}},
{'score': 0.6544694900512695,
'label': 'truck',
'box': {'xmin': 393, 'ymin': 203, 'xmax': 433, 'ymax': 227}},
{'score': 0.5787176489830017,
'label': 'motorcycle',
'box': {'xmin': 680, 'ymin': 526, 'xmax': 728, 'ymax': 587}},
{'score': 0.874998152256012,
'label': 'truck',
'box': {'xmin': 498, 'ymin': 226, 'xmax': 541, 'ymax': 266}},
{'score': 0.9974609613418579,
'label': 'car',
'box': {'xmin': 412, 'ymin': 402, 'xmax': 528, 'ymax': 505}},
{'score': 0.998721182346344,
'label': 'person',
'box': {'xmin': 663, 'ymin': 467, 'xmax': 724, 'ymax': 549}}]
위 결과에서 모델이 **자동차(car), 보행자(person), 신호등(traffic light)**을 인식했음을 확인할 수 있습니다.
3-2. 탐지된 객체를 이미지에 시각화
탐지된 객체를 보기 쉽게 Bounding Box(경계 상자)와 라벨을 추가하여 시각화하겠습니다.
코드 구현
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# 이미지 불러오기
image = plt.imread(image_path)
# Matplotlib을 사용하여 이미지 출력
fig, ax = plt.subplots(1, figsize=(10, 6))
ax.imshow(image)
# 탐지된 객체에 Bounding Box 추가
for data in result:
xmin = int(data['box']['xmin'])
ymin = int(data['box']['ymin'])
xmax = int(data['box']['xmax'])
ymax = int(data['box']['ymax'])
# Bounding Box 그리기
width = xmax - xmin
height = ymax - ymin
rect = patches.Rectangle((xmin, ymin), width, height, linewidth=2, edgecolor='red', facecolor='none')
ax.add_patch(rect)
# 객체 라벨 표시
label = data['label']
confidence = data['score']
text = f"{label}: {confidence:.2f}"
ax.text(xmin, ymin, text, fontsize=10, color='yellow', bbox=dict(facecolor='black', alpha=0.5))
# 시각화 출력
plt.axis("off")
plt.show()
출력

코드 설명
- plt.imread(image_path) → 이미지를 불러옵니다.
- matplotlib.patches.Rectangle() → Bounding Box(경계 상자)를 추가합니다.
- ax.text() → 객체 라벨(이름)과 신뢰도(확률)를 표시합니다.
- 결과 이미지 예시
- 신호등, 자동차, 보행자가 감지된 도로 사진
4. Fine-Tuning: 모델 개선하기
위에서 사용한 모델은 사전 학습된 모델이므로, 특정 도로 환경(예: 한국 도로 표지판)에 맞춰져 있지 않을 수 있습니다.
따라서 우리 데이터로 Fine-Tuning을 진행하여 모델 성능을 향상시킬 수 있습니다.
4-1. 데이터셋 준비
Fine-Tuning을 위해 도로 이미지를 포함한 Custom Dataset을 준비해야 합니다.
- COCO Dataset: 교통량 분석에 유용한 데이터셋
- Roboflow Dataset: 커스텀 데이터셋 제작 가능
예제 데이터셋 구조
/data
├── train/
│ ├── image_1.jpg
│ ├── image_2.jpg
│ ├── ...
│ ├── labels/
│ │ ├── image_1.json
│ │ ├── image_2.json
│ │ ├── ...
├── test/
├── val/
- labels/ 폴더에는 이미지에 대한 객체 정보(라벨, Bounding Box)가 포함된 .json 파일 저장.
5. 결론 및 요약
이 글에서는 Hugging Face pipeline을 활용한 Object Detection을 수행하고,
도로 사진에서 자동차, 신호등, 보행자를 감지하는 방법을 설명했습니다.
핵심 요약
- pipeline("object-detection")을 활용하여 도로 이미지 속 객체 탐지
- matplotlib을 사용하여 탐지된 객체를 이미지에 시각화
- Fine-Tuning을 통해 한국 도로 환경에 최적화된 모델 구축
Fine-Tuning된 모델을 배포하면 자율주행, 교통 감시, 사고 감지 시스템 등에 활용할 수 있습니다.
'Streamlit > 이론' 카테고리의 다른 글
184. [Streamlit] requirements.txt 생성 및 설치 방법 (0) | 2025.03.30 |
---|---|
155. [Streamlit] [Anaconda] : Streamlit 설치시 필수 및 추천 라이브러리 (1) | 2025.02.19 |
147. [Python] [Streamlit] : Streamlit에서 한글 폰트 설정하기 (Mac, Windows, Linux) (0) | 2025.02.04 |
145. [Python] [Streamlit] : Streamlit(스트림릿) 차트 그리기(2) (0) | 2025.02.04 |
144. [Python] [Streamlit] : Streamlit(스트림릿) 차트 그리기(1) (0) | 2025.02.04 |