darknet yolov3v3 Colaboratory

 

 

1.voc_labe.py

代码如下:

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join

sets=[('2007', 'train'), ('2007', 'val'), ('2007', 'test')]

classes = ["mouse"]


def convert(size, box):
    dw = 1./(size[0])
    dh = 1./(size[1])
    x = (box[0] + box[1])/2.0 - 1
    y = (box[2] + box[3])/2.0 - 1
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x*dw
    w = w*dw
    y = y*dh
    h = h*dh
    return (x,y,w,h)

def convert_annotation(year, image_id):
    in_file = open('VOCdevkit/VOC%s/Annotations/%s.xml'%(year, image_id))
    out_file = open('VOCdevkit/VOC%s/labels/%s.txt'%(year, image_id), 'w')
    tree=ET.parse(in_file)
    root = tree.getroot()
    size = root.find('size')
    w = int(size.find('width').text)
    h = int(size.find('height').text)

    for obj in root.iter('object'):
        difficult = obj.find('difficult').text
        cls = obj.find('name').text
        if cls not in classes or int(difficult)==1:
            continue
        cls_id = classes.index(cls)
        xmlbox = obj.find('bndbox')
        b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
        bb = convert((w,h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')

wd = getcwd()

for year, image_set in sets:
    if not os.path.exists('VOCdevkit/VOC%s/labels/'%(year)):
        os.makedirs('VOCdevkit/VOC%s/labels/'%(year))
    image_ids = open('VOCdevkit/VOC%s/ImageSets/Main/%s.txt'%(year, image_set)).read().strip().split()
    list_file = open('%s_%s.txt'%(year, image_set), 'w')
    for image_id in image_ids:
        list_file.write('%s/VOCdevkit/VOC%s/JPEGImages/%s.jpg\n'%(wd, year, image_id))
        convert_annotation(year, image_id)
    list_file.close()


2.CreateMainDirTex.py

代码如下:

import os
import random

trainval_percent = 0.1
train_percent = 0.9
xmlfilepath = 'Annotations'
txtsavepath = 'ImageSets\Main'
total_xml = os.listdir(xmlfilepath)

num = len(total_xml)
list = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list, tv)
train = random.sample(trainval, tr)

ftrainval = open('ImageSets/Main/trainval.txt', 'w')
ftest = open('ImageSets/Main/test.txt', 'w')
ftrain = open('ImageSets/Main/train.txt', 'w')
fval = open('ImageSets/Main/val.txt', 'w')

for i in list:
    name = total_xml[i][:-4] + '\n'
    if i in trainval:
        ftrainval.write(name)
        if i in train:
            ftest.write(name)
        else:
            fval.write(name)
    else:
        ftrain.write(name)

ftrainval.close()
ftrain.close()
fval.close()
ftest.close()

3.video.py

代码如下:
 

# @Time    : 2021/4/14 12:59
# @File    : yolo3-video.py
import cv2 as cv
import argparse
import sys
import numpy as np
import os.path
# python yolo3-video.py --video=video.mp4
confThreshold = 0.4  # Confidence threshold
nmsThreshold = 0.6 # Non-maximum suppression threshold
inpWidth = 416  # Width of network's input image
inpHeight = 416  # Height of network's input image

parser = argparse.ArgumentParser(description='Object Detection using YOLO in OPENCV')
parser.add_argument('--image', help='Path to image file.')
parser.add_argument('--video', help='Path to video file.')
args = parser.parse_args()

# Load names of classes
classesFile = "data/config.names";
classes = None
with open(classesFile, 'rt') as f:
      classes = f.read().rstrip('\n').split('\n')

# Give the configuration and weight files for the model and load the network using them.
modelConfiguration = "cfg/yolov3-tiny.cfg";
modelWeights = "backup/yolov3-tiny_last.weights";

net = cv.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)


# Get the names of the output layers
def getOutputsNames(net):
      # Get the names of all the layers in the network
      layersNames = net.getLayerNames()
      # Get the names of the output layers,
      # i.e. the layers with unconnected outputs
      return [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()]


