当前位置:   article > 正文

py-faster-rcnn标注FDDB人脸便于其在FDDB上进行测试_fddb 未检测到人脸怎么标注

fddb 未检测到人脸怎么标注

本程序是在py-faster-rcnn/tools/demo.py的基础上进行修改的

程序功能:用训练好的caffemodel,对FDDB人脸进行标注,便于其在FDDB上进行测试

  1. <span style="font-size:24px;">#!/usr/bin/env python
  2. # --------------------------------------------------------
  3. # Faster R-CNN
  4. # Copyright (c) 2015 Microsoft
  5. # Licensed under The MIT License [see LICENSE for details]
  6. # Written by Ross Girshick
  7. # --------------------------------------------------------
  8. """
  9. Demo script showing detections in sample images.
  10. See README.md for installation instructions before running.
  11. """
  12. import _init_paths
  13. from fast_rcnn.config import cfg
  14. from fast_rcnn.test import im_detect
  15. from fast_rcnn.nms_wrapper import nms
  16. from utils.timer import Timer
  17. import matplotlib.pyplot as plt
  18. import numpy as np
  19. import scipy.io as sio
  20. import caffe, os, sys, cv2
  21. import argparse
  22. #CLASSES = ('__background__', #背景 + 类
  23. # 'aeroplane', 'bicycle', 'bird', 'boat',
  24. # 'bottle', 'bus', 'car', 'cat', 'chair',
  25. # 'cow', 'diningtable', 'dog', 'horse',
  26. # 'motorbike', 'person', 'pottedplant',
  27. # 'sheep', 'sofa', 'train', 'tvmonitor')
  28. CLASSES = ('__background__','face') #只有一类:face
  29. NETS = {'vgg16': ('VGG16',
  30. 'VGG16_faster_rcnn_final.caffemodel'),
  31. 'myvgg': ('VGG_CNN_M_1024',
  32. 'VGG_CNN_M_1024_faster_rcnn_final.caffemodel'),
  33. 'zf': ('ZF',
  34. 'ZF_faster_rcnn_final.caffemodel'),
  35. 'myzf': ('ZF',
  36. 'zf_rpn_stage1_iter_80000.caffemodel'),
  37. }
  38. def vis_detections(im, class_name, dets, thresh=0.5):
  39. """Draw detected bounding boxes."""
  40. inds = np.where(dets[:, -1] >= thresh)[0]
  41. if len(inds) == 0:
  42. return
  43. write_file.write(str(len(inds)) + '\n') #add by zhipeng
  44. im = im[:, :, (2, 1, 0)]
  45. #fig, ax = plt.subplots(figsize=(12, 12))
  46. #ax.imshow(im, aspect='equal')
  47. for i in inds:
  48. bbox = dets[i, :4]
  49. score = dets[i, -1]
  50. ########## add by zhipeng for write rectange to txt ########
  51. write_file.write( "{} {} {} {} {}\n".format(str(bbox[0]), str(bbox[1]),
  52. str(bbox[2] - bbox[0]),
  53. str(bbox[3] - bbox[1]),
  54. str(score)))
  55. #print "zhipeng, bbox:", bbox, "score:",score
  56. ########## add by zhipeng for write rectange to txt ########
  57. '''ax.add_patch(
  58. plt.Rectangle((bbox[0], bbox[1]),
  59. bbox[2] - bbox[0],
  60. bbox[3] - bbox[1], fill=False,
  61. edgecolor='red', linewidth=3.5)
  62. )
  63. ax.text(bbox[0], bbox[1] - 2,
  64. '{:s} {:.3f}'.format(class_name, score),
  65. bbox=dict(facecolor='blue', alpha=0.5),
  66. fontsize=14, color='white')
  67. ax.set_title(('{} detections with '
  68. 'p({} | box) >= {:.1f}').format(class_name, class_name,
  69. thresh),
  70. fontsize=14)
  71. plt.axis('off')
  72. plt.tight_layout()
  73. plt.draw()'''
  74. def demo(net, image_name):
  75. """Detect object classes in an image using pre-computed object proposals."""
  76. # Load the demo image
  77. #im_file = os.path.join(cfg.DATA_DIR, 'demo', image_name)
  78. im = cv2.imread(image_name)
  79. # Detect all object classes and regress object bounds
  80. timer = Timer()
  81. timer.tic()
  82. scores, boxes = im_detect(net, im)
  83. timer.toc()
  84. print ('Detection took {:.3f}s for '
  85. '{:d} object proposals').format(timer.total_time, boxes.shape[0])
  86. # Visualize detections for each class
  87. CONF_THRESH = 0.8
  88. NMS_THRESH = 0.3
  89. for cls_ind, cls in enumerate(CLASSES[1:]):
  90. cls_ind += 1 # because we skipped background
  91. cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)]
  92. cls_scores = scores[:, cls_ind]
  93. dets = np.hstack((cls_boxes,
  94. cls_scores[:, np.newaxis])).astype(np.float32)
  95. keep = nms(dets, NMS_THRESH)
  96. dets = dets[keep, :]
  97. vis_detections(im, cls, dets, thresh=CONF_THRESH)
  98. def parse_args():
  99. """Parse input arguments."""
  100. parser = argparse.ArgumentParser(description='Faster R-CNN demo')
  101. parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]',
  102. default=0, type=int)
  103. parser.add_argument('--cpu', dest='cpu_mode',
  104. help='Use CPU mode (overrides --gpu)',
  105. action='store_true')
  106. parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16]',
  107. choices=NETS.keys(), default='vgg16')
  108. args = parser.parse_args()
  109. return args
  110. if __name__ == '__main__':
  111. cfg.TEST.HAS_RPN = True # Use RPN for proposals
  112. args = parse_args()
  113. prototxt = os.path.join(cfg.MODELS_DIR, NETS[args.demo_net][0],
  114. 'faster_rcnn_alt_opt', 'faster_rcnn_test.pt')
  115. caffemodel = os.path.join(cfg.DATA_DIR, 'faster_rcnn_models',
  116. NETS[args.demo_net][1])
  117. if not os.path.isfile(caffemodel):
  118. raise IOError(('{:s} not found.\nDid you run ./data/script/'
  119. 'fetch_faster_rcnn_models.sh?').format(caffemodel))
  120. if args.cpu_mode:
  121. caffe.set_mode_cpu()
  122. else:
  123. caffe.set_mode_gpu()
  124. caffe.set_device(args.gpu_id)
  125. cfg.GPU_ID = args.gpu_id
  126. net = caffe.Net(prototxt, caffemodel, caffe.TEST)
  127. print '\n\nLoaded network {:s}'.format(caffemodel)
  128. # Warmup on a dummy image
  129. im = 128 * np.ones((300, 500, 3), dtype=np.uint8)
  130. for i in xrange(2):
  131. _, _= im_detect(net, im)
  132. '''im_names = ['000456.jpg', '000542.jpg', '001150.jpg',
  133. '001763.jpg', '004545.jpg']'''
  134. ########## add by zhipeng for write rectange to txt ########
  135. #write_file_name = '/home/xiao/code/py-faster-rcnn-master/py-faster-rcnn/tools/detections/out.txt'
  136. #write_file = open(write_file_name, "w")
  137. ########## add by zhipeng for write rectange to txt ########
  138. for current_file in range(1,11): #orginal range(1, 11)
  139. print 'Processing file ' + str(current_file) + ' ...'
  140. read_file_name = '/home/xiao/code/py-faster-rcnn-master/py-faster-rcnn/tools/FDDB-fold/FDDB-fold-' + str(current_file).zfill(2) + '.txt'
  141. write_file_name = '/home/xiao/code/py-faster-rcnn-master/py-faster-rcnn/tools/detections/fold-' + str(current_file).zfill(2) + '-out.txt'
  142. write_file = open(write_file_name, "w")
  143. with open(read_file_name, "r") as ins:
  144. array = []
  145. for line in ins:
  146. array.append(line) # list of strings
  147. number_of_images = len(array)
  148. for current_image in range(number_of_images):
  149. if current_image % 10 == 0:
  150. print 'Processing image : ' + str(current_image)
  151. # load image and convert to gray
  152. read_img_name = '/home/xiao/code/py-faster-rcnn-master/py-faster-rcnn/data/FDDB/originalPics/' + array[current_image].rstrip() + '.jpg'
  153. write_file.write(array[current_image]) #add by zhipeng
  154. demo(net, read_img_name)
  155. write_file.close()
  156. '''for im_name in im_names:
  157. print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
  158. print 'Demo for data/demo/{}'.format(im_name)
  159. write_file.write(im_name + '\n') #add by zhipeng
  160. demo(net, im_name)'''
  161. #write_file.close() # add by zhipeng,close file
  162. plt.show()
  163. </span>


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/250059
推荐阅读
相关标签
  

闽ICP备14008679号