test.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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. parser.add_argument('--rep_conv', action='store_true', default=False,
  39. help='fuse Rep VGG block')
  40. # Data setting
  41. parser.add_argument('--root', default='D:/python_work/dataset/COCO/',
  42. help='data root')
  43. parser.add_argument('-d', '--dataset', default='coco',
  44. help='coco, voc.')
  45. return parser.parse_args()
  46. @torch.no_grad()
  47. def test_det(args,
  48. model,
  49. device,
  50. dataset,
  51. transform=None,
  52. class_colors=None,
  53. class_names=None):
  54. num_images = len(dataset)
  55. save_path = os.path.join('det_results/', args.dataset, args.model)
  56. os.makedirs(save_path, exist_ok=True)
  57. for index in range(num_images):
  58. print('Testing image {:d}/{:d}....'.format(index+1, num_images))
  59. image, _ = dataset.pull_image(index)
  60. orig_h, orig_w, _ = image.shape
  61. orig_size = [orig_w, orig_h]
  62. # prepare
  63. x, _, ratio = transform(image)
  64. x = x.unsqueeze(0).to(device)
  65. t0 = time.time()
  66. # inference
  67. outputs = model(x)
  68. scores = outputs['scores']
  69. labels = outputs['labels']
  70. bboxes = outputs['bboxes']
  71. print("detection time used ", time.time() - t0, "s")
  72. # rescale bboxes
  73. bboxes = rescale_bboxes(bboxes, orig_size, ratio)
  74. # vis detection
  75. img_processed = visualize(image=image,
  76. bboxes=bboxes,
  77. scores=scores,
  78. labels=labels,
  79. class_colors=class_colors,
  80. class_names=class_names)
  81. if args.show:
  82. h, w = img_processed.shape[:2]
  83. sw, sh = int(w*args.window_scale), int(h*args.window_scale)
  84. cv2.namedWindow('detection', 0)
  85. cv2.resizeWindow('detection', sw, sh)
  86. cv2.imshow('detection', img_processed)
  87. cv2.waitKey(0)
  88. if args.save:
  89. # save result
  90. cv2.imwrite(os.path.join(save_path, str(index).zfill(6) +'.jpg'), img_processed)
  91. if __name__ == '__main__':
  92. args = parse_args()
  93. # Set cuda
  94. if args.cuda and torch.cuda.is_available():
  95. print('use cuda')
  96. device = torch.device("cuda")
  97. else:
  98. device = torch.device("cpu")
  99. # Build config
  100. cfg = build_config(args)
  101. # Build data processor
  102. transform = build_transform(cfg, is_train=False)
  103. # Build dataset
  104. dataset = build_dataset(args, cfg, transform, is_train=False)
  105. # Build model
  106. model = build_model(args, cfg, is_val=False)
  107. # Load trained weight
  108. model = load_weight(model, args.weight, args.fuse_conv_bn, args.rep_conv)
  109. model.to(device).eval()
  110. # Compute FLOPs and Params
  111. model_copy = deepcopy(model)
  112. model_copy.trainable = False
  113. model_copy.eval()
  114. compute_flops(model_copy, cfg.test_img_size, device)
  115. del model_copy
  116. print("================= DETECT =================")
  117. # Color for beautiful visualization
  118. np.random.seed(0)
  119. class_colors = [(np.random.randint(255),
  120. np.random.randint(255),
  121. np.random.randint(255))
  122. for _ in range(cfg.num_classes)]
  123. # Run
  124. test_det(args = args,
  125. model = model,
  126. device = device,
  127. dataset = dataset,
  128. transform = transform,
  129. class_colors = class_colors,
  130. class_names = cfg.class_labels,
  131. )