deeplabv3p.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import
  15. import os.path as osp
  16. import numpy as np
  17. import tqdm
  18. import math
  19. import cv2
  20. from multiprocessing.pool import ThreadPool
  21. import paddle.fluid as fluid
  22. import paddlex.utils.logging as logging
  23. import paddlex
  24. from paddlex.cv.transforms import arrange_transforms
  25. from paddlex.cv.datasets import generate_minibatch
  26. from paddlex.cv.transforms.seg_transforms import Compose
  27. from collections import OrderedDict
  28. from .base import BaseAPI
  29. from .utils.seg_eval import ConfusionMatrix
  30. from .utils.visualize import visualize_segmentation
  31. class DeepLabv3p(BaseAPI):
  32. """实现DeepLabv3+网络的构建并进行训练、评估、预测和模型导出。
  33. Args:
  34. num_classes (int): 类别数。
  35. backbone (str): DeepLabv3+的backbone网络,实现特征图的计算,取值范围为['Xception65', 'Xception41',
  36. 'MobileNetV2_x0.25', 'MobileNetV2_x0.5', 'MobileNetV2_x1.0', 'MobileNetV2_x1.5',
  37. 'MobileNetV2_x2.0', 'MobileNetV3_large_x1_0_ssld']。默认'MobileNetV2_x1.0'。
  38. output_stride (int): backbone 输出特征图相对于输入的下采样倍数,一般取值为8或16。默认16。
  39. aspp_with_sep_conv (bool): 在asspp模块是否采用separable convolutions。默认True。
  40. decoder_use_sep_conv (bool): decoder模块是否采用separable convolutions。默认True。
  41. encoder_with_aspp (bool): 是否在encoder阶段采用aspp模块。默认True。
  42. enable_decoder (bool): 是否使用decoder模块。默认True。
  43. use_bce_loss (bool): 是否使用bce loss作为网络的损失函数,只能用于两类分割。可与dice loss同时使用。默认False。
  44. use_dice_loss (bool): 是否使用dice loss作为网络的损失函数,只能用于两类分割,可与bce loss同时使用,
  45. 当use_bce_loss和use_dice_loss都为False时,使用交叉熵损失函数。默认False。
  46. class_weight (list/str): 交叉熵损失函数各类损失的权重。当class_weight为list的时候,长度应为
  47. num_classes。当class_weight为str时, weight.lower()应为'dynamic',这时会根据每一轮各类像素的比重
  48. 自行计算相应的权重,每一类的权重为:每类的比例 * num_classes。class_weight取默认值None时,各类的权重1,
  49. 即平时使用的交叉熵损失函数。
  50. ignore_index (int): label上忽略的值,label为ignore_index的像素不参与损失函数的计算。默认255。
  51. pooling_crop_size (list): 当backbone为MobileNetV3_large_x1_0_ssld时,需设置为训练过程中模型输入大小, 格式为[W, H]。
  52. 在encoder模块中获取图像平均值时被用到,若为None,则直接求平均值;若为模型输入大小,则使用'pool'算子得到平均值。
  53. 默认值为None。
  54. input_channel (int): 输入图像通道数。默认值3。
  55. Raises:
  56. ValueError: use_bce_loss或use_dice_loss为真且num_calsses > 2。
  57. ValueError: backbone取值不在['Xception65', 'Xception41', 'MobileNetV2_x0.25',
  58. 'MobileNetV2_x0.5', 'MobileNetV2_x1.0', 'MobileNetV2_x1.5', 'MobileNetV2_x2.0', 'MobileNetV3_large_x1_0_ssld']之内。
  59. ValueError: class_weight为list, 但长度不等于num_class。
  60. class_weight为str, 但class_weight.low()不等于dynamic。
  61. TypeError: class_weight不为None时,其类型不是list或str。
  62. """
  63. def __init__(self,
  64. num_classes=2,
  65. backbone='MobileNetV2_x1.0',
  66. output_stride=16,
  67. aspp_with_sep_conv=True,
  68. decoder_use_sep_conv=True,
  69. encoder_with_aspp=True,
  70. enable_decoder=True,
  71. use_bce_loss=False,
  72. use_dice_loss=False,
  73. class_weight=None,
  74. ignore_index=255,
  75. pooling_crop_size=None,
  76. input_channel=3):
  77. self.init_params = locals()
  78. super(DeepLabv3p, self).__init__('segmenter')
  79. # dice_loss或bce_loss只适用两类分割中
  80. if num_classes > 2 and (use_bce_loss or use_dice_loss):
  81. raise ValueError(
  82. "dice loss and bce loss is only applicable to binary classfication"
  83. )
  84. self.output_stride = output_stride
  85. if backbone not in [
  86. 'Xception65', 'Xception41', 'MobileNetV2_x0.25',
  87. 'MobileNetV2_x0.5', 'MobileNetV2_x1.0', 'MobileNetV2_x1.5',
  88. 'MobileNetV2_x2.0', 'MobileNetV3_large_x1_0_ssld'
  89. ]:
  90. raise ValueError(
  91. "backbone: {} is set wrong. it should be one of "
  92. "('Xception65', 'Xception41', 'MobileNetV2_x0.25', 'MobileNetV2_x0.5',"
  93. " 'MobileNetV2_x1.0', 'MobileNetV2_x1.5', 'MobileNetV2_x2.0', 'MobileNetV3_large_x1_0_ssld')".
  94. format(backbone))
  95. if class_weight is not None:
  96. if isinstance(class_weight, list):
  97. if len(class_weight) != num_classes:
  98. raise ValueError(
  99. "Length of class_weight should be equal to number of classes"
  100. )
  101. elif isinstance(class_weight, str):
  102. if class_weight.lower() != 'dynamic':
  103. raise ValueError(
  104. "if class_weight is string, must be dynamic!")
  105. else:
  106. raise TypeError(
  107. 'Expect class_weight is a list or string but receive {}'.
  108. format(type(class_weight)))
  109. self.backbone = backbone
  110. self.num_classes = num_classes
  111. self.use_bce_loss = use_bce_loss
  112. self.use_dice_loss = use_dice_loss
  113. self.class_weight = class_weight
  114. self.ignore_index = ignore_index
  115. self.aspp_with_sep_conv = aspp_with_sep_conv
  116. self.decoder_use_sep_conv = decoder_use_sep_conv
  117. self.encoder_with_aspp = encoder_with_aspp
  118. self.enable_decoder = enable_decoder
  119. self.labels = None
  120. self.sync_bn = True
  121. self.fixed_input_shape = None
  122. self.pooling_stride = [1, 1]
  123. self.pooling_crop_size = pooling_crop_size
  124. self.aspp_with_se = False
  125. self.se_use_qsigmoid = False
  126. self.aspp_convs_filters = 256
  127. self.aspp_with_concat_projection = True
  128. self.add_image_level_feature = True
  129. self.use_sum_merge = False
  130. self.conv_filters = 256
  131. self.output_is_logits = False
  132. self.backbone_lr_mult_list = None
  133. if 'MobileNetV3' in backbone:
  134. self.output_stride = 32
  135. self.pooling_stride = (4, 5)
  136. self.aspp_with_se = True
  137. self.se_use_qsigmoid = True
  138. self.aspp_convs_filters = 128
  139. self.aspp_with_concat_projection = False
  140. self.add_image_level_feature = False
  141. self.use_sum_merge = True
  142. self.output_is_logits = True
  143. if self.output_is_logits:
  144. self.conv_filters = self.num_classes
  145. self.backbone_lr_mult_list = [0.15, 0.35, 0.65, 0.85, 1]
  146. self.input_channel = input_channel
  147. def _get_backbone(self, backbone):
  148. def mobilenetv2(backbone):
  149. # backbone: xception结构配置
  150. # output_stride:下采样倍数
  151. # end_points: mobilenetv2的block数
  152. # decode_point: 从mobilenetv2中引出分支所在block数, 作为decoder输入
  153. if '0.25' in backbone:
  154. scale = 0.25
  155. elif '0.5' in backbone:
  156. scale = 0.5
  157. elif '1.0' in backbone:
  158. scale = 1.0
  159. elif '1.5' in backbone:
  160. scale = 1.5
  161. elif '2.0' in backbone:
  162. scale = 2.0
  163. end_points = 18
  164. decode_points = 4
  165. return paddlex.cv.nets.MobileNetV2(
  166. scale=scale,
  167. output_stride=self.output_stride,
  168. end_points=end_points,
  169. decode_points=decode_points)
  170. def xception(backbone):
  171. # decode_point: 从Xception中引出分支所在block数,作为decoder输入
  172. # end_point:Xception的block数
  173. if '65' in backbone:
  174. decode_points = 2
  175. end_points = 21
  176. layers = 65
  177. if '41' in backbone:
  178. decode_points = 2
  179. end_points = 13
  180. layers = 41
  181. if '71' in backbone:
  182. decode_points = 3
  183. end_points = 23
  184. layers = 71
  185. return paddlex.cv.nets.Xception(
  186. layers=layers,
  187. output_stride=self.output_stride,
  188. end_points=end_points,
  189. decode_points=decode_points)
  190. def mobilenetv3(backbone):
  191. scale = 1.0
  192. lr_mult_list = self.backbone_lr_mult_list
  193. return paddlex.cv.nets.MobileNetV3(
  194. scale=scale,
  195. model_name='large',
  196. output_stride=self.output_stride,
  197. lr_mult_list=lr_mult_list,
  198. for_seg=True)
  199. if 'Xception' in backbone:
  200. return xception(backbone)
  201. elif 'MobileNetV2' in backbone:
  202. return mobilenetv2(backbone)
  203. elif 'MobileNetV3' in backbone:
  204. return mobilenetv3(backbone)
  205. def build_net(self, mode='train'):
  206. model = paddlex.cv.nets.segmentation.DeepLabv3p(
  207. self.num_classes,
  208. mode=mode,
  209. backbone=self._get_backbone(self.backbone),
  210. output_stride=self.output_stride,
  211. aspp_with_sep_conv=self.aspp_with_sep_conv,
  212. decoder_use_sep_conv=self.decoder_use_sep_conv,
  213. encoder_with_aspp=self.encoder_with_aspp,
  214. enable_decoder=self.enable_decoder,
  215. use_bce_loss=self.use_bce_loss,
  216. use_dice_loss=self.use_dice_loss,
  217. class_weight=self.class_weight,
  218. ignore_index=self.ignore_index,
  219. fixed_input_shape=self.fixed_input_shape,
  220. pooling_stride=self.pooling_stride,
  221. pooling_crop_size=self.pooling_crop_size,
  222. aspp_with_se=self.aspp_with_se,
  223. se_use_qsigmoid=self.se_use_qsigmoid,
  224. aspp_convs_filters=self.aspp_convs_filters,
  225. aspp_with_concat_projection=self.aspp_with_concat_projection,
  226. add_image_level_feature=self.add_image_level_feature,
  227. use_sum_merge=self.use_sum_merge,
  228. conv_filters=self.conv_filters,
  229. output_is_logits=self.output_is_logits,
  230. input_channel=self.input_channel)
  231. inputs = model.generate_inputs()
  232. model_out = model.build_net(inputs)
  233. outputs = OrderedDict()
  234. if mode == 'train':
  235. self.optimizer.minimize(model_out)
  236. outputs['loss'] = model_out
  237. else:
  238. outputs['pred'] = model_out[0]
  239. outputs['logit'] = model_out[1]
  240. return inputs, outputs
  241. def default_optimizer(self,
  242. learning_rate,
  243. num_epochs,
  244. num_steps_each_epoch,
  245. lr_decay_power=0.9):
  246. decay_step = num_epochs * num_steps_each_epoch
  247. lr_decay = fluid.layers.polynomial_decay(
  248. learning_rate,
  249. decay_step,
  250. end_learning_rate=0,
  251. power=lr_decay_power)
  252. optimizer = fluid.optimizer.Momentum(
  253. lr_decay,
  254. momentum=0.9,
  255. regularization=fluid.regularizer.L2Decay(
  256. regularization_coeff=4e-05))
  257. return optimizer
  258. def train(self,
  259. num_epochs,
  260. train_dataset,
  261. train_batch_size=2,
  262. eval_dataset=None,
  263. save_interval_epochs=1,
  264. log_interval_steps=2,
  265. save_dir='output',
  266. pretrain_weights='IMAGENET',
  267. optimizer=None,
  268. learning_rate=0.01,
  269. lr_decay_power=0.9,
  270. use_vdl=False,
  271. sensitivities_file=None,
  272. eval_metric_loss=0.05,
  273. early_stop=False,
  274. early_stop_patience=5,
  275. resume_checkpoint=None):
  276. """训练。
  277. Args:
  278. num_epochs (int): 训练迭代轮数。
  279. train_dataset (paddlex.datasets): 训练数据读取器。
  280. train_batch_size (int): 训练数据batch大小。同时作为验证数据batch大小。默认为2。
  281. eval_dataset (paddlex.datasets): 评估数据读取器。
  282. save_interval_epochs (int): 模型保存间隔(单位:迭代轮数)。默认为1。
  283. log_interval_steps (int): 训练日志输出间隔(单位:迭代次数)。默认为2。
  284. save_dir (str): 模型保存路径。默认'output'。
  285. pretrain_weights (str): 若指定为路径时,则加载路径下预训练模型;若为字符串'IMAGENET',
  286. 则自动下载在ImageNet图片数据上预训练的模型权重;若为字符串'COCO',
  287. 则自动下载在COCO数据集上预训练的模型权重;若为字符串'CITYSCAPES',
  288. 则自动下载在CITYSCAPES数据集上预训练的模型权重;若为None,则不使用预训练模型。默认'IMAGENET。
  289. optimizer (paddle.fluid.optimizer): 优化器。当该参数为None时,使用默认的优化器:使用
  290. fluid.optimizer.Momentum优化方法,polynomial的学习率衰减策略。
  291. learning_rate (float): 默认优化器的初始学习率。默认0.01。
  292. lr_decay_power (float): 默认优化器学习率衰减指数。默认0.9。
  293. use_vdl (bool): 是否使用VisualDL进行可视化。默认False。
  294. sensitivities_file (str): 若指定为路径时,则加载路径下敏感度信息进行裁剪;若为字符串'DEFAULT',
  295. 则自动下载在Cityscapes图片数据上获得的敏感度信息进行裁剪;若为None,则不进行裁剪。默认为None。
  296. eval_metric_loss (float): 可容忍的精度损失。默认为0.05。
  297. early_stop (bool): 是否使用提前终止训练策略。默认值为False。
  298. early_stop_patience (int): 当使用提前终止训练策略时,如果验证集精度在`early_stop_patience`个epoch内
  299. 连续下降或持平,则终止训练。默认值为5。
  300. resume_checkpoint (str): 恢复训练时指定上次训练保存的模型路径。若为None,则不会恢复训练。默认值为None。
  301. Raises:
  302. ValueError: 模型从inference model进行加载。
  303. """
  304. if not self.trainable:
  305. raise ValueError("Model is not trainable from load_model method.")
  306. self.labels = train_dataset.labels
  307. if optimizer is None:
  308. num_steps_each_epoch = train_dataset.num_samples // train_batch_size
  309. optimizer = self.default_optimizer(
  310. learning_rate=learning_rate,
  311. num_epochs=num_epochs,
  312. num_steps_each_epoch=num_steps_each_epoch,
  313. lr_decay_power=lr_decay_power)
  314. self.optimizer = optimizer
  315. # 构建训练、验证、预测网络
  316. self.build_program()
  317. # 初始化网络权重
  318. self.net_initialize(
  319. startup_prog=fluid.default_startup_program(),
  320. pretrain_weights=pretrain_weights,
  321. save_dir=save_dir,
  322. sensitivities_file=sensitivities_file,
  323. eval_metric_loss=eval_metric_loss,
  324. resume_checkpoint=resume_checkpoint)
  325. # 训练
  326. self.train_loop(
  327. num_epochs=num_epochs,
  328. train_dataset=train_dataset,
  329. train_batch_size=train_batch_size,
  330. eval_dataset=eval_dataset,
  331. save_interval_epochs=save_interval_epochs,
  332. log_interval_steps=log_interval_steps,
  333. save_dir=save_dir,
  334. use_vdl=use_vdl,
  335. early_stop=early_stop,
  336. early_stop_patience=early_stop_patience)
  337. def evaluate(self,
  338. eval_dataset,
  339. batch_size=1,
  340. epoch_id=None,
  341. return_details=False):
  342. """评估。
  343. Args:
  344. eval_dataset (paddlex.datasets): 评估数据读取器。
  345. batch_size (int): 评估时的batch大小。默认1。
  346. epoch_id (int): 当前评估模型所在的训练轮数。
  347. return_details (bool): 是否返回详细信息。默认False。
  348. Returns:
  349. dict: 当return_details为False时,返回dict。包含关键字:'miou'、'category_iou'、'macc'、
  350. 'category_acc'和'kappa',分别表示平均iou、各类别iou、平均准确率、各类别准确率和kappa系数。
  351. tuple (metrics, eval_details):当return_details为True时,增加返回dict (eval_details),
  352. 包含关键字:'confusion_matrix',表示评估的混淆矩阵。
  353. """
  354. arrange_transforms(
  355. model_type=self.model_type,
  356. class_name=self.__class__.__name__,
  357. transforms=eval_dataset.transforms,
  358. mode='eval')
  359. total_steps = math.ceil(eval_dataset.num_samples * 1.0 / batch_size)
  360. conf_mat = ConfusionMatrix(self.num_classes, streaming=True)
  361. data_generator = eval_dataset.generator(
  362. batch_size=batch_size, drop_last=False)
  363. if not hasattr(self, 'parallel_test_prog'):
  364. with fluid.scope_guard(self.scope):
  365. self.parallel_test_prog = fluid.CompiledProgram(
  366. self.test_prog).with_data_parallel(
  367. share_vars_from=self.parallel_train_prog)
  368. logging.info(
  369. "Start to evaluating(total_samples={}, total_steps={})...".format(
  370. eval_dataset.num_samples, total_steps))
  371. for step, data in tqdm.tqdm(
  372. enumerate(data_generator()), total=total_steps):
  373. images = np.array([d[0] for d in data])
  374. im_info = [d[1] for d in data]
  375. labels = [d[2] for d in data]
  376. num_samples = images.shape[0]
  377. if num_samples < batch_size:
  378. num_pad_samples = batch_size - num_samples
  379. pad_images = np.tile(images[0:1], (num_pad_samples, 1, 1, 1))
  380. images = np.concatenate([images, pad_images])
  381. feed_data = {'image': images}
  382. with fluid.scope_guard(self.scope):
  383. outputs = self.exe.run(
  384. self.parallel_test_prog,
  385. feed=feed_data,
  386. fetch_list=list(self.test_outputs.values()),
  387. return_numpy=True)
  388. pred = outputs[0]
  389. if num_samples < batch_size:
  390. pred = pred[0:num_samples]
  391. for i in range(num_samples):
  392. one_pred = np.squeeze(pred[i]).astype('uint8')
  393. one_label = labels[i]
  394. for info in im_info[i][::-1]:
  395. if info[0] == 'resize':
  396. w, h = info[1][1], info[1][0]
  397. one_pred = cv2.resize(one_pred, (w, h),
  398. cv2.INTER_NEAREST)
  399. elif info[0] == 'padding':
  400. w, h = info[1][1], info[1][0]
  401. one_pred = one_pred[0:h, 0:w]
  402. one_pred = one_pred.astype('int64')
  403. one_pred = one_pred[np.newaxis, :, :, np.newaxis]
  404. one_label = one_label[np.newaxis, np.newaxis, :, :]
  405. mask = one_label != self.ignore_index
  406. conf_mat.calculate(pred=one_pred, label=one_label, ignore=mask)
  407. _, iou = conf_mat.mean_iou()
  408. logging.debug("[EVAL] Epoch={}, Step={}/{}, iou={}".format(
  409. epoch_id, step + 1, total_steps, iou))
  410. category_iou, miou = conf_mat.mean_iou()
  411. category_acc, oacc = conf_mat.accuracy()
  412. category_f1score = conf_mat.f1_score()
  413. metrics = OrderedDict(
  414. zip([
  415. 'miou', 'category_iou', 'oacc', 'category_acc', 'kappa',
  416. 'category_F1-score'
  417. ], [
  418. miou, category_iou, oacc, category_acc, conf_mat.kappa(),
  419. category_f1score
  420. ]))
  421. if return_details:
  422. eval_details = {
  423. 'confusion_matrix': conf_mat.confusion_matrix.tolist()
  424. }
  425. return metrics, eval_details
  426. return metrics
  427. @staticmethod
  428. def _preprocess(images,
  429. transforms,
  430. model_type,
  431. class_name,
  432. thread_pool=None,
  433. input_channel=3):
  434. arrange_transforms(
  435. model_type=model_type,
  436. class_name=class_name,
  437. transforms=transforms,
  438. mode='test',
  439. input_channel=input_channel)
  440. if thread_pool is not None:
  441. batch_data = thread_pool.map(transforms, images)
  442. else:
  443. batch_data = list()
  444. for image in images:
  445. batch_data.append(transforms(image))
  446. padding_batch = generate_minibatch(batch_data)
  447. im = np.array(
  448. [data[0] for data in padding_batch],
  449. dtype=padding_batch[0][0].dtype)
  450. im_info = [data[1] for data in padding_batch]
  451. return im, im_info
  452. @staticmethod
  453. def _postprocess(results, im_info):
  454. pred_list = list()
  455. logit_list = list()
  456. for i, (pred, logit) in enumerate(zip(results[0], results[1])):
  457. pred = pred.astype('uint8')
  458. pred = np.squeeze(pred).astype('uint8')
  459. logit = np.transpose(logit, (1, 2, 0))
  460. for info in im_info[i][::-1]:
  461. if info[0] == 'resize':
  462. w, h = info[1][1], info[1][0]
  463. pred = cv2.resize(pred, (w, h), cv2.INTER_NEAREST)
  464. logit = cv2.resize(logit, (w, h), cv2.INTER_LINEAR)
  465. elif info[0] == 'padding':
  466. w, h = info[1][1], info[1][0]
  467. pred = pred[0:h, 0:w]
  468. logit = logit[0:h, 0:w, :]
  469. pred_list.append(pred)
  470. logit_list.append(logit)
  471. preds = list()
  472. for pred, logit in zip(pred_list, logit_list):
  473. preds.append({'label_map': pred, 'score_map': logit})
  474. return preds
  475. def predict(self, img_file, transforms=None):
  476. """预测。
  477. Args:
  478. img_file(str|np.ndarray): 预测图像路径,或者是解码后的排列格式为(H, W, C)且类型为float32且为BGR格式的数组。
  479. transforms(paddlex.cv.transforms): 数据预处理操作。
  480. Returns:
  481. dict: 包含关键字'label_map'和'score_map', 'label_map'存储预测结果灰度图,
  482. 像素值表示对应的类别,'score_map'存储各类别的概率,shape=(h, w, num_classes)
  483. """
  484. if transforms is None and not hasattr(self, 'test_transforms'):
  485. raise Exception("transforms need to be defined, now is None.")
  486. if isinstance(img_file, (str, np.ndarray)):
  487. images = [img_file]
  488. else:
  489. raise Exception("img_file must be str/np.ndarray")
  490. if transforms is None:
  491. transforms = self.test_transforms
  492. input_channel = getattr(self, 'input_channel', 3)
  493. im, im_info = DeepLabv3p._preprocess(
  494. images,
  495. transforms,
  496. self.model_type,
  497. self.__class__.__name__,
  498. input_channel=input_channel)
  499. with fluid.scope_guard(self.scope):
  500. result = self.exe.run(self.test_prog,
  501. feed={'image': im},
  502. fetch_list=list(self.test_outputs.values()),
  503. use_program_cache=True)
  504. preds = DeepLabv3p._postprocess(result, im_info)
  505. return preds[0]
  506. def batch_predict(self, img_file_list, transforms=None):
  507. """预测。
  508. Args:
  509. img_file_list(list|tuple): 对列表(或元组)中的图像同时进行预测,列表中的元素可以是图像路径
  510. 也可以是解码后的排列格式为(H,W,C)且类型为float32且为BGR格式的数组。
  511. transforms(paddlex.cv.transforms): 数据预处理操作。
  512. Returns:
  513. list: 每个元素都为列表,表示各图像的预测结果。各图像的预测结果用字典表示,包含关键字'label_map'和'score_map', 'label_map'存储预测结果灰度图,
  514. 像素值表示对应的类别,'score_map'存储各类别的概率,shape=(h, w, num_classes)
  515. """
  516. if transforms is None and not hasattr(self, 'test_transforms'):
  517. raise Exception("transforms need to be defined, now is None.")
  518. if not isinstance(img_file_list, (list, tuple)):
  519. raise Exception("im_file must be list/tuple")
  520. if transforms is None:
  521. transforms = self.test_transforms
  522. input_channel = getattr(self, 'input_channel', 3)
  523. im, im_info = DeepLabv3p._preprocess(
  524. img_file_list,
  525. transforms,
  526. self.model_type,
  527. self.__class__.__name__,
  528. self.thread_pool,
  529. input_channel=input_channel)
  530. with fluid.scope_guard(self.scope):
  531. result = self.exe.run(self.test_prog,
  532. feed={'image': im},
  533. fetch_list=list(self.test_outputs.values()),
  534. use_program_cache=True)
  535. preds = DeepLabv3p._postprocess(result, im_info)
  536. return preds
  537. def overlap_tile_predict(self,
  538. img_file,
  539. tile_size=[512, 512],
  540. pad_size=[64, 64],
  541. batch_size=32,
  542. transforms=None):
  543. """有重叠的大图切小图预测。
  544. Args:
  545. img_file(str|np.ndarray): 预测图像路径,或者是解码后的排列格式为(H, W, C)且类型为float32且为BGR格式的数组。
  546. tile_size(list|tuple): 滑动窗口的大小,该区域内用于拼接预测结果,格式为(W,H)。默认值为[512, 512]。
  547. pad_size(list|tuple): 滑动窗口向四周扩展的大小,扩展区域内不用于拼接预测结果,格式为(W,H)。默认值为[64,64]。
  548. batch_size(int):对窗口进行批量预测时的批量大小。默认值为32
  549. transforms(paddlex.cv.transforms): 数据预处理操作。
  550. Returns:
  551. dict: 包含关键字'label_map'和'score_map', 'label_map'存储预测结果灰度图,
  552. 像素值表示对应的类别,'score_map'存储各类别的概率,shape=(h, w, num_classes)
  553. """
  554. if transforms is None and not hasattr(self, 'test_transforms'):
  555. raise Exception("transforms need to be defined, now is None.")
  556. if isinstance(img_file, str):
  557. image, _ = Compose.decode_image(img_file, None)
  558. elif isinstance(img_file, np.ndarray):
  559. image = img_file.copy()
  560. else:
  561. raise Exception("im_file must be list/tuple")
  562. height, width, channel = image.shape
  563. image_tile_list = list()
  564. # Padding along the left and right sides
  565. if pad_size[0] > 0:
  566. left_pad = cv2.flip(image[0:height, 0:pad_size[0], :], 1)
  567. right_pad = cv2.flip(image[0:height, -pad_size[0]:width, :], 1)
  568. padding_image = cv2.hconcat([left_pad, image])
  569. padding_image = cv2.hconcat([padding_image, right_pad])
  570. else:
  571. import copy
  572. padding_image = copy.deepcopy(image)
  573. # Padding along the upper and lower sides
  574. padding_height, padding_width, _ = padding_image.shape
  575. if pad_size[1] > 0:
  576. upper_pad = cv2.flip(
  577. padding_image[0:pad_size[1], 0:padding_width, :], 0)
  578. lower_pad = cv2.flip(
  579. padding_image[-pad_size[1]:padding_height, 0:padding_width, :],
  580. 0)
  581. padding_image = cv2.vconcat([upper_pad, padding_image])
  582. padding_image = cv2.vconcat([padding_image, lower_pad])
  583. # crop the padding image into tile pieces
  584. padding_height, padding_width, _ = padding_image.shape
  585. for h_id in range(0, height // tile_size[1] + 1):
  586. for w_id in range(0, width // tile_size[0] + 1):
  587. left = w_id * tile_size[0]
  588. upper = h_id * tile_size[1]
  589. right = min(left + tile_size[0] + pad_size[0] * 2,
  590. padding_width)
  591. lower = min(upper + tile_size[1] + pad_size[1] * 2,
  592. padding_height)
  593. image_tile = padding_image[upper:lower, left:right, :]
  594. image_tile_list.append(image_tile)
  595. # predict
  596. label_map = np.zeros((height, width), dtype=np.uint8)
  597. score_map = np.zeros(
  598. (height, width, self.num_classes), dtype=np.float32)
  599. num_tiles = len(image_tile_list)
  600. for i in range(0, num_tiles, batch_size):
  601. begin = i
  602. end = min(i + batch_size, num_tiles)
  603. res = self.batch_predict(
  604. img_file_list=image_tile_list[begin:end],
  605. transforms=transforms)
  606. for j in range(begin, end):
  607. h_id = j // (width // tile_size[0] + 1)
  608. w_id = j % (width // tile_size[0] + 1)
  609. left = w_id * tile_size[0]
  610. upper = h_id * tile_size[1]
  611. right = min((w_id + 1) * tile_size[0], width)
  612. lower = min((h_id + 1) * tile_size[1], height)
  613. tile_label_map = res[j - begin]["label_map"]
  614. tile_score_map = res[j - begin]["score_map"]
  615. tile_upper = pad_size[1]
  616. tile_lower = tile_label_map.shape[0] - pad_size[1]
  617. tile_left = pad_size[0]
  618. tile_right = tile_label_map.shape[1] - pad_size[0]
  619. label_map[upper:lower, left:right] = \
  620. tile_label_map[tile_upper:tile_lower, tile_left:tile_right]
  621. score_map[upper:lower, left:right, :] = \
  622. tile_score_map[tile_upper:tile_lower, tile_left:tile_right, :]
  623. result = {"label_map": label_map, "score_map": score_map}
  624. return result