学习笔记:简介yolo在python下识别本地视频

前记:

作用说明:学习笔记,主要用于自我记录。

(PS:本人新手,文章仅供参考;如有错误,欢迎各位大神批评指正!)

最近刚刚接触yolo,由于yolo官网和网上各种资料几乎都是基于C语言的,本人觉得python比较简洁,故用python实现了C可实现的部分功能。

该文承接上篇博文“yolo在python下图片检测及画框”。此篇介绍(2)yolo用python实现检测本地视频。

【本系列博文代码基于原作者程序,文中代码由于TAB缩进量可能会出现缩进问题,敬请谅解。】

1、使用环境和平台

ubuntu 14.04+ python2.7+opencv2.4+yolo

2、检测本地视频的python代码

在darknet/python文件夹下新建my_local_video_darknet.py

以下是我实现检测本地视频的代码:

#!coding=utf-8

#modified by Leo at 2018.04.25
#function: 1,detect the video captured by the webcam  
#          2,No passing frames, so it's very slow on my computer.

from ctypes import *
import math
import random
#import module named cv2 to draw
import cv2
import Image

def sample(probs):
    s = sum(probs)
    probs = [a/s for a in probs]
    r = random.uniform(0, 1)
    for i in range(len(probs)):
        r = r - probs[i]
        if r <= 0:
            return i
    return len(probs)-1

def c_array(ctype, values):
    arr = (ctype*len(values))()
    arr[:] = values
    return arr

class BOX(Structure):
    _fields_ = [("x", c_float),
                ("y", c_float),
                ("w", c_float),
                ("h", c_float)]

class DETECTION(Structure):
    _fields_ = [("bbox", BOX),
                ("classes", c_int),
                ("prob", POINTER(c_float)),
                ("mask", POINTER(c_float)),
                ("objectness", c_float),
                ("sort_class", c_int)]


class IMAGE(Structure):
    _fields_ = [("w", c_int),
                ("h", c_int),
                ("c", c_int),
                ("data", POINTER(c_float))]

class METADATA(Structure):
    _fields_ = [("classes", c_int),
                ("names", POINTER(c_char_p))]

    

#lib = CDLL("/home/pjreddie/documents/darknet/libdarknet.so", RTLD_GLOBAL)
lib = CDLL("/home/username/darknet/libdarknet.so", RTLD_GLOBAL)
lib.network_width.argtypes = [c_void_p]
lib.network_width.restype = c_int
lib.network_height.argtypes = [c_void_p]
lib.network_height.restype = c_int

predict = lib.network_predict
predict.argtypes = [c_void_p, POINTER(c_float)]
predict.restype = POINTER(c_float)

set_gpu = lib.cuda_set_device
set_gpu.argtypes = [c_int]

make_image = lib.make_image
make_image.argtypes = [c_int, c_int, c_int]
make_image.restype = IMAGE

get_network_boxes = lib.get_network_boxes
get_network_boxes.argtypes = [c_void_p, c_int, c_int, c_float, c_float, POINTER(c_int), c_int, POINTER(c_int)]
get_network_boxes.restype = POINTER(DETECTION)

make_network_boxes = lib.make_network_boxes
make_network_boxes.argtypes = [c_void_p]
make_network_boxes.restype = POINTER(DETECTION)

free_detections = lib.free_detections
free_detections.argtypes = [POINTER(DETECTION), c_int]

free_ptrs = lib.free_ptrs
free_ptrs.argtypes = [POINTER(c_void_p), c_int]

network_predict = lib.network_predict
network_predict.argtypes = [c_void_p, POINTER(c_float)]

reset_rnn = lib.reset_rnn
reset_rnn.argtypes = [c_void_p]

load_net = lib.load_network
load_net.argtypes = [c_char_p, c_char_p, c_int]
load_net.restype = c_void_p

do_nms_obj = lib.do_nms_obj
do_nms_obj.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]

do_nms_sort = lib.do_nms_sort
do_nms_sort.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]

free_image = lib.free_image
free_image.argtypes = [IMAGE]

letterbox_image = lib.letterbox_image
letterbox_image.argtypes = [IMAGE, c_int, c_int]
letterbox_image.restype = IMAGE

load_meta = lib.get_metadata
lib.get_metadata.argtypes = [c_char_p]
lib.get_metadata.restype = METADATA

load_image = lib.load_image_color
load_image.argtypes = [c_char_p, c_int, c_int]
load_image.restype = IMAGE

rgbgr_image = lib.rgbgr_image
rgbgr_image.argtypes = [IMAGE]

predict_image = lib.network_predict_image
predict_image.argtypes = [c_void_p, IMAGE]
predict_image.restype = POINTER(c_float)

def classify(net, meta, im):
    out = predict_image(net, im)
    res = []
    for i in range(meta.classes):
        res.append((meta.names[i], out[i]))
    res = sorted(res, key=lambda x: -x[1])
    return res

