frcnn.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import colorsys
  2. import os
  3. import time
  4. import numpy as np
  5. import torch
  6. import torch.nn as nn
  7. from PIL import Image, ImageDraw, ImageFont
  8. from nets.frcnn import FasterRCNN
  9. from utils.utils import (cvtColor, get_classes, get_new_img_size, resize_image, preprocess_input, show_config)
  10. from utils.utils_bbox import DecodeBox
  11. #--------------------------------------------#
  12. # 使用自己训练好的模型预测需要修改2个参数
  13. # model_path和classes_path都需要修改!
  14. # 如果出现shape不匹配
  15. # 一定要注意训练时的NUM_CLASSES、
  16. # model_path和classes_path参数的修改
  17. #--------------------------------------------#
  18. class FRCNN(object):
  19. _defaults = {
  20. #--------------------------------------------------------------------------#
  21. # 使用自己训练好的模型进行预测一定要修改model_path和classes_path!
  22. # model_path指向logs文件夹下的权值文件,classes_path指向model_data下的txt
  23. #
  24. # 训练好后logs文件夹下存在多个权值文件,选择验证集损失较低的即可。
  25. # 验证集损失较低不代表mAP较高,仅代表该权值在验证集上泛化性能较好。
  26. # 如果出现shape不匹配,同时要注意训练时的model_path和classes_path参数的修改
  27. #--------------------------------------------------------------------------#
  28. "model_path" : './logs_wm/best_epoch_weights.pth',
  29. "classes_path" : './model_data/voc_classes.txt',
  30. #---------------------------------------------------------------------#
  31. # 网络的主干特征提取网络,resnet50或者vgg
  32. #---------------------------------------------------------------------#
  33. "backbone" : "resnet50",
  34. #---------------------------------------------------------------------#
  35. # 只有得分大于置信度的预测框会被保留下来
  36. #---------------------------------------------------------------------#
  37. "confidence" : 0.5,
  38. #---------------------------------------------------------------------#
  39. # 非极大抑制所用到的nms_iou大小
  40. #---------------------------------------------------------------------#
  41. "nms_iou" : 0.3,
  42. #---------------------------------------------------------------------#
  43. # 用于指定先验框的大小
  44. #---------------------------------------------------------------------#
  45. 'anchors_size' : [8, 16, 32],
  46. #-------------------------------#
  47. # 是否使用Cuda
  48. # 没有GPU可以设置成False
  49. #-------------------------------#
  50. "cuda" : True,
  51. }
  52. @classmethod
  53. def get_defaults(cls, n):
  54. if n in cls._defaults:
  55. return cls._defaults[n]
  56. else:
  57. return "Unrecognized attribute name '" + n + "'"
  58. #---------------------------------------------------#
  59. # 初始化faster RCNN
  60. #---------------------------------------------------#
  61. def __init__(self, **kwargs):
  62. self.__dict__.update(self._defaults)
  63. for name, value in kwargs.items():
  64. setattr(self, name, value)
  65. self._defaults[name] = value
  66. #---------------------------------------------------#
  67. # 获得种类和先验框的数量
  68. #---------------------------------------------------#
  69. self.class_names, self.num_classes = get_classes(self.classes_path)
  70. self.std = torch.Tensor([0.1, 0.1, 0.2, 0.2]).repeat(self.num_classes + 1)[None]
  71. if self.cuda:
  72. self.std = self.std.cuda()
  73. self.bbox_util = DecodeBox(self.std, self.num_classes)
  74. #---------------------------------------------------#
  75. # 画框设置不同的颜色
  76. #---------------------------------------------------#
  77. hsv_tuples = [(x / self.num_classes, 1., 1.) for x in range(self.num_classes)]
  78. self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
  79. self.colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), self.colors))
  80. self.generate()
  81. show_config(**self._defaults)
  82. #---------------------------------------------------#
  83. # 载入模型
  84. #---------------------------------------------------#
  85. def generate(self):
  86. #-------------------------------#
  87. # 载入模型与权值
  88. #-------------------------------#
  89. self.net = FasterRCNN(self.num_classes, "predict", anchor_scales = self.anchors_size, backbone = self.backbone)
  90. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  91. self.net.load_state_dict(torch.load(self.model_path, map_location=device))
  92. self.net = self.net.eval()
  93. print('{} model, anchors, and classes loaded.'.format(self.model_path))
  94. if self.cuda:
  95. self.net = nn.DataParallel(self.net)
  96. self.net = self.net.cuda()
  97. #---------------------------------------------------#
  98. # 检测图片
  99. #---------------------------------------------------#
  100. def detect_image(self, image, crop = False, count = False):
  101. #---------------------------------------------------#
  102. # 计算输入图片的高和宽
  103. #---------------------------------------------------#
  104. image_shape = np.array(np.shape(image)[0:2])
  105. #---------------------------------------------------#
  106. # 计算resize后的图片的大小,resize后的图片短边为600
  107. #---------------------------------------------------#
  108. input_shape = get_new_img_size(image_shape[0], image_shape[1])
  109. #---------------------------------------------------------#
  110. # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。
  111. # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB
  112. #---------------------------------------------------------#
  113. image = cvtColor(image)
  114. #---------------------------------------------------------#
  115. # 给原图像进行resize,resize到短边为600的大小上
  116. #---------------------------------------------------------#
  117. image_data = resize_image(image, [input_shape[1], input_shape[0]])
  118. #---------------------------------------------------------#
  119. # 添加上batch_size维度
  120. #---------------------------------------------------------#
  121. image_data = np.expand_dims(np.transpose(preprocess_input(np.array(image_data, dtype='float32')), (2, 0, 1)), 0)
  122. with torch.no_grad():
  123. images = torch.from_numpy(image_data)
  124. if self.cuda:
  125. images = images.cuda()
  126. #-------------------------------------------------------------#
  127. # roi_cls_locs 建议框的调整参数
  128. # roi_scores 建议框的种类得分
  129. # rois 建议框的坐标
  130. #-------------------------------------------------------------#
  131. roi_cls_locs, roi_scores, rois, _ = self.net(images)
  132. #-------------------------------------------------------------#
  133. # 利用classifier的预测结果对建议框进行解码,获得预测框
  134. #-------------------------------------------------------------#
  135. results = self.bbox_util.forward(roi_cls_locs, roi_scores, rois, image_shape, input_shape,
  136. nms_iou = self.nms_iou, confidence = self.confidence)
  137. #---------------------------------------------------------#
  138. # 如果没有检测出物体,返回原图
  139. #---------------------------------------------------------#
  140. if len(results[0]) <= 0:
  141. return image
  142. top_label = np.array(results[0][:, 5], dtype = 'int32')
  143. top_conf = results[0][:, 4]
  144. top_boxes = results[0][:, :4]
  145. #---------------------------------------------------------#
  146. # 设置字体与边框厚度
  147. #---------------------------------------------------------#
  148. font = ImageFont.truetype(font='./model_data/simhei.ttf', size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))
  149. thickness = int(max((image.size[0] + image.size[1]) // np.mean(input_shape), 1))
  150. #---------------------------------------------------------#
  151. # 计数
  152. #---------------------------------------------------------#
  153. if count:
  154. print("top_label:", top_label)
  155. classes_nums = np.zeros([self.num_classes])
  156. for i in range(self.num_classes):
  157. num = np.sum(top_label == i)
  158. if num > 0:
  159. print(self.class_names[i], " : ", num)
  160. classes_nums[i] = num
  161. print("classes_nums:", classes_nums)
  162. #---------------------------------------------------------#
  163. # 是否进行目标的裁剪
  164. #---------------------------------------------------------#
  165. if crop:
  166. for i, c in list(enumerate(top_label)):
  167. top, left, bottom, right = top_boxes[i]
  168. top = max(0, np.floor(top).astype('int32'))
  169. left = max(0, np.floor(left).astype('int32'))
  170. bottom = min(image.size[1], np.floor(bottom).astype('int32'))
  171. right = min(image.size[0], np.floor(right).astype('int32'))
  172. dir_save_path = "img_crop"
  173. if not os.path.exists(dir_save_path):
  174. os.makedirs(dir_save_path)
  175. crop_image = image.crop([left, top, right, bottom])
  176. crop_image.save(os.path.join(dir_save_path, "crop_" + str(i) + ".png"), quality=95, subsampling=0)
  177. print("save crop_" + str(i) + ".png to " + dir_save_path)
  178. #---------------------------------------------------------#
  179. # 图像绘制
  180. #---------------------------------------------------------#
  181. for i, c in list(enumerate(top_label)):
  182. predicted_class = self.class_names[int(c)]
  183. box = top_boxes[i]
  184. score = top_conf[i]
  185. top, left, bottom, right = box
  186. top = max(0, np.floor(top).astype('int32'))
  187. left = max(0, np.floor(left).astype('int32'))
  188. bottom = min(image.size[1], np.floor(bottom).astype('int32'))
  189. right = min(image.size[0], np.floor(right).astype('int32'))
  190. label = '{} {:.2f}'.format(predicted_class, score)
  191. draw = ImageDraw.Draw(image)
  192. label_bbox = draw.textbbox((0, 0), label, font=font)
  193. label_size = (label_bbox[2] - label_bbox[0], label_bbox[3] - label_bbox[1])
  194. label = label.encode('utf-8')
  195. # print(label, top, left, bottom, right)
  196. if top - label_size[1] >= 0:
  197. text_origin = np.array([left, top - label_size[1]])
  198. else:
  199. text_origin = np.array([left, top + 1])
  200. for i in range(thickness):
  201. draw.rectangle([left + i, top + i, right - i, bottom - i], outline=self.colors[c])
  202. draw.rectangle([tuple(text_origin), tuple(text_origin + label_size)], fill=self.colors[c])
  203. draw.text(text_origin, str(label,'UTF-8'), fill=(0, 0, 0), font=font)
  204. del draw
  205. return image
  206. def get_FPS(self, image, test_interval):
  207. #---------------------------------------------------#
  208. # 计算输入图片的高和宽
  209. #---------------------------------------------------#
  210. image_shape = np.array(np.shape(image)[0:2])
  211. input_shape = get_new_img_size(image_shape[0], image_shape[1])
  212. #---------------------------------------------------------#
  213. # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。
  214. # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB
  215. #---------------------------------------------------------#
  216. image = cvtColor(image)
  217. #---------------------------------------------------------#
  218. # 给原图像进行resize,resize到短边为600的大小上
  219. #---------------------------------------------------------#
  220. image_data = resize_image(image, [input_shape[1], input_shape[0]])
  221. #---------------------------------------------------------#
  222. # 添加上batch_size维度
  223. #---------------------------------------------------------#
  224. image_data = np.expand_dims(np.transpose(preprocess_input(np.array(image_data, dtype='float32')), (2, 0, 1)), 0)
  225. with torch.no_grad():
  226. images = torch.from_numpy(image_data)
  227. if self.cuda:
  228. images = images.cuda()
  229. roi_cls_locs, roi_scores, rois, _ = self.net(images)
  230. #-------------------------------------------------------------#
  231. # 利用classifier的预测结果对建议框进行解码,获得预测框
  232. #-------------------------------------------------------------#
  233. results = self.bbox_util.forward(roi_cls_locs, roi_scores, rois, image_shape, input_shape,
  234. nms_iou = self.nms_iou, confidence = self.confidence)
  235. t1 = time.time()
  236. for _ in range(test_interval):
  237. with torch.no_grad():
  238. roi_cls_locs, roi_scores, rois, _ = self.net(images)
  239. #-------------------------------------------------------------#
  240. # 利用classifier的预测结果对建议框进行解码,获得预测框
  241. #-------------------------------------------------------------#
  242. results = self.bbox_util.forward(roi_cls_locs, roi_scores, rois, image_shape, input_shape,
  243. nms_iou = self.nms_iou, confidence = self.confidence)
  244. t2 = time.time()
  245. tact_time = (t2 - t1) / test_interval
  246. return tact_time
  247. #---------------------------------------------------#
  248. # 检测图片
  249. #---------------------------------------------------#
  250. def get_map_txt(self, image_id, image, class_names, map_out_path):
  251. f = open(os.path.join(map_out_path, "detection-results/"+image_id+".txt"),"w")
  252. #---------------------------------------------------#
  253. # 计算输入图片的高和宽
  254. #---------------------------------------------------#
  255. image_shape = np.array(np.shape(image)[0:2])
  256. input_shape = get_new_img_size(image_shape[0], image_shape[1])
  257. #---------------------------------------------------------#
  258. # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。
  259. # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB
  260. #---------------------------------------------------------#
  261. image = cvtColor(image)
  262. #---------------------------------------------------------#
  263. # 给原图像进行resize,resize到短边为600的大小上
  264. #---------------------------------------------------------#
  265. image_data = resize_image(image, [input_shape[1], input_shape[0]])
  266. #---------------------------------------------------------#
  267. # 添加上batch_size维度
  268. #---------------------------------------------------------#
  269. image_data = np.expand_dims(np.transpose(preprocess_input(np.array(image_data, dtype='float32')), (2, 0, 1)), 0)
  270. with torch.no_grad():
  271. images = torch.from_numpy(image_data)
  272. if self.cuda:
  273. images = images.cuda()
  274. roi_cls_locs, roi_scores, rois, _ = self.net(images)
  275. #-------------------------------------------------------------#
  276. # 利用classifier的预测结果对建议框进行解码,获得预测框
  277. #-------------------------------------------------------------#
  278. results = self.bbox_util.forward(roi_cls_locs, roi_scores, rois, image_shape, input_shape,
  279. nms_iou = self.nms_iou, confidence = self.confidence)
  280. #--------------------------------------#
  281. # 如果没有检测到物体,则返回原图
  282. #--------------------------------------#
  283. if len(results[0]) <= 0:
  284. return
  285. top_label = np.array(results[0][:, 5], dtype = 'int32')
  286. top_conf = results[0][:, 4]
  287. top_boxes = results[0][:, :4]
  288. for i, c in list(enumerate(top_label)):
  289. predicted_class = self.class_names[int(c)]
  290. box = top_boxes[i]
  291. score = str(top_conf[i])
  292. top, left, bottom, right = box
  293. if predicted_class not in class_names:
  294. continue
  295. f.write("%s %s %s %s %s %s\n" % (predicted_class, score[:6], str(int(left)), str(int(top)), str(int(right)),str(int(bottom))))
  296. f.close()
  297. return