Yolo(You only look once)
17 Aug 2020Yolo(You only look once)
프레임워크는 open cv2 사용
import cv2
import numpy as np
import matplotlib.pyplot as plt
print(cv2.__version__)
BLOBSIZE = 416
CONFIDENCE = 0.4
# https://pjreddie.com/darknet/yolo/ 320 다운
net = cv2.dnn.readNet("yolo/yolov3.weights", "yolo/yolov3.cfg")
classes = []
# 80개의 이름 클래스 [person, bicycle...]
with open("yolo/coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
colors = np.random.uniform(0, 255, size=(len(classes), 3))
img = cv2.imread("yolo/myImage.jpg")
img = cv2.resize(img, None, fx=0.4, fy=0.4)
height, width, channels = img.shape
blob = cv2.dnn.blobFromImage(img, 0.00392, (BLOBSIZE, BLOBSIZE), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > CONFIDENCE:# 신뢰도 체크
# Object detected
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
# Rectangle coordinates
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.1, 0.4) # 같은물체에 대한 박스 제거
font = cv2.FONT_HERSHEY_PLAIN
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
color = colors[i]
cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
cv2.putText(img, label, (x, y - 10), font, 1, color, 2)
print(label, confidences[i], x, y, w, h)
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()