先贴效果。文末都有项目文件,伸手直接拿。你只看一次,你只看一次。这么有故事的名模,真的值得一试。我们直接下载yolov3模型使用,所以需要下载几个东西,除了检测代码是自己写的,其他的都要下载。文末分享了所有下载资料,大家可以自行下载。所需文件代码的解释其实主要难点在于画图,而不是如何预测,因为我们直接加载yolo来检测。最好对照项目代码看下面的代码,不然看起来没有层次感。首先加载yolo:#loadyolobase=r"G:/Code/YOLOrecognition/"net=cv2.dnn.readNet(base+"yolov3.weights",base+"yolov3.cfg")classes=[]withopen(base+"coco.names")asf:classes=[line.strip()forlineinf]#print(classes)接下来,将图像加载到cv中并进行简单的blob转换。这里的高、宽等是为后续绘制方框做标记对象准备的#loadimageimg=cv2.imread(base+"2.jpg")#img=cv2.resize(img,None,fx=0.4,fy=0.4)height,width,channel=img.shapecv2.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里面有很多很多的objectcenter和对应的confidence值。我们需要将置信度值大于0.5的框一个一个的取出来。因为yolo会有很多重叠的物体中心,我们先把他拿出来用。confidences=[]boxes=[]pred_indeces=[]#showinfoonpicforoutinouts:fordetectioninout:scores=detection[5:]pred_index=np.argmax(scores)confidence=scores[pred_index]如果有信心>0.5:print("有一个!")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)#矩形坐标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)然后画出不同颜色的框。如果不需要,也可以自己使用setcolorcolors=np.random.uniform(0,255,size=(len(classes),3))font=cv2.FONT_HERSHEY_PLAINforiinrange(len(boxes)):如果iinindexes: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)并显示出来cv2.imshow("detection",img)cv2.waitKey(0)cv2.destroyAllWindows()最后伸手把百度网盘里的东西全部拿走,记得改路径下载地址:链接:https://pan.baidu.com/s/1PzAQ...提取码:z1oi复制此内容后,打开百度网盘手机APP,操作更方便
