源代碼來(lái)自小賽的文章儡遮,他的解釋更加詳細(xì)蹬挤,這里我做記錄用讶坯。
import numpyas np
import cv2as cv
import os
import time
yolo_dir ='/home/hessesummer/github/NTS-Net-my/yolov3' # YOLO文件路徑
weightsPath = os.path.join(yolo_dir, 'yolov3.weights')# 權(quán)重文件
configPath = os.path.join(yolo_dir, 'yolov3.cfg')# 配置文件
labelsPath = os.path.join(yolo_dir, 'coco.names')# label名稱
imgPath = os.path.join(yolo_dir, 'test.jpg')# 測(cè)試圖像
CONFIDENCE =0.5 # 過濾弱檢測(cè)的最小概率
THRESHOLD =0.4 # 非最大值抑制閾值
# 加載網(wǎng)絡(luò)休建、配置權(quán)重
net = cv.dnn.readNetFromDarknet(configPath, weightsPath)# # 利用下載的文件
print("[INFO] loading YOLO from disk...")# # 可以打印下信息
# 加載圖片、轉(zhuǎn)為blob格式聚谁、送入網(wǎng)絡(luò)輸入層
img = cv.imread(imgPath)
blobImg = cv.dnn.blobFromImage(img, 1.0/255.0, (416, 416), None, True, False)# # net需要的輸入是blob格式的母剥,用blobFromImage這個(gè)函數(shù)來(lái)轉(zhuǎn)格式
net.setInput(blobImg)# # 調(diào)用setInput函數(shù)將圖片送入輸入層
# 獲取網(wǎng)絡(luò)輸出層信息(所有輸出層的名字),設(shè)定并前向傳播
outInfo = net.getUnconnectedOutLayersNames()# # 前面的yolov3架構(gòu)也講了形导,yolo在每個(gè)scale都有輸出环疼,outInfo是每個(gè)scale的名字信息,供net.forward使用
start = time.time()
layerOutputs = net.forward(outInfo)# 得到各個(gè)輸出層的骤宣、各個(gè)檢測(cè)框等信息秦爆,是二維結(jié)構(gòu)。
end = time.time()
print("[INFO] YOLO took {:.6f} seconds".format(end - start))# # 可以打印下信息
# 拿到圖片尺寸
(H, W) = img.shape[:2]
# 過濾layerOutputs
# layerOutputs的第1維的元素內(nèi)容: [center_x, center_y, width, height, objectness, N-class score data]
# 過濾后的結(jié)果放入:
boxes = []# 所有邊界框(各層結(jié)果放一起)
confidences = []# 所有置信度
classIDs = []# 所有分類ID
# # 1)過濾掉置信度低的框框
for outin layerOutputs:# 各個(gè)輸出層
for detectionin out:# 各個(gè)框框
# 拿到置信度
scores = detection[5:]# 各個(gè)類別的置信度
classID = np.argmax(scores)# 最高置信度的id即為分類id
confidence = scores[classID]# 拿到置信度
# 根據(jù)置信度篩查
if confidence > CONFIDENCE:
box = detection[0:4] * np.array([W, H, W, H])# 將邊界框放會(huì)圖片尺寸
(centerX, centerY, width, height) = box.astype("int")
x =int(centerX - (width /2))
y =int(centerY - (height /2))
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
# # 2)應(yīng)用非最大值抑制(non-maxima suppression憔披,nms)進(jìn)一步篩掉
idxs = cv.dnn.NMSBoxes(boxes, confidences, CONFIDENCE, THRESHOLD)# boxes中等限,保留的box的索引index存入idxs
# 得到labels列表
with open(labelsPath, 'rt')as f:
labels = f.read().rstrip('\n').split('\n')
# 應(yīng)用檢測(cè)結(jié)果
np.random.seed(42)
COLORS = np.random.randint(0, 255, size=(len(labels), 3), dtype="uint8")# 框框顯示顏色,每一類有不同的顏色芬膝,每種顏色都是由RGB三個(gè)值組成的望门,所以size為(len(labels), 3)
if len(idxs) >0:
for iin idxs.flatten():# indxs是二維的,第0維是輸出層锰霜,所以這里把它展平成1維
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
color = [int(c)for cin COLORS[classIDs[i]]]
cv.rectangle(img, (x, y), (x+w, y+h), color, 2)# 線條粗細(xì)為2px
text ="{}: {:.4f}".format(labels[classIDs[i]], confidences[i])
cv.putText(img, text, (x, y-5), cv.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)# cv.FONT_HERSHEY_SIMPLEX字體風(fēng)格筹误、0.5字體大小、粗細(xì)2px
cv.imshow('detected image', img)
cv.waitKey(0)