py-faster-rcnn demo.py解析

来源:互联网 发布:windows 下载 编辑:程序博客网 时间:2024/04/29 21:59

CAFFE深度学习交流群:532629018


对py-faster-rcnn/tools/demo.py文件的解析:
    运行该文件:先cd进入到py-faster-rcnn根目录,再在命令后窗口输入: ./tools/demo.py --net myvgg   即可运行

[python] view plain copy
  1. #程序功能:调用caffemodel,画出检测到的人脸并显示  
  2.   
  3. #用来指定用什么解释器运行脚本,以及解释器所在位置,这样就可以直接执行脚本  
  4. #!/usr/bin/env python  
  5.   
  6. # --------------------------------------------------------  
  7. # Faster R-CNN  
  8. # Copyright (c) 2015 Microsoft  
  9. # Licensed under The MIT License [see LICENSE for details]  
  10. # Written by Ross Girshick  
  11. # --------------------------------------------------------  
  12.   
  13. """ 
  14. Demo script showing detections in sample images. 
  15.  
  16. See README.md for installation instructions before running. 
  17. """  
  18.   
  19. import _init_paths  #导入“_init_paths.py”文件  
  20. from fast_rcnn.config import cfg  
  21. from fast_rcnn.test import im_detect  
  22. from fast_rcnn.nms_wrapper import nms  
  23. from utils.timer import Timer   
  24. import matplotlib.pyplot as plt  #导入用来画图的工具  
  25. import numpy as np  #numpg:矩阵计算模块  
  26. import scipy.io as sio  #scipy.io:对matlab中mat文件进行读取操作  
  27. import caffe, os, sys, cv2  
  28. import argparse  #argparse:是python用于解析命令行参数和选项的标准模块  
  29.   
  30. #CLASSES = ('__background__',   #背景 + 类  
  31. #           'aeroplane', 'bicycle', 'bird', 'boat',  
  32. #           'bottle', 'bus', 'car', 'cat', 'chair',  
  33. #           'cow', 'diningtable', 'dog', 'horse',  
  34. #           'motorbike', 'person', 'pottedplant',  
  35. #           'sheep', 'sofa', 'train', 'tvmonitor')  
  36.   
  37. CLASSES = ('__background__','face')  #只有一类:face  
  38.   
  39. NETS = {'vgg16': ('VGG16',   #网络  
  40.                   'VGG16_faster_rcnn_final.caffemodel'),  
  41.         'myvgg': ('VGG_CNN_M_1024',  
  42.                   'VGG_CNN_M_1024_faster_rcnn_final.caffemodel'),  
  43.         'zf': ('ZF',  
  44.                   'ZF_faster_rcnn_final.caffemodel'),  
  45.         'myzf': ('ZF',  
  46.                   'zf_rpn_stage1_iter_80000.caffemodel'),  
  47. }  
  48.   
  49.   
  50. def vis_detections(im, class_name, dets, thresh=0.5):  
  51.     """Draw detected bounding boxes."""  
  52.     inds = np.where(dets[:, -1] >= thresh)[0]  #返回置信度大于阈值的窗口下标  
  53.     if len(inds) == 0:  
  54.         return  
  55.   
  56.     im = im[:, :, (210)]  
  57.     fig, ax = plt.subplots(figsize=(1212))  
  58.     ax.imshow(im, aspect='equal')  
  59.     for i in inds:  
  60.         bbox = dets[i, :4]  #人脸坐标位置(Xmin,Ymin,Xmax,Ymax)  
  61.         score = dets[i, -1]  #置信度得分  
  62.           
  63.         ax.add_patch(  
  64.             plt.Rectangle((bbox[0], bbox[1]),  #bbox[0]:x, bbox[1]:y, bbox[2]:x+w, bbox[3]:y+h  
  65.                           bbox[2] - bbox[0],  
  66.                           bbox[3] - bbox[1], fill=False,  
  67.                           edgecolor='red', linewidth=3.5)  
  68.             )  
  69.         ax.text(bbox[0], bbox[1] - 2,  
  70.                 '{:s} {:.3f}'.format(class_name, score),  
  71.                 bbox=dict(facecolor='blue', alpha=0.5),  
  72.                 fontsize=14, color='white')  
  73.   
  74.     ax.set_title(('{} detections with '  
  75.                   'p({} | box) >= {:.1f}').format(class_name, class_name,  
  76.                                                   thresh),  
  77.                   fontsize=14)  
  78.     plt.axis('off')  
  79.     plt.tight_layout()  
  80.     plt.draw()  
  81.   
  82. def demo(net, image_name):  
  83.     #检测目标类,在图片中提议窗口  
  84.     """Detect object classes in an image using pre-computed object proposals."""  
  85.   
  86.     # Load the demo image,得到图片绝对地址  
  87.     im_file = os.path.join(cfg.DATA_DIR, 'demo', image_name) #拼接路径,返回'A/B/C'之类路径  
  88.     im = cv2.imread(im_file)  #读取图片  
  89.   
  90.     # Detect all object classes and regress object bounds  
  91.     timer = Timer()  #time.time()返回当前时间  
  92.     timer.tic()  #返回开始时间,见'time.py'中  
  93.     scores, boxes = im_detect(net, im)  #检测,返回得分和人脸区域所在位置  
  94.     timer.toc()  #返回平均时间,'time.py'文件中  
  95.     print ('Detection took {:.3f}s for '  #输出  
  96.            '{:d} object proposals').format(timer.total_time, boxes.shape[0])  
  97.   
  98.     # Visualize detections for each class  
  99.     CONF_THRESH = 0.8  
  100.     NMS_THRESH = 0.3  
  101.     for cls_ind, cls in enumerate(CLASSES[1:]):  #enumerate:用于遍历序列中元素及他们的下标  
  102.         cls_ind += 1 # because we skipped background    ,cls_ind:下标,cls:元素  
  103.         cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)]  #返回当前坐标  
  104.         cls_scores = scores[:, cls_ind]  #返回当前得分  
  105.         dets = np.hstack((cls_boxes,  #hstack:拷贝,合并参数  
  106.                           cls_scores[:, np.newaxis])).astype(np.float32)  
  107.         keep = nms(dets, NMS_THRESH)  
  108.         dets = dets[keep, :]  
  109.         vis_detections(im, cls, dets, thresh=CONF_THRESH)  #画检测框  
  110.   
  111. def parse_args():  
  112.     """Parse input arguments."""  
  113.     parser = argparse.ArgumentParser(description='Faster R-CNN demo')  
  114.     parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]',  
  115.                         default=0, type=int)  
  116.     parser.add_argument('--cpu', dest='cpu_mode',  
  117.                         help='Use CPU mode (overrides --gpu)',  
  118.                         action='store_true')  
  119.     parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16]',  
  120.                         choices=NETS.keys(), default='vgg16')  
  121.   
  122.     args = parser.parse_args()  
  123.   
  124.     return args  
  125.   
  126. if __name__ == '__main__':  #判断是否在直接运行该.py文件  
  127.     cfg.TEST.HAS_RPN = True  # Use RPN for proposals  
  128.   
  129.     args = parse_args()  #模式设置  
  130.   
  131.     prototxt = os.path.join(cfg.MODELS_DIR, NETS[args.demo_net][0],  #连接路径,设置prototxt文件  
  132.                             'faster_rcnn_alt_opt''faster_rcnn_test.pt')  
  133.     caffemodel = os.path.join(cfg.DATA_DIR, 'faster_rcnn_models',  
  134.                               NETS[args.demo_net][1])  
  135.   
  136.     if not os.path.isfile(caffemodel):  
  137.         raise IOError(('{:s} not found.\nDid you run ./data/script/'  
  138.                        'fetch_faster_rcnn_models.sh?').format(caffemodel))  
  139.   
  140.     if args.cpu_mode:  
  141.         caffe.set_mode_cpu()  
  142.     else:  
  143.         caffe.set_mode_gpu()  
  144.         caffe.set_device(args.gpu_id)  
  145.         cfg.GPU_ID = args.gpu_id  
  146.     net = caffe.Net(prototxt, caffemodel, caffe.TEST)  #设置网络  
  147.   
  148.     print '\n\nLoaded network {:s}'.format(caffemodel)  
  149.   
  150.     # Warmup on a dummy image  
  151.     im = 128 * np.ones((3005003), dtype=np.uint8)  
  152.     for i in xrange(2):  #xrange是一个类,返回的是一个xrange对象  
  153.         _, _= im_detect(net, im)  
  154.     #用于演示的图片名  
  155.     im_names = ['000456.jpg''000542.jpg''001150.jpg',  
  156.                 '001763.jpg''004545.jpg''001.jpg''002.jpg''003.jpg',  
  157.                 '004.jpg''005.jpg''006.jpg''007.jpg''008.jpg']  
  158.     for im_name in im_names:  
  159.         print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'  
  160.         print 'Demo for data/demo/{}'.format(im_name)  
  161.         demo(net, im_name)  #逐个跑demo  
  162.   
  163.     plt.show()  
0 0
原创粉丝点击