def detect(net, meta, image, thresh=.5, hier_thresh=.5, nms=.45):
    im = load_image(image, 0, 0) 
    num = c_int(0)
    pnum = pointer(num)
    predict_image(net, im)
    dets = get_network_boxes(net, im.w, im.h, thresh, hier_thresh, None, 0, pnum)
    num = pnum[0]
    if (nms): do_nms_obj(dets, num, meta.classes, nms);

    res = []
    for j in range(num):
        for i in range(meta.classes):
            if dets[j].prob[i] > 0:
                b = dets[j].bbox
                res.append((meta.names[i], dets[j].prob[i], (b.x, b.y, b.w, b.h)))
    res = sorted(res, key=lambda x: -x[1])
    free_image(im)
    free_detections(dets, num)
    return res

# 2018.04.25
def showPicResult(image):
    img = cv2.imread(image)
    cv2.imwrite(out_img, img)
    for i in range(len(r)):
        x1=r[i][2][0]-r[i][2][2]/2
        y1=r[i][2][1]-r[i][2][3]/2
        x2=r[i][2][0]+r[i][2][2]/2
        y2=r[i][2][1]+r[i][2][3]/2
        im = cv2.imread(out_img)
        #draw different color rectangle
        '''
        #random color
        r_color = random.randint(0,255)
        g = random.randint(0,255)
        b = random.randint(0,255)
        cv2.rectangle(im,(int(x1),int(y1)),(int(x2),int(y2)),(r_color,g,b),3)
        '''
        cv2.rectangle(im,(int(x1),int(y1)),(int(x2),int(y2)),(0,255,0),3)
        #This is a method that works well. 
        cv2.imwrite(out_img, im)
    cv2.imshow('yolo_image_detector', cv2.imread(out_img))
    
if __name__ == "__main__":
    net = load_net("/home/username/darknet/cfg/yolov3.cfg", "/home/username/darknet/weights/yolov3.weights", 0)
    meta = load_meta("/home/username/darknet/cfg/coco.data")
    out_img = "/home/username/darknet/data/test_result.jpg"
    video_tmp = "/home/username/darknet/data/video_tmp.jpg"
    origin_video = '/home/username/darknet/data/video_20180426_test.mp4'

    # make a video_object and init the video object
    cap = cv2.VideoCapture(origin_video)
    # define picture to_down' coefficient of ratio
    scaling_factor = 0.5
    count = 0
    # loop until press 'esc' or 'q'
    while (cap.isOpened()):
        # collect current frame
        ret, frame = cap.read()
        if ret == True:
    	    count = count + 1
            #print count
        else:
            break
        #detect and show per 50 frames
        if count == 50:
            count = 0
            # resize the frame
            frame = cv2.resize(frame,None,fx=scaling_factor,fy=scaling_factor,interpolation=cv2.INTER_AREA)
            img_arr = Image.fromarray(frame)
            img_goal = img_arr.save(video_tmp)
            r = detect(net, meta, video_tmp)
            print r
            print ''
            print '#*********************************#'
            #display the rectangle of the objects in window
            showPicResult(video_tmp)
        else:
            continue
        # wait 1ms per iteration; press Esc to jump out the loop 
        c = cv2.waitKey(1)
        if (c==27) or (0xFF == ord('q')):
            break
    # release and close the display_window
    cap.release()
 

如果出现配置问题,可参考第一篇博文。

3、代码解释

除了showPicResult()函数(用作绘制物体框)在上一篇博客中已经加入,此程序中再次加入了读取本地视频的相关函数。

    # notice: path of local video
  origin_video = '/home/username/darknet/data/video_20180426_test.mp4'

    # make a video_object and init the video object
    cap = cv2.VideoCapture(origin_video)
    # define picture to_down' coefficient of ratio
    scaling_factor = 0.5
    count = 0
    # loop until press 'esc' or 'q'
    while (cap.isOpened()):
        # collect current frame
        ret, frame = cap.read()
        if ret == True:
    	    count = count + 1
            #print count
        else:
            break
        #detect and show per 50 frames
        if count == 50:
            count = 0
            # resize the frame
            frame = cv2.resize(frame,None,fx=scaling_factor,fy=scaling_factor,interpolation=cv2.INTER_AREA)
            img_arr = Image.fromarray(frame)
            img_goal = img_arr.save(video_tmp)
            r = detect(net, meta, video_tmp)
            print r
            print ''
            print '#*********************************#'
            #display the rectangle of the objects in window
            showPicResult(video_tmp)
        else:
            continue
        # wait 1ms per iteration; press Esc to jump out the loop 
        c = cv2.waitKey(1)
        if (c==27) or (0xFF == ord('q')):
            break
    # release and close the display_window
    cap.release()


此部分主要是读取本地视频的每帧,然后利用python的Image工具把numpy.ndarry的帧数据类型转换为Image类型数据(如不转换在“

 im = load_image(image, 0, 0)

”中就会报错);转换为Image数据类型之后,就可利用我们在第一篇博文中提到的showPicResult()函数在视频中显示物体框。

另外:

由于本人电脑没有独显,处理速度慢,所以在程序中跳过了一些帧(每50帧用yolo检测一次);即使有GPU,也没必要每一帧都去检测,每秒几十帧的图像,大多数都是一样的,挑选几帧检测一下即可。


后记:

程序理解起来很简单,在我自己的电脑上完全可以实现,如有问题欢迎各位大佬批评指正!

联系邮箱:2052383522@qq.com

(PS:后续部分,陆续奉上。)
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值