opencv+yolov3實現物體檢測

效果:

 

yolo, you only look once. 如此著名故事又多的模型,真的值得一試。

我們是直接下載人家yolov3模型來用,所以需要下載幾個東西,除了detection是我們自己寫的代碼,其餘都要下載,文末分享了所有的下載材料,自己下載即可。

 

代碼講解:

其實主要的代碼在畫框上,而不是怎樣預測上,因爲我們直接加載了yolo來detect。

 

首先加載yolo,加載類別,沒什麼好說的

#load yolo
base=r"G:/Code/YOLO recognition/"
net = cv2.dnn.readNet(base+"yolov3.weights",base+"yolov3.cfg")

classes=[]
with open(base+"coco.names") as f:
    classes=[line.strip() for line in f]

# print(classes)

接下來加載圖片到cv中,做一下簡單的blob變換。這裏的height、width等等,爲了之後的畫方框標出物體做準備

#load image
img=cv2.imread(base+"2.jpg")
# img=cv2.resize(img,None,fx=0.4,fy=0.4)
height,width,channel=img.shape
cv2.imshow("original",img)
blob=cv2.dnn.blobFromImage(img,0.00392,(416,416),(0,0,0),True,crop=False)

然後用yolo預測物體中心,很簡單。。。

net.setInput(blob)
outs=net.forward(output_layers)

這樣outs裏面就有了很多很多物體的中心以及對應的可信值(confidence),我們要逐一把可信值大於0.5的框框取出來。因爲yolo會出現很多重合的物體中心,所以我們先把他取出來待用。

confidences=[]
boxes=[]
pred_indeces=[]
#show info on pic
for out in outs:
    for detection in out:
        scores=detection[5:]
        pred_index=np.argmax(scores)
        confidence=scores[pred_index]
        
        if confidence > 0.5:
            print("there is one!")
            
            center_x=int(detection[0]*width)
            center_y=int(detection[1]*height)
            w= int(detection[2]*width)
            h=int(detection[3]*height)

            # cv2.circle(img,(center_x,center_y),10,(0,0,255),2)

            #rectangle coordinates
            x=int(center_x-w/2)
            y=int(center_y-h/2)

            boxes.append([x,y,w,h])
            pred_indeces.append(pred_index)
            confidences.append(float(confidence))
            # cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)

然後把重複的物體中心去掉

indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)

然後用不同的顏色畫框,如果不需要的話,也可以自己設定color

colors = np.random.uniform(0, 255, size=(len(classes), 3))
font=cv2.FONT_HERSHEY_PLAIN
for i in range(len(boxes)):
    if i in indexes:
        x,y,w,h=boxes[i]
        label=classes[pred_indeces[i]]
        color=colors[i]
        cv2.rectangle(img,(x,y),(x+w,y+h),color,2)
        cv2.putText(img,label,(x,y+30),font,1,color,2)

然後show出來就可以了

cv2.imshow("detection",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

 

伸手黨把百度網盤的項目全都取走即可,記得自己改下路徑。

下載地址:

鏈接:https://pan.baidu.com/s/1PzAQnybF7fMiVFRXti9SoA 
提取碼:z1oi 
複製這段內容後打開百度網盤手機App,操作更方便哦

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章