⚙️ yolo-3
📌 기본 세팅
import numpy as np
import pandas as pd
import cv2
import matplotlib.pyplot as plt
import time
names = open("/content/coco.names").read()
names = names.strip().split("\n")
weight_path = "/content/yolov3.weights"
conf_path = "/content/yolov3.cfg"
yolo_model = cv2.dnn.readNetFromDarknet(conf_path, weight_path, )
layers = yolo_model.getLayerNames()
output_layers = [layers[i-1] for i in yolo_model.getUnconnectedOutLayers()]
📌 이미지 처리
# 주의사항
# OpenCV 기반으로 yolo-3을 사용할 경우, 이미지 크기를 32의 배수로 세팅해야 한다.
image = cv2.imread("/content/dog.png")
blob = cv2.dnn.blobFromImage(image, 1/255., (416,416), swapRB = True, crop=False)
📌 모델에 이미지 적용
yolo_model.setInput(blob)
output_sample = yolo_model.forward()
📌 기준 설정
# 유효성 판별 기준
pro_min = 0.5
# 클래스 판별 기준
threshold = 0.3
📌 객체 영역 구분하기
classes = []
confidence = []
boxes = []
Height = image.shape[0]
Width = image.shape[1]
for out in output_sample:
for res in out:
# 앞에 5개는 정보, 뒤에 6~85번째가 80개 클래스의 확률값
scores = res[5:]
class_current = np.argmax(scores)
confidence_current = scores[class_current]
# 가장 큰 확률값을 가지는 클래스의 유효성 체크
if confidence_current > 0.5:
box = res[0:4] * np.array([Width, Height, Width, Height])
x, y, w, h = box.astype("int")
x = int(x-(w/2))
y = int(y-(h/2))
boxes.append([x, y, int(w), int(h)])
confidence.append(float(confidence_current)) # 박스의 신뢰도
classes.append(class_current)
results = cv2.dnn.NMSBoxes(boxes, confidence, 0.5, 0.4)
📌 이미지에 객체 영역 표시하기
colorarea = np.random.randint(0, 255, size=(len(names), 3))
if len(results) > 0 :
for i in results:
x, y = boxes[i][0], boxes[i][1]
width, height = boxes[i][2], boxes[i][3]
colorarea_currnet = [int(j) for j in colorarea[ classes[i]]]
cv2.rectangle(image, (x,y), (x+width, y+height), colorarea_currnet, 5)
text_bar_current = "{}:{:.4f}".format(names[classes[i]], confidence[i])
cv2.putText(image, text_bar_current, (x+2, y+2), cv2.FONT_HERSHEY_DUPLEX, 0.5, (0,0,0))
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.show()

⚙️ yolo-3
📌 기본 세팅
import numpy as np
import pandas as pd
import cv2
import matplotlib.pyplot as plt
import time
names = open("/content/coco.names").read()
names = names.strip().split("\n")
weight_path = "/content/yolov3.weights"
conf_path = "/content/yolov3.cfg"
yolo_model = cv2.dnn.readNetFromDarknet(conf_path, weight_path, )
layers = yolo_model.getLayerNames()
output_layers = [layers[i-1] for i in yolo_model.getUnconnectedOutLayers()]
📌 이미지 처리
# 주의사항
# OpenCV 기반으로 yolo-3을 사용할 경우, 이미지 크기를 32의 배수로 세팅해야 한다.
image = cv2.imread("/content/dog.png")
blob = cv2.dnn.blobFromImage(image, 1/255., (416,416), swapRB = True, crop=False)
📌 모델에 이미지 적용
yolo_model.setInput(blob)
output_sample = yolo_model.forward()
📌 기준 설정
# 유효성 판별 기준
pro_min = 0.5
# 클래스 판별 기준
threshold = 0.3
📌 객체 영역 구분하기
classes = []
confidence = []
boxes = []
Height = image.shape[0]
Width = image.shape[1]
for out in output_sample:
for res in out:
# 앞에 5개는 정보, 뒤에 6~85번째가 80개 클래스의 확률값
scores = res[5:]
class_current = np.argmax(scores)
confidence_current = scores[class_current]
# 가장 큰 확률값을 가지는 클래스의 유효성 체크
if confidence_current > 0.5:
box = res[0:4] * np.array([Width, Height, Width, Height])
x, y, w, h = box.astype("int")
x = int(x-(w/2))
y = int(y-(h/2))
boxes.append([x, y, int(w), int(h)])
confidence.append(float(confidence_current)) # 박스의 신뢰도
classes.append(class_current)
results = cv2.dnn.NMSBoxes(boxes, confidence, 0.5, 0.4)
📌 이미지에 객체 영역 표시하기
colorarea = np.random.randint(0, 255, size=(len(names), 3))
if len(results) > 0 :
for i in results:
x, y = boxes[i][0], boxes[i][1]
width, height = boxes[i][2], boxes[i][3]
colorarea_currnet = [int(j) for j in colorarea[ classes[i]]]
cv2.rectangle(image, (x,y), (x+width, y+height), colorarea_currnet, 5)
text_bar_current = "{}:{:.4f}".format(names[classes[i]], confidence[i])
cv2.putText(image, text_bar_current, (x+2, y+2), cv2.FONT_HERSHEY_DUPLEX, 0.5, (0,0,0))
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.show()
