test.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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.data_augment import build_transform
  10. # load some utils
  11. from utils.misc import build_dataset, load_weight
  12. from utils.com_flops_params import FLOPs_and_Params
  13. from utils.box_ops import rescale_bboxes
  14. from utils import fuse_conv_bn
  15. from models import build_model
  16. from config import build_model_config, build_trans_config
  17. def parse_args():
  18. parser = argparse.ArgumentParser(description='YOLO-Tutorial')
  19. # basic
  20. parser.add_argument('-size', '--img_size', default=640, type=int,
  21. help='the max size of input image')
  22. parser.add_argument('--show', action='store_true', default=False,
  23. help='show the visulization results.')
  24. parser.add_argument('--save', action='store_true', default=False,
  25. help='save the visulization results.')
  26. parser.add_argument('--cuda', action='store_true', default=False,
  27. help='use cuda.')
  28. parser.add_argument('--save_folder', default='det_results/', type=str,
  29. help='Dir to save results')
  30. parser.add_argument('-vs', '--visual_threshold', default=0.3, type=float,
  31. help='Final confidence threshold')
  32. parser.add_argument('-ws', '--window_scale', default=1.0, type=float,
  33. help='resize window of cv2 for visualization.')
  34. # model
  35. parser.add_argument('-m', '--model', default='yolov1', type=str,
  36. choices=['yolov1', 'yolov2', 'yolov3', 'yolov4', 'yolox'], help='build yolo')
  37. parser.add_argument('--weight', default=None,
  38. type=str, help='Trained state_dict file path to open')
  39. parser.add_argument('-ct', '--conf_thresh', default=0.1, type=float,
  40. help='confidence threshold')
  41. parser.add_argument('-nt', '--nms_thresh', default=0.5, type=float,
  42. help='NMS threshold')
  43. parser.add_argument('--topk', default=100, type=int,
  44. help='topk candidates for testing')
  45. parser.add_argument('--fuse_conv_bn', action='store_true', default=False,
  46. help='fuse conv and bn')
  47. parser.add_argument("--no_decode", action="store_true", default=False,
  48. help="not decode in inference or yes")
  49. # dataset
  50. parser.add_argument('--root', default='/mnt/share/ssd2/dataset',
  51. help='data root')
  52. parser.add_argument('-d', '--dataset', default='coco',
  53. help='coco, voc.')
  54. parser.add_argument('--min_box_size', default=8.0, type=float,
  55. help='min size of target bounding box.')
  56. parser.add_argument('--mosaic', default=None, type=float,
  57. help='mosaic augmentation.')
  58. parser.add_argument('--mixup', default=None, type=float,
  59. help='mixup augmentation.')
  60. return parser.parse_args()
  61. def plot_bbox_labels(img, bbox, label=None, cls_color=None, text_scale=0.4):
  62. x1, y1, x2, y2 = bbox
  63. x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
  64. t_size = cv2.getTextSize(label, 0, fontScale=1, thickness=2)[0]
  65. # plot bbox
  66. cv2.rectangle(img, (x1, y1), (x2, y2), cls_color, 2)
  67. if label is not None:
  68. # plot title bbox
  69. cv2.rectangle(img, (x1, y1-t_size[1]), (int(x1 + t_size[0] * text_scale), y1), cls_color, -1)
  70. # put the test on the title bbox
  71. cv2.putText(img, label, (int(x1), int(y1 - 5)), 0, text_scale, (0, 0, 0), 1, lineType=cv2.LINE_AA)
  72. return img
  73. def visualize(img,
  74. bboxes,
  75. scores,
  76. labels,
  77. vis_thresh,
  78. class_colors,
  79. class_names,
  80. class_indexs=None,
  81. dataset_name='voc'):
  82. ts = 0.4
  83. for i, bbox in enumerate(bboxes):
  84. if scores[i] > vis_thresh:
  85. cls_id = int(labels[i])
  86. if dataset_name == 'coco':
  87. cls_color = class_colors[cls_id]
  88. cls_id = class_indexs[cls_id]
  89. else:
  90. cls_color = class_colors[cls_id]
  91. mess = '%s: %.2f' % (class_names[cls_id], scores[i])
  92. img = plot_bbox_labels(img, bbox, mess, cls_color, text_scale=ts)
  93. return img
  94. @torch.no_grad()
  95. def test(args,
  96. model,
  97. device,
  98. dataset,
  99. transforms=None,
  100. class_colors=None,
  101. class_names=None,
  102. class_indexs=None):
  103. num_images = len(dataset)
  104. save_path = os.path.join('det_results/', args.dataset, args.model)
  105. os.makedirs(save_path, exist_ok=True)
  106. for index in range(num_images):
  107. print('Testing image {:d}/{:d}....'.format(index+1, num_images))
  108. image, _ = dataset.pull_image(index)
  109. orig_h, orig_w, _ = image.shape
  110. # prepare
  111. x, _, deltas = transforms(image)
  112. x = x.unsqueeze(0).to(device) / 255.
  113. t0 = time.time()
  114. # inference
  115. bboxes, scores, labels = model(x)
  116. print("detection time used ", time.time() - t0, "s")
  117. # rescale bboxes
  118. origin_img_size = [orig_h, orig_w]
  119. cur_img_size = [*x.shape[-2:]]
  120. bboxes = rescale_bboxes(bboxes, origin_img_size, cur_img_size, deltas)
  121. # vis detection
  122. img_processed = visualize(
  123. img=image,
  124. bboxes=bboxes,
  125. scores=scores,
  126. labels=labels,
  127. vis_thresh=args.visual_threshold,
  128. class_colors=class_colors,
  129. class_names=class_names,
  130. class_indexs=class_indexs,
  131. dataset_name=args.dataset)
  132. if args.show:
  133. h, w = img_processed.shape[:2]
  134. sw, sh = int(w*args.window_scale), int(h*args.window_scale)
  135. cv2.namedWindow('detection', 0)
  136. cv2.resizeWindow('detection', sw, sh)
  137. cv2.imshow('detection', img_processed)
  138. cv2.waitKey(0)
  139. if args.save:
  140. # save result
  141. cv2.imwrite(os.path.join(save_path, str(index).zfill(6) +'.jpg'), img_processed)
  142. if __name__ == '__main__':
  143. args = parse_args()
  144. # cuda
  145. if args.cuda:
  146. print('use cuda')
  147. device = torch.device("cuda")
  148. else:
  149. device = torch.device("cpu")
  150. # config
  151. model_cfg = build_model_config(args)
  152. trans_cfg = build_trans_config(model_cfg['trans_type'])
  153. # dataset and evaluator
  154. dataset, dataset_info, evaluator = build_dataset(args, trans_cfg, device, is_train=False)
  155. num_classes, class_names, class_indexs = dataset_info
  156. np.random.seed(0)
  157. class_colors = [(np.random.randint(255),
  158. np.random.randint(255),
  159. np.random.randint(255)) for _ in range(num_classes)]
  160. # build model
  161. model = build_model(args, model_cfg, device, num_classes, False)
  162. # load trained weight
  163. model = load_weight(model=model, path_to_ckpt=args.weight)
  164. model.to(device).eval()
  165. # compute FLOPs and Params
  166. model_copy = deepcopy(model)
  167. model_copy.trainable = False
  168. model_copy.eval()
  169. FLOPs_and_Params(
  170. model=model_copy,
  171. img_size=args.img_size,
  172. device=device)
  173. del model_copy
  174. # fuse conv bn
  175. if args.fuse_conv_bn:
  176. print('fuse conv and bn ...')
  177. model = fuse_conv_bn.fuse_conv_bn(model)
  178. # transform
  179. transform = build_transform(args.img_size, trans_cfg, is_train=False)
  180. print("================= DETECT =================")
  181. # run
  182. test(args=args,
  183. model=model,
  184. device=device,
  185. dataset=dataset,
  186. transforms=transform,
  187. class_colors=class_colors,
  188. class_names=class_names,
  189. class_indexs=class_indexs
  190. )