python opencv 调用yolo的例子

在这里插入图片描述

#!/usr/bin/env python3
import cv2 
import numpy as np 
import os 
path  = os.getcwd()
modelConfiguration = path+ '/model/yolov3.cfg'
modelWeights = path+ '/model/yolov3.weights'
classesFile = path + '/model/coco.names'

class YOLO:
    def __init__(self):
        self.confThreshold = 0.5
        self.nms_threshold = 0.3 
        self.whT = 320
        self.classNames = []
        with open(classesFile, 'rt') as f:
            self.classNames = f.read().rstrip('\n').split('\n')
        self.net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
        self.net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
        self.net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)

    def detect(self,image):
        blob = cv2.dnn.blobFromImage(image,1/255,(self.whT,self.whT),[0,0,0],1,crop=False)
        self.net.setInput(blob)
        layerNames = self.net.getLayerNames()
        outputNames = [layerNames[i[0]-1] for i in self.net.getUnconnectedOutLayers()]
        outputs = self.net.forward(outputNames)
        hT,wT,cT = image.shape
        bbox = []

        #class Ids and their confidence value
        classIds = []
        confs = []
        for output in outputs:
            for det in output:
                #remove first 5 elements find the value of the height value
                scores = det[5:]
                #index
                classId = np.argmax(scores)
                #value of that index
                confidence = scores[classId]

                #filtering object
                if confidence > self.confThreshold:
                    #save width,height,x,y(are in decimals so we have to multiple them by our actual image size)
                    w,h=int(det[2]*wT),int(det[3]*hT)
                    #the center point(divide by 2 and substract)
                    x,y=int(det[0]*wT - w/2) , int(det[1]*hT - h/2)
                    bbox.append([x,y,w,h])
                    classIds.append(classId)
                    confs.append(float(confidence))
        print(len(bbox))
        indices = cv2.dnn.NMSBoxes(bbox,confs,self.confThreshold,self.nms_threshold)
        for i in indices:
            #to remove the extra bracket
            i = i[0]
            box = bbox[i]
            #extract x,y,width,height
            x,y,w,h = box[0],box[1],box[2],box[3]
            #drawing the box
            cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,255),2)
            #print name and confidence level
            cv2.putText(image,f'{self.classNames[classIds[i]].upper()} {int(confs[i]*100)}%',
                        (x,y-10),cv2.FONT_HERSHEY_SIMPLEX,0.6,(255,0,255),2)
        

if __name__ == "__main__":
    image = cv2.imread("kids.jpg")
    yolo_model = YOLO()
    yolo_model.detect(image)
    cv2.imshow("result", image)
    cv2.waitKey(0)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值