test.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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 dataset.build import build_dataset, build_transform
  10. # load some utils
  11. from utils.misc import load_weight, compute_flops
  12. from utils.box_ops import rescale_bboxes
  13. from utils.vis_tools import visualize
  14. from config import build_config
  15. from models import build_model
  16. def parse_args():
  17. parser = argparse.ArgumentParser(description='Real-time Object Detection LAB')
  18. # Basic setting
  19. parser.add_argument('-size', '--img_size', default=640, type=int,
  20. help='the max size of input image')
  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('--cuda', action='store_true', default=False,
  26. help='use cuda.')
  27. parser.add_argument('--save_folder', default='det_results/', type=str,
  28. help='Dir to save results')
  29. parser.add_argument('-ws', '--window_scale', default=1.0, type=float,
  30. help='resize window of cv2 for visualization.')
  31. # Model setting
  32. parser.add_argument('-m', '--model', default='yolo_n', type=str,
  33. help='build yolo')
  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. # Data setting
  39. parser.add_argument('--root', default='D:/python_work/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,
  46. model,
  47. device,
  48. dataset,
  49. transform=None,
  50. class_colors=None,
  51. class_names=None):
  52. num_images = len(dataset)
  53. save_path = os.path.join('det_results/', args.dataset, args.model)
  54. os.makedirs(save_path, exist_ok=True)
  55. for index in range(num_images):
  56. print('Testing image {:d}/{:d}....'.format(index+1, num_images))
  57. image, _ = dataset.pull_image(index)
  58. orig_h, orig_w, _ = image.shape
  59. orig_size = [orig_w, orig_h]
  60. # prepare
  61. x, _, ratio = transform(image)
  62. x = x.unsqueeze(0).to(device)
  63. t0 = time.time()
  64. # inference
  65. outputs = model(x)
  66. scores = outputs['scores']
  67. labels = outputs['labels']
  68. bboxes = outputs['bboxes']
  69. print("detection time used ", time.time() - t0, "s")
  70. # rescale bboxes
  71. bboxes = rescale_bboxes(bboxes, orig_size, ratio)
  72. # vis detection
  73. img_processed = visualize(image=image,
  74. bboxes=bboxes,
  75. scores=scores,
  76. labels=labels,
  77. class_colors=class_colors,
  78. class_names=class_names)
  79. if args.show:
  80. h, w = img_processed.shape[:2]
  81. sw, sh = int(w*args.window_scale), int(h*args.window_scale)
  82. cv2.namedWindow('detection', 0)
  83. cv2.resizeWindow('detection', sw, sh)
  84. cv2.imshow('detection', img_processed)
  85. cv2.waitKey(0)
  86. if args.save:
  87. # save result
  88. cv2.imwrite(os.path.join(save_path, str(index).zfill(6) +'.jpg'), img_processed)
  89. if __name__ == '__main__':
  90. args = parse_args()
  91. # Set cuda
  92. if args.cuda and torch.cuda.is_available():
  93. print('use cuda')
  94. device = torch.device("cuda")
  95. else:
  96. device = torch.device("cpu")
  97. # Build config
  98. cfg = build_config(args)
  99. # Build data processor
  100. transform = build_transform(cfg, is_train=False)
  101. # Build dataset
  102. dataset = build_dataset(args, cfg, transform, is_train=False)
  103. # Build model
  104. model = build_model(args, cfg, is_val=False)
  105. # Load trained weight
  106. model = load_weight(model, args.weight, args.fuse_conv_bn)
  107. model.to(device).eval()
  108. # Compute FLOPs and Params
  109. model_copy = deepcopy(model)
  110. model_copy.trainable = False
  111. model_copy.eval()
  112. compute_flops(model_copy, cfg.test_img_size, device)
  113. del model_copy
  114. print("================= DETECT =================")
  115. # Color for beautiful visualization
  116. np.random.seed(0)
  117. class_colors = [(np.random.randint(255),
  118. np.random.randint(255),
  119. np.random.randint(255))
  120. for _ in range(cfg.num_classes)]
  121. # Run
  122. test_det(args = args,
  123. model = model,
  124. device = device,
  125. dataset = dataset,
  126. transform = transform,
  127. class_colors = class_colors,
  128. class_names = cfg.class_labels,
  129. )