# Draw the predicted bounding box
def drawPred(classId, conf, left, top, right, bottom):
      # Draw a bounding box.
      cv.rectangle(frame, (left, top), (right, bottom), (255, 178, 50), 3)

      label = '%.2f' % conf

      # Get the label for the class name and its confidence
      if classes:
            assert (classId < len(classes))
            label = '%s:%s' % (classes[classId], label)

      # Display the label at the top of the bounding box
      labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)
      top = max(top, labelSize[1])
      cv.rectangle(frame, (left, top - round(1.5 * labelSize[1])), (left + round(1.5 * labelSize[0]), top + baseLine),
                   (255, 255, 255), cv.FILLED)
      cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 0), 1)


# Remove the bounding boxes with low confidence using nms
def postprocess(frame, outs):
      frameHeight = frame.shape[0]
      frameWidth = frame.shape[1]

      classIds = []
      confidences = []
      boxes = []
      classIds = []
      confidences = []
      boxes = []
      for out in outs:
            for detection in out:
                  scores = detection[5:]
                  classId = np.argmax(scores)
                  confidence = scores[classId]
                  if confidence > confThreshold:
                        center_x = int(detection[0] * frameWidth)
                        center_y = int(detection[1] * frameHeight)
                        width = int(detection[2] * frameWidth)
                        height = int(detection[3] * frameHeight)
                        left = int(center_x - width / 2)
                        top = int(center_y - height / 2)
                        classIds.append(classId)
                        confidences.append(float(confidence))
                        boxes.append([left, top, width, height])

      # Perform nms to eliminate redundant overlapping boxes with
      # lower confidences.
      indices = cv.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold)
      for i in indices:
            i = i[0]
            box = boxes[i]
            left = box[0]
            top = box[1]
            width = box[2]
            height = box[3]
            drawPred(classIds[i], confidences[i], left, top, left + width, top + height)


# Process inputs
winName = 'Deep learning object detection in OpenCV'
cv.namedWindow(winName, cv.WINDOW_NORMAL)

outputFile = "yolo_out_py.avi"
if (args.image):
      # Open the image file
      if not os.path.isfile(args.image):
            print("Input image file ", args.image, " doesn't exist")
            sys.exit(1)
      cap = cv.VideoCapture(args.image)
      outputFile = args.image[:-4] + '_yolo_out_py.jpg'
elif (args.video):
      # Open the video file
      if not os.path.isfile(args.video):
            print("Input video file ", args.video, " doesn't exist")
            sys.exit(1)
      cap = cv.VideoCapture(args.video)
      outputFile = args.video[:-4] + '_yolo_out_py.avi'
else:
      # Webcam input
      cap = cv.VideoCapture(0)

# Get the video writer initialized to save the output video
if (not args.image):
      vid_writer = cv.VideoWriter(outputFile, cv.VideoWriter_fourcc('M', 'J', 'P', 'G'), 30,
                                  (round(cap.get(cv.CAP_PROP_FRAME_WIDTH)), round(cap.get(cv.CAP_PROP_FRAME_HEIGHT))))

while cv.waitKey(1) < 0:

      # get frame from the video
      hasFrame, frame = cap.read()

      # Stop the program if reached end of video
      if not hasFrame:
            print("Done processing !!!")
            print("Output file is stored as ", outputFile)
            cv.waitKey(3000)
            # Release device
            cap.release()
            break

      # Create a 4D blob from a frame.
      blob = cv.dnn.blobFromImage(frame, 1 / 255, (inpWidth, inpHeight), [0, 0, 0], 1, crop=False)

      # Sets the input to the network
      net.setInput(blob)
      # Runs the forward pass to get output of the output layers
      outs = net.forward(getOutputsNames(net))
      # Remove the bounding boxes with low confidence
      postprocess(frame, outs)

      # Put efficiency information.
      # The function getPerfProfile returns the overall time for inference(t)
      # and the timings for each of the layers(in layersTimes)
      t, _ = net.getPerfProfile()
      label = 'Inference time: %.2f ms' % (t * 100.0 / cv.getTickFrequency())
      cv.putText(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255))

      # Write the frame with the detection boxes
      if (args.image):
            cv.imwrite(outputFile, frame.astype(np.uint8));
      else:
            vid_writer.write(frame.astype(np.uint8))
      cv.imshow(winName, frame)


作:yc

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值