test.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. import argparse
  2. import cv2
  3. import os
  4. import time
  5. import numpy as np
  6. from copy import deepcopy
  7. import torch
  8. # load transform
  9. from datasets import build_dataset, build_transform
  10. from datasets.coco import coco_labels_91
  11. # load some utils
  12. from utils.misc import load_weight, compute_flops
  13. from utils.vis_tools import visualize
  14. from config import build_config
  15. from models.detectors import build_model
  16. def parse_args():
  17. parser = argparse.ArgumentParser(description='Object Detection Lab')
  18. # Basic
  19. parser.add_argument('--cuda', action='store_true', default=False,
  20. help='use cuda.')
  21. parser.add_argument('--show', action='store_true', default=False,
  22. help='show the visulization results.')
  23. parser.add_argument('--save', action='store_true', default=False,
  24. help='save the visulization results.')
  25. parser.add_argument('--save_folder', default='det_results/', type=str,
  26. help='Dir to save results')
  27. parser.add_argument('-vt', '--visual_threshold', default=0.3, type=float,
  28. help='Final confidence threshold')
  29. parser.add_argument('-ws', '--window_scale', default=1.0, type=float,
  30. help='resize window of cv2 for visualization.')
  31. # Model
  32. parser.add_argument('-m', '--model', default='yolof_r18_c5_1x', type=str,
  33. help='build detector')
  34. parser.add_argument('--weight', default=None,
  35. type=str, help='Trained state_dict file path to open')
  36. parser.add_argument('--fuse_conv_bn', action='store_true', default=False,
  37. help='fuse Conv & BN')
  38. # Dataset
  39. parser.add_argument('--root', default='/Users/liuhaoran/Desktop/python_work/object-detection/dataset/COCO/',
  40. help='data root')
  41. parser.add_argument('-d', '--dataset', default='coco',
  42. help='coco, voc.')
  43. return parser.parse_args()
  44. @torch.no_grad()
  45. def test_det(args, model, device, dataset, transform, class_colors, class_names):
  46. num_images = len(dataset)
  47. save_path = os.path.join('det_results/', args.dataset, args.model)
  48. os.makedirs(save_path, exist_ok=True)
  49. for index, (image, _) in enumerate(dataset):
  50. print('Testing image {:d}/{:d}....'.format(index+1, num_images))
  51. orig_h, orig_w = image.height, image.width
  52. # PreProcess
  53. x, _ = transform(image)
  54. x = x.unsqueeze(0).to(device)
  55. # Inference
  56. t0 = time.time()
  57. outputs = model(x)
  58. scores = outputs['scores']
  59. labels = outputs['labels']
  60. bboxes = outputs['bboxes']
  61. print("Infer. time: {}".format(time.time() - t0, "s"))
  62. # Rescale bboxes
  63. bboxes[..., 0::2] *= orig_w
  64. bboxes[..., 1::2] *= orig_h
  65. # Convert PIL.Image to numpy
  66. image = np.array(image).astype(np.uint8)
  67. image = image[..., (2, 1, 0)].copy()
  68. # Visualize results
  69. img_processed = visualize(image=image,
  70. bboxes=bboxes,
  71. scores=scores,
  72. labels=labels,
  73. class_colors=class_colors,
  74. class_names=class_names)
  75. if args.show:
  76. h, w = img_processed.shape[:2]
  77. sw, sh = int(w*args.window_scale), int(h*args.window_scale)
  78. cv2.namedWindow('detection', 0)
  79. cv2.resizeWindow('detection', sw, sh)
  80. cv2.imshow('detection', img_processed)
  81. cv2.waitKey(0)
  82. if args.save:
  83. # save result
  84. cv2.imwrite(os.path.join(save_path, str(index).zfill(6) +'.jpg'), img_processed)
  85. if __name__ == '__main__':
  86. args = parse_args()
  87. # cuda
  88. if args.cuda:
  89. print('use cuda')
  90. device = torch.device("cuda")
  91. else:
  92. device = torch.device("cpu")
  93. # Dataset & Model Config
  94. cfg = build_config(args)
  95. # Transform
  96. transform = build_transform(cfg, is_train=False)
  97. # Dataset
  98. dataset = build_dataset(args, cfg, is_train=False)
  99. if args.model == "detr_r50":
  100. # Test official DETR model
  101. cfg.class_labels = coco_labels_91
  102. cfg.num_classes = 91
  103. # Model
  104. model = build_model(args, cfg, is_val=False)
  105. model = load_weight(model, args.weight, args.fuse_conv_bn)
  106. model.to(device).eval()
  107. # Compute FLOPs and Params
  108. model_copy = deepcopy(model)
  109. model_copy.trainable = False
  110. model_copy.eval()
  111. compute_flops(
  112. model=model_copy,
  113. min_size=cfg.test_min_size,
  114. max_size=cfg.test_max_size,
  115. device=device)
  116. del model_copy
  117. print("================= DETECT =================")
  118. # Color for beautiful visualization
  119. np.random.seed(0)
  120. class_colors = [(np.random.randint(255),
  121. np.random.randint(255),
  122. np.random.randint(255))
  123. for _ in range(cfg.num_classes)]
  124. # Run
  125. test_det(args = args,
  126. model = model,
  127. device = device,
  128. dataset = dataset,
  129. transform = transform,
  130. class_colors = class_colors,
  131. class_names = cfg.class_labels,
  132. )