test.py 8.2 KB

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