이미지나 비디오에서 관심 있는 객체를 탐지하는 것이 목표인 컴퓨터 비전 작업입니다. 단순히 강아지나 고양이를 분리하는 것이 아닌, 개체의 위치와 경계를 식별하고 다양한 범주로 분류하는 작업이 포함됩니다. 이는 이미지 분류(Image Classification) 및 검색(Image Retrieval)과 함께 비전 인식의 중요한 기술을 구성합니다.
최신 방법으로 두 가지 주요 유형으로 분류하고 있습니다.
YOLO : You Only Look Once는 이름 그대로 이미지를 한 번만 보고 물체를 검출하는 딥러닝 기술을 이용한 Object Detection 모델입니다. 이전의 모델들은 이미지를 여러 번에 걸쳐 확인하며 동작하였기 때문에 시간이 많이 소요되어 실시간 검출이 필요한 경우에 사용할 수 없는 기술이었습니다.
YOLO의 딥러닝 기술에 대해서는 제가 모르는 부분이 많기 때문에, 따로 공부하는 것으로 하고.. 오늘은 모델을 활용해 간단하게 인공지능 CCTV를 만들어 보겠습니다.
OpenCV : Open Source Computer Vision의 약자로, 영상 처리에 사용할 수 있는 오픈 소스 라이브러리입니다. 오늘은 고급 기능은 사용하지 않고, 컴퓨터에 연결된 카메라의 영상을 편하게 사용할 수 있도록 VideoCapture기능만 사용하려고 합니다.
Device : Macbook Pro M1, 2020
위에서 설명한 OpenCV를 설치하고 카메라 영상을 불러와 그대로 출력합니다.
카메라 인덱스는 환경에 따라 다를 수 있어 확인이 요구됩니다.
pip install opencv-python
import cv2
cam_index = 0
cap = cv2.VideoCapture(cam_index)
while True:
ret, frame = cap.read()
if not ret:
print('Cam Error')
break
cv2.imshow('frame', frame)
if cv2.waitKey(1) == ord('q'):
break
pip install ultralytics
from ultralytics import YOLO
model = YOLO('yolov8n.pt')
detection = model(frame)[0]
detection 변수 안에 탐색된 객체의 종류와, 위치가 있습니다.
detection = model(frame)[0]
for data in detection.boxes.data.tolist():
confidence = float(data[4])
if confidence < CONFIDENCE_THRESHOLD:
continue
xmin, ymin, xmax, ymax = int(data[0]), int(data[1]), int(data[2]), int(data[3])
label = int(data[5])
cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), GREEN, 2)
cv2.putText(frame, class_list[label]+' '+str(round(confidence, 2))+'%', (xmin, ymin), cv2.FONT_ITALIC, 1, WHITE, 2)
cv2.rectange 통해 bounding box를 그리고, cv2.putText를 통해 개체의 종류와 확률(confidence)를 그려줍니다.
import cv2
from ultralytics import YOLO
CONFIDENCE_THRESHOLD = 0.7
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
with open('coco128.txt', 'r', encoding='utf8') as coco128:
data = coco128.read()
class_list = data.split('\n')
while True:
ret, frame = cap.read()
if not ret:
print('Cam Error')
break
model = YOLO('yolov8n.pt')
detection = model(frame)[0]
for data in detection.boxes.data.tolist():
confidence = float(data[4])
if confidence < CONFIDENCE_THRESHOLD:
continue
xmin, ymin, xmax, ymax = int(data[0]), int(data[1]), int(data[2]), int(data[3])
label = int(data[5])
cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), GREEN, 2)
cv2.putText(frame, class_list[label]+' '+str(round(confidence, 2))+'%', (xmin, ymin), cv2.FONT_ITALIC, 1, WHITE, 2)
cv2.imshow('frame', frame)
if cv2.waitKey(1) == ord('q'):
break
Class list (coco128.txt)
person
bicycle
car
motorcycle
airplane
bus
train
truck
boat
traffic light
fire hydrant
stop sign
parking meter
bench
bird
cat
dog
horse
sheep
cow
elephant
bear
zebra
giraffe
backpack
umbrella
handbag
tie
suitcase
frisbee
skis
snowboard
sports ball
kite
baseball bat
baseball glove
skateboard
surfboard
tennis racket
bottle
wine glass
cup
fork
knife
spoon
bowl
banana
apple
sandwich
orange
broccoli
carrot
hot dog
pizza
donut
cake
chair
couch
potted plant
bed
dining table
toilet
tv
laptop
mouse
remote
keyboard
cell phone
microwave
oven
toaster
sink
refrigerator
book
clock
vase
scissors
teddy bear
hair drier
toothbrush

간단한 코드로 괜찮은 성능을 가진 지능형 CCTV를 만들었습니다. 사실 Object Detection만으로는 기능이 조금 부족하고, 설정한 시간대에 사람이 감지되면 이벤트와 캡처된 비디오를 전달하는 등, 추가적인 기능을 붙여보면 어떨까 합니다. 라즈베리파이 하나 구매해 직접만은 지능형 CCTV를 자취하는 친구들에게 선물하면 어떨까요?