Оптимизация кода веб-камеры для тестирования TF-fast-cnn - PullRequest
0 голосов
/ 21 января 2020

Я новичок в машинном обучении и пытаюсь запустить код для обнаружения изображений, но проблема, с которой я сталкиваюсь, заключается в том, что при попытке отобразить изображение код становится очень медленным, а частота кадров снижается до 3 или 4 FPS. Я приложил код. Кто-нибудь может, пожалуйста, подсказать мне, как оптимизировать этот код, чтобы, когда изображения начинают показывать, что он не медленный, ярлыки и объекты, которые я обучил, обнаруживают около 134 предметов.

  cap = cv2.VideoCapture(0)
  cap.set(cv2.CAP_PROP_FPS, 2)


  while True:
    ret, image_np = cap.read()
    time = datetime.now()

    print('Step 0 :: ' + str(datetime.now()))

    _t['im_detect'].tic()
    scores, boxes = im_detect(sess, net, image_np)
    _t['im_detect'].toc()

    _t['misc'].tic()
    print('Step 1 :: ' + str(datetime.now() - time))
    # Visualize detections for each class
    CONF_THRESH = 0.8
    NMS_THRESH = 0.3
    for cls_ind, cls in enumerate(CLASSES[1:]):
        cls_ind += 1 # because we skipped background
        cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)]
        cls_scores = scores[:, cls_ind]
        dets = np.hstack((cls_boxes,
                          cls_scores[:, np.newaxis])).astype(np.float32)
        keep = nms(dets, NMS_THRESH)
        dets = dets[keep, :]
        vis_detections(image_np, cls, dets, thresh=CONF_THRESH)

    print('Step 2 :: ' + str(datetime.now() - time))
    print('im_detect: {:d}/{:d} {:.3f}s {:.3f}s' \
        .format(1, num_images, _t['im_detect'].average_time,
            _t['misc'].average_time))

  det_file = os.path.join(output_dir, 'detections.pkl')
  with open(det_file, 'wb') as f:
    pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL)

  print('Evaluating detections')
  imdb.evaluate_detections(all_boxes, output_dir)

def vis_detections(im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]

    if len(inds) > 0:
      for i in inds:
          bbox = dets[i, :4]
          score = dets[i, -1]

          # ax.text(bbox[0], bbox[1] - 2,
          #         '{:s} {:.0f}'.format(class_name, score),
          #         bbox=dict(facecolor='blue', alpha=0.5),
          #         fontsize=14, color='white')
          print(str(class_name))
          im = cv2.rectangle(im,(bbox[0], bbox[1]),(bbox[2], bbox[3]),(0,255,0),3)

          font                   = cv2.FONT_HERSHEY_SIMPLEX
          bottomLeftCornerOfText = (bbox[0], bbox[1])
          fontScale              = 0.5
          fontColor              = (255,255,255)
          lineType               = 2

          cv2.putText(im, class_name + " " + str(score), 
              bottomLeftCornerOfText, 
              font, 
              fontScale,
              fontColor,
              lineType)

    cv2.imshow('object detection', cv2.resize(im, (1280, 1024)))
    if cv2.waitKey(25) & 0xFF == ord('q'):
      cv2.destroyAllWindows()
...