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,操作更方便哦

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值