You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

633 lines
30 KiB

6 years ago
  1. # Copyright 2017 The TensorFlow 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. # ==============================================================================
  15. """Function to build box predictor from configuration."""
  16. import collections
  17. import tensorflow as tf
  18. from object_detection.predictors import convolutional_box_predictor
  19. from object_detection.predictors import convolutional_keras_box_predictor
  20. from object_detection.predictors import mask_rcnn_box_predictor
  21. from object_detection.predictors import rfcn_box_predictor
  22. from object_detection.predictors.heads import box_head
  23. from object_detection.predictors.heads import class_head
  24. from object_detection.predictors.heads import keras_box_head
  25. from object_detection.predictors.heads import keras_class_head
  26. from object_detection.predictors.heads import mask_head
  27. from object_detection.protos import box_predictor_pb2
  28. def build_convolutional_box_predictor(is_training,
  29. num_classes,
  30. conv_hyperparams_fn,
  31. min_depth,
  32. max_depth,
  33. num_layers_before_predictor,
  34. use_dropout,
  35. dropout_keep_prob,
  36. kernel_size,
  37. box_code_size,
  38. apply_sigmoid_to_scores=False,
  39. add_background_class=True,
  40. class_prediction_bias_init=0.0,
  41. use_depthwise=False,):
  42. """Builds the ConvolutionalBoxPredictor from the arguments.
  43. Args:
  44. is_training: Indicates whether the BoxPredictor is in training mode.
  45. num_classes: number of classes. Note that num_classes *does not*
  46. include the background category, so if groundtruth labels take values
  47. in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the
  48. assigned classification targets can range from {0,... K}).
  49. conv_hyperparams_fn: A function to generate tf-slim arg_scope with
  50. hyperparameters for convolution ops.
  51. min_depth: Minimum feature depth prior to predicting box encodings
  52. and class predictions.
  53. max_depth: Maximum feature depth prior to predicting box encodings
  54. and class predictions. If max_depth is set to 0, no additional
  55. feature map will be inserted before location and class predictions.
  56. num_layers_before_predictor: Number of the additional conv layers before
  57. the predictor.
  58. use_dropout: Option to use dropout or not. Note that a single dropout
  59. op is applied here prior to both box and class predictions, which stands
  60. in contrast to the ConvolutionalBoxPredictor below.
  61. dropout_keep_prob: Keep probability for dropout.
  62. This is only used if use_dropout is True.
  63. kernel_size: Size of final convolution kernel. If the
  64. spatial resolution of the feature map is smaller than the kernel size,
  65. then the kernel size is automatically set to be
  66. min(feature_width, feature_height).
  67. box_code_size: Size of encoding for each box.
  68. apply_sigmoid_to_scores: If True, apply the sigmoid on the output
  69. class_predictions.
  70. add_background_class: Whether to add an implicit background class.
  71. class_prediction_bias_init: Constant value to initialize bias of the last
  72. conv2d layer before class prediction.
  73. use_depthwise: Whether to use depthwise convolutions for prediction
  74. steps. Default is False.
  75. Returns:
  76. A ConvolutionalBoxPredictor class.
  77. """
  78. box_prediction_head = box_head.ConvolutionalBoxHead(
  79. is_training=is_training,
  80. box_code_size=box_code_size,
  81. kernel_size=kernel_size,
  82. use_depthwise=use_depthwise)
  83. class_prediction_head = class_head.ConvolutionalClassHead(
  84. is_training=is_training,
  85. num_class_slots=num_classes + 1 if add_background_class else num_classes,
  86. use_dropout=use_dropout,
  87. dropout_keep_prob=dropout_keep_prob,
  88. kernel_size=kernel_size,
  89. apply_sigmoid_to_scores=apply_sigmoid_to_scores,
  90. class_prediction_bias_init=class_prediction_bias_init,
  91. use_depthwise=use_depthwise)
  92. other_heads = {}
  93. return convolutional_box_predictor.ConvolutionalBoxPredictor(
  94. is_training=is_training,
  95. num_classes=num_classes,
  96. box_prediction_head=box_prediction_head,
  97. class_prediction_head=class_prediction_head,
  98. other_heads=other_heads,
  99. conv_hyperparams_fn=conv_hyperparams_fn,
  100. num_layers_before_predictor=num_layers_before_predictor,
  101. min_depth=min_depth,
  102. max_depth=max_depth)
  103. def build_convolutional_keras_box_predictor(is_training,
  104. num_classes,
  105. conv_hyperparams,
  106. freeze_batchnorm,
  107. inplace_batchnorm_update,
  108. num_predictions_per_location_list,
  109. min_depth,
  110. max_depth,
  111. num_layers_before_predictor,
  112. use_dropout,
  113. dropout_keep_prob,
  114. kernel_size,
  115. box_code_size,
  116. add_background_class=True,
  117. class_prediction_bias_init=0.0,
  118. use_depthwise=False,
  119. name='BoxPredictor'):
  120. """Builds the Keras ConvolutionalBoxPredictor from the arguments.
  121. Args:
  122. is_training: Indicates whether the BoxPredictor is in training mode.
  123. num_classes: number of classes. Note that num_classes *does not*
  124. include the background category, so if groundtruth labels take values
  125. in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the
  126. assigned classification targets can range from {0,... K}).
  127. conv_hyperparams: A `hyperparams_builder.KerasLayerHyperparams` object
  128. containing hyperparameters for convolution ops.
  129. freeze_batchnorm: Whether to freeze batch norm parameters during
  130. training or not. When training with a small batch size (e.g. 1), it is
  131. desirable to freeze batch norm update and use pretrained batch norm
  132. params.
  133. inplace_batchnorm_update: Whether to update batch norm moving average
  134. values inplace. When this is false train op must add a control
  135. dependency on tf.graphkeys.UPDATE_OPS collection in order to update
  136. batch norm statistics.
  137. num_predictions_per_location_list: A list of integers representing the
  138. number of box predictions to be made per spatial location for each
  139. feature map.
  140. min_depth: Minimum feature depth prior to predicting box encodings
  141. and class predictions.
  142. max_depth: Maximum feature depth prior to predicting box encodings
  143. and class predictions. If max_depth is set to 0, no additional
  144. feature map will be inserted before location and class predictions.
  145. num_layers_before_predictor: Number of the additional conv layers before
  146. the predictor.
  147. use_dropout: Option to use dropout or not. Note that a single dropout
  148. op is applied here prior to both box and class predictions, which stands
  149. in contrast to the ConvolutionalBoxPredictor below.
  150. dropout_keep_prob: Keep probability for dropout.
  151. This is only used if use_dropout is True.
  152. kernel_size: Size of final convolution kernel. If the
  153. spatial resolution of the feature map is smaller than the kernel size,
  154. then the kernel size is automatically set to be
  155. min(feature_width, feature_height).
  156. box_code_size: Size of encoding for each box.
  157. add_background_class: Whether to add an implicit background class.
  158. class_prediction_bias_init: constant value to initialize bias of the last
  159. conv2d layer before class prediction.
  160. use_depthwise: Whether to use depthwise convolutions for prediction
  161. steps. Default is False.
  162. name: A string name scope to assign to the box predictor. If `None`, Keras
  163. will auto-generate one from the class name.
  164. Returns:
  165. A Keras ConvolutionalBoxPredictor class.
  166. """
  167. box_prediction_heads = []
  168. class_prediction_heads = []
  169. other_heads = {}
  170. for stack_index, num_predictions_per_location in enumerate(
  171. num_predictions_per_location_list):
  172. box_prediction_heads.append(
  173. keras_box_head.ConvolutionalBoxHead(
  174. is_training=is_training,
  175. box_code_size=box_code_size,
  176. kernel_size=kernel_size,
  177. conv_hyperparams=conv_hyperparams,
  178. freeze_batchnorm=freeze_batchnorm,
  179. num_predictions_per_location=num_predictions_per_location,
  180. use_depthwise=use_depthwise,
  181. name='ConvolutionalBoxHead_%d' % stack_index))
  182. class_prediction_heads.append(
  183. keras_class_head.ConvolutionalClassHead(
  184. is_training=is_training,
  185. num_class_slots=(
  186. num_classes + 1 if add_background_class else num_classes),
  187. use_dropout=use_dropout,
  188. dropout_keep_prob=dropout_keep_prob,
  189. kernel_size=kernel_size,
  190. conv_hyperparams=conv_hyperparams,
  191. freeze_batchnorm=freeze_batchnorm,
  192. num_predictions_per_location=num_predictions_per_location,
  193. class_prediction_bias_init=class_prediction_bias_init,
  194. use_depthwise=use_depthwise,
  195. name='ConvolutionalClassHead_%d' % stack_index))
  196. return convolutional_keras_box_predictor.ConvolutionalBoxPredictor(
  197. is_training=is_training,
  198. num_classes=num_classes,
  199. box_prediction_heads=box_prediction_heads,
  200. class_prediction_heads=class_prediction_heads,
  201. other_heads=other_heads,
  202. conv_hyperparams=conv_hyperparams,
  203. num_layers_before_predictor=num_layers_before_predictor,
  204. min_depth=min_depth,
  205. max_depth=max_depth,
  206. freeze_batchnorm=freeze_batchnorm,
  207. inplace_batchnorm_update=inplace_batchnorm_update,
  208. name=name)
  209. def build_weight_shared_convolutional_box_predictor(
  210. is_training,
  211. num_classes,
  212. conv_hyperparams_fn,
  213. depth,
  214. num_layers_before_predictor,
  215. box_code_size,
  216. kernel_size=3,
  217. add_background_class=True,
  218. class_prediction_bias_init=0.0,
  219. use_dropout=False,
  220. dropout_keep_prob=0.8,
  221. share_prediction_tower=False,
  222. apply_batch_norm=True,
  223. use_depthwise=False,
  224. score_converter_fn=tf.identity,
  225. box_encodings_clip_range=None):
  226. """Builds and returns a WeightSharedConvolutionalBoxPredictor class.
  227. Args:
  228. is_training: Indicates whether the BoxPredictor is in training mode.
  229. num_classes: number of classes. Note that num_classes *does not*
  230. include the background category, so if groundtruth labels take values
  231. in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the
  232. assigned classification targets can range from {0,... K}).
  233. conv_hyperparams_fn: A function to generate tf-slim arg_scope with
  234. hyperparameters for convolution ops.
  235. depth: depth of conv layers.
  236. num_layers_before_predictor: Number of the additional conv layers before
  237. the predictor.
  238. box_code_size: Size of encoding for each box.
  239. kernel_size: Size of final convolution kernel.
  240. add_background_class: Whether to add an implicit background class.
  241. class_prediction_bias_init: constant value to initialize bias of the last
  242. conv2d layer before class prediction.
  243. use_dropout: Whether to apply dropout to class prediction head.
  244. dropout_keep_prob: Probability of keeping activiations.
  245. share_prediction_tower: Whether to share the multi-layer tower between box
  246. prediction and class prediction heads.
  247. apply_batch_norm: Whether to apply batch normalization to conv layers in
  248. this predictor.
  249. use_depthwise: Whether to use depthwise separable conv2d instead of conv2d.
  250. score_converter_fn: Callable score converter to perform elementwise op on
  251. class scores.
  252. box_encodings_clip_range: Min and max values for clipping the box_encodings.
  253. Returns:
  254. A WeightSharedConvolutionalBoxPredictor class.
  255. """
  256. box_prediction_head = box_head.WeightSharedConvolutionalBoxHead(
  257. box_code_size=box_code_size,
  258. kernel_size=kernel_size,
  259. use_depthwise=use_depthwise,
  260. box_encodings_clip_range=box_encodings_clip_range)
  261. class_prediction_head = (
  262. class_head.WeightSharedConvolutionalClassHead(
  263. num_class_slots=(
  264. num_classes + 1 if add_background_class else num_classes),
  265. kernel_size=kernel_size,
  266. class_prediction_bias_init=class_prediction_bias_init,
  267. use_dropout=use_dropout,
  268. dropout_keep_prob=dropout_keep_prob,
  269. use_depthwise=use_depthwise,
  270. score_converter_fn=score_converter_fn))
  271. other_heads = {}
  272. return convolutional_box_predictor.WeightSharedConvolutionalBoxPredictor(
  273. is_training=is_training,
  274. num_classes=num_classes,
  275. box_prediction_head=box_prediction_head,
  276. class_prediction_head=class_prediction_head,
  277. other_heads=other_heads,
  278. conv_hyperparams_fn=conv_hyperparams_fn,
  279. depth=depth,
  280. num_layers_before_predictor=num_layers_before_predictor,
  281. kernel_size=kernel_size,
  282. apply_batch_norm=apply_batch_norm,
  283. share_prediction_tower=share_prediction_tower,
  284. use_depthwise=use_depthwise)
  285. def build_mask_rcnn_box_predictor(is_training,
  286. num_classes,
  287. fc_hyperparams_fn,
  288. use_dropout,
  289. dropout_keep_prob,
  290. box_code_size,
  291. add_background_class=True,
  292. share_box_across_classes=False,
  293. predict_instance_masks=False,
  294. conv_hyperparams_fn=None,
  295. mask_height=14,
  296. mask_width=14,
  297. mask_prediction_num_conv_layers=2,
  298. mask_prediction_conv_depth=256,
  299. masks_are_class_agnostic=False,
  300. convolve_then_upsample_masks=False):
  301. """Builds and returns a MaskRCNNBoxPredictor class.
  302. Args:
  303. is_training: Indicates whether the BoxPredictor is in training mode.
  304. num_classes: number of classes. Note that num_classes *does not*
  305. include the background category, so if groundtruth labels take values
  306. in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the
  307. assigned classification targets can range from {0,... K}).
  308. fc_hyperparams_fn: A function to generate tf-slim arg_scope with
  309. hyperparameters for fully connected ops.
  310. use_dropout: Option to use dropout or not. Note that a single dropout
  311. op is applied here prior to both box and class predictions, which stands
  312. in contrast to the ConvolutionalBoxPredictor below.
  313. dropout_keep_prob: Keep probability for dropout.
  314. This is only used if use_dropout is True.
  315. box_code_size: Size of encoding for each box.
  316. add_background_class: Whether to add an implicit background class.
  317. share_box_across_classes: Whether to share boxes across classes rather
  318. than use a different box for each class.
  319. predict_instance_masks: If True, will add a third stage mask prediction
  320. to the returned class.
  321. conv_hyperparams_fn: A function to generate tf-slim arg_scope with
  322. hyperparameters for convolution ops.
  323. mask_height: Desired output mask height. The default value is 14.
  324. mask_width: Desired output mask width. The default value is 14.
  325. mask_prediction_num_conv_layers: Number of convolution layers applied to
  326. the image_features in mask prediction branch.
  327. mask_prediction_conv_depth: The depth for the first conv2d_transpose op
  328. applied to the image_features in the mask prediction branch. If set
  329. to 0, the depth of the convolution layers will be automatically chosen
  330. based on the number of object classes and the number of channels in the
  331. image features.
  332. masks_are_class_agnostic: Boolean determining if the mask-head is
  333. class-agnostic or not.
  334. convolve_then_upsample_masks: Whether to apply convolutions on mask
  335. features before upsampling using nearest neighbor resizing. Otherwise,
  336. mask features are resized to [`mask_height`, `mask_width`] using
  337. bilinear resizing before applying convolutions.
  338. Returns:
  339. A MaskRCNNBoxPredictor class.
  340. """
  341. box_prediction_head = box_head.MaskRCNNBoxHead(
  342. is_training=is_training,
  343. num_classes=num_classes,
  344. fc_hyperparams_fn=fc_hyperparams_fn,
  345. use_dropout=use_dropout,
  346. dropout_keep_prob=dropout_keep_prob,
  347. box_code_size=box_code_size,
  348. share_box_across_classes=share_box_across_classes)
  349. class_prediction_head = class_head.MaskRCNNClassHead(
  350. is_training=is_training,
  351. num_class_slots=num_classes + 1 if add_background_class else num_classes,
  352. fc_hyperparams_fn=fc_hyperparams_fn,
  353. use_dropout=use_dropout,
  354. dropout_keep_prob=dropout_keep_prob)
  355. third_stage_heads = {}
  356. if predict_instance_masks:
  357. third_stage_heads[
  358. mask_rcnn_box_predictor.
  359. MASK_PREDICTIONS] = mask_head.MaskRCNNMaskHead(
  360. num_classes=num_classes,
  361. conv_hyperparams_fn=conv_hyperparams_fn,
  362. mask_height=mask_height,
  363. mask_width=mask_width,
  364. mask_prediction_num_conv_layers=mask_prediction_num_conv_layers,
  365. mask_prediction_conv_depth=mask_prediction_conv_depth,
  366. masks_are_class_agnostic=masks_are_class_agnostic,
  367. convolve_then_upsample=convolve_then_upsample_masks)
  368. return mask_rcnn_box_predictor.MaskRCNNBoxPredictor(
  369. is_training=is_training,
  370. num_classes=num_classes,
  371. box_prediction_head=box_prediction_head,
  372. class_prediction_head=class_prediction_head,
  373. third_stage_heads=third_stage_heads)
  374. def build_score_converter(score_converter_config, is_training):
  375. """Builds score converter based on the config.
  376. Builds one of [tf.identity, tf.sigmoid] score converters based on the config
  377. and whether the BoxPredictor is for training or inference.
  378. Args:
  379. score_converter_config:
  380. box_predictor_pb2.WeightSharedConvolutionalBoxPredictor.score_converter.
  381. is_training: Indicates whether the BoxPredictor is in training mode.
  382. Returns:
  383. Callable score converter op.
  384. Raises:
  385. ValueError: On unknown score converter.
  386. """
  387. if score_converter_config == (
  388. box_predictor_pb2.WeightSharedConvolutionalBoxPredictor.IDENTITY):
  389. return tf.identity
  390. if score_converter_config == (
  391. box_predictor_pb2.WeightSharedConvolutionalBoxPredictor.SIGMOID):
  392. return tf.identity if is_training else tf.sigmoid
  393. raise ValueError('Unknown score converter.')
  394. BoxEncodingsClipRange = collections.namedtuple('BoxEncodingsClipRange',
  395. ['min', 'max'])
  396. def build(argscope_fn, box_predictor_config, is_training, num_classes,
  397. add_background_class=True):
  398. """Builds box predictor based on the configuration.
  399. Builds box predictor based on the configuration. See box_predictor.proto for
  400. configurable options. Also, see box_predictor.py for more details.
  401. Args:
  402. argscope_fn: A function that takes the following inputs:
  403. * hyperparams_pb2.Hyperparams proto
  404. * a boolean indicating if the model is in training mode.
  405. and returns a tf slim argscope for Conv and FC hyperparameters.
  406. box_predictor_config: box_predictor_pb2.BoxPredictor proto containing
  407. configuration.
  408. is_training: Whether the models is in training mode.
  409. num_classes: Number of classes to predict.
  410. add_background_class: Whether to add an implicit background class.
  411. Returns:
  412. box_predictor: box_predictor.BoxPredictor object.
  413. Raises:
  414. ValueError: On unknown box predictor.
  415. """
  416. if not isinstance(box_predictor_config, box_predictor_pb2.BoxPredictor):
  417. raise ValueError('box_predictor_config not of type '
  418. 'box_predictor_pb2.BoxPredictor.')
  419. box_predictor_oneof = box_predictor_config.WhichOneof('box_predictor_oneof')
  420. if box_predictor_oneof == 'convolutional_box_predictor':
  421. config_box_predictor = box_predictor_config.convolutional_box_predictor
  422. conv_hyperparams_fn = argscope_fn(config_box_predictor.conv_hyperparams,
  423. is_training)
  424. return build_convolutional_box_predictor(
  425. is_training=is_training,
  426. num_classes=num_classes,
  427. add_background_class=add_background_class,
  428. conv_hyperparams_fn=conv_hyperparams_fn,
  429. use_dropout=config_box_predictor.use_dropout,
  430. dropout_keep_prob=config_box_predictor.dropout_keep_probability,
  431. box_code_size=config_box_predictor.box_code_size,
  432. kernel_size=config_box_predictor.kernel_size,
  433. num_layers_before_predictor=(
  434. config_box_predictor.num_layers_before_predictor),
  435. min_depth=config_box_predictor.min_depth,
  436. max_depth=config_box_predictor.max_depth,
  437. apply_sigmoid_to_scores=config_box_predictor.apply_sigmoid_to_scores,
  438. class_prediction_bias_init=(
  439. config_box_predictor.class_prediction_bias_init),
  440. use_depthwise=config_box_predictor.use_depthwise)
  441. if box_predictor_oneof == 'weight_shared_convolutional_box_predictor':
  442. config_box_predictor = (
  443. box_predictor_config.weight_shared_convolutional_box_predictor)
  444. conv_hyperparams_fn = argscope_fn(config_box_predictor.conv_hyperparams,
  445. is_training)
  446. apply_batch_norm = config_box_predictor.conv_hyperparams.HasField(
  447. 'batch_norm')
  448. # During training phase, logits are used to compute the loss. Only apply
  449. # sigmoid at inference to make the inference graph TPU friendly.
  450. score_converter_fn = build_score_converter(
  451. config_box_predictor.score_converter, is_training)
  452. # Optionally apply clipping to box encodings, when box_encodings_clip_range
  453. # is set.
  454. box_encodings_clip_range = (
  455. BoxEncodingsClipRange(
  456. min=config_box_predictor.box_encodings_clip_range.min,
  457. max=config_box_predictor.box_encodings_clip_range.max)
  458. if config_box_predictor.HasField('box_encodings_clip_range') else None)
  459. return build_weight_shared_convolutional_box_predictor(
  460. is_training=is_training,
  461. num_classes=num_classes,
  462. add_background_class=add_background_class,
  463. conv_hyperparams_fn=conv_hyperparams_fn,
  464. depth=config_box_predictor.depth,
  465. num_layers_before_predictor=(
  466. config_box_predictor.num_layers_before_predictor),
  467. box_code_size=config_box_predictor.box_code_size,
  468. kernel_size=config_box_predictor.kernel_size,
  469. class_prediction_bias_init=(
  470. config_box_predictor.class_prediction_bias_init),
  471. use_dropout=config_box_predictor.use_dropout,
  472. dropout_keep_prob=config_box_predictor.dropout_keep_probability,
  473. share_prediction_tower=config_box_predictor.share_prediction_tower,
  474. apply_batch_norm=apply_batch_norm,
  475. use_depthwise=config_box_predictor.use_depthwise,
  476. score_converter_fn=score_converter_fn,
  477. box_encodings_clip_range=box_encodings_clip_range)
  478. if box_predictor_oneof == 'mask_rcnn_box_predictor':
  479. config_box_predictor = box_predictor_config.mask_rcnn_box_predictor
  480. fc_hyperparams_fn = argscope_fn(config_box_predictor.fc_hyperparams,
  481. is_training)
  482. conv_hyperparams_fn = None
  483. if config_box_predictor.HasField('conv_hyperparams'):
  484. conv_hyperparams_fn = argscope_fn(
  485. config_box_predictor.conv_hyperparams, is_training)
  486. return build_mask_rcnn_box_predictor(
  487. is_training=is_training,
  488. num_classes=num_classes,
  489. add_background_class=add_background_class,
  490. fc_hyperparams_fn=fc_hyperparams_fn,
  491. use_dropout=config_box_predictor.use_dropout,
  492. dropout_keep_prob=config_box_predictor.dropout_keep_probability,
  493. box_code_size=config_box_predictor.box_code_size,
  494. share_box_across_classes=(
  495. config_box_predictor.share_box_across_classes),
  496. predict_instance_masks=config_box_predictor.predict_instance_masks,
  497. conv_hyperparams_fn=conv_hyperparams_fn,
  498. mask_height=config_box_predictor.mask_height,
  499. mask_width=config_box_predictor.mask_width,
  500. mask_prediction_num_conv_layers=(
  501. config_box_predictor.mask_prediction_num_conv_layers),
  502. mask_prediction_conv_depth=(
  503. config_box_predictor.mask_prediction_conv_depth),
  504. masks_are_class_agnostic=(
  505. config_box_predictor.masks_are_class_agnostic),
  506. convolve_then_upsample_masks=(
  507. config_box_predictor.convolve_then_upsample_masks))
  508. if box_predictor_oneof == 'rfcn_box_predictor':
  509. config_box_predictor = box_predictor_config.rfcn_box_predictor
  510. conv_hyperparams_fn = argscope_fn(config_box_predictor.conv_hyperparams,
  511. is_training)
  512. box_predictor_object = rfcn_box_predictor.RfcnBoxPredictor(
  513. is_training=is_training,
  514. num_classes=num_classes,
  515. conv_hyperparams_fn=conv_hyperparams_fn,
  516. crop_size=[config_box_predictor.crop_height,
  517. config_box_predictor.crop_width],
  518. num_spatial_bins=[config_box_predictor.num_spatial_bins_height,
  519. config_box_predictor.num_spatial_bins_width],
  520. depth=config_box_predictor.depth,
  521. box_code_size=config_box_predictor.box_code_size)
  522. return box_predictor_object
  523. raise ValueError('Unknown box predictor: {}'.format(box_predictor_oneof))
  524. def build_keras(conv_hyperparams_fn, freeze_batchnorm, inplace_batchnorm_update,
  525. num_predictions_per_location_list, box_predictor_config,
  526. is_training, num_classes, add_background_class=True):
  527. """Builds a Keras-based box predictor based on the configuration.
  528. Builds Keras-based box predictor based on the configuration.
  529. See box_predictor.proto for configurable options. Also, see box_predictor.py
  530. for more details.
  531. Args:
  532. conv_hyperparams_fn: A function that takes a hyperparams_pb2.Hyperparams
  533. proto and returns a `hyperparams_builder.KerasLayerHyperparams`
  534. for Conv or FC hyperparameters.
  535. freeze_batchnorm: Whether to freeze batch norm parameters during
  536. training or not. When training with a small batch size (e.g. 1), it is
  537. desirable to freeze batch norm update and use pretrained batch norm
  538. params.
  539. inplace_batchnorm_update: Whether to update batch norm moving average
  540. values inplace. When this is false train op must add a control
  541. dependency on tf.graphkeys.UPDATE_OPS collection in order to update
  542. batch norm statistics.
  543. num_predictions_per_location_list: A list of integers representing the
  544. number of box predictions to be made per spatial location for each
  545. feature map.
  546. box_predictor_config: box_predictor_pb2.BoxPredictor proto containing
  547. configuration.
  548. is_training: Whether the models is in training mode.
  549. num_classes: Number of classes to predict.
  550. add_background_class: Whether to add an implicit background class.
  551. Returns:
  552. box_predictor: box_predictor.KerasBoxPredictor object.
  553. Raises:
  554. ValueError: On unknown box predictor, or one with no Keras box predictor.
  555. """
  556. if not isinstance(box_predictor_config, box_predictor_pb2.BoxPredictor):
  557. raise ValueError('box_predictor_config not of type '
  558. 'box_predictor_pb2.BoxPredictor.')
  559. box_predictor_oneof = box_predictor_config.WhichOneof('box_predictor_oneof')
  560. if box_predictor_oneof == 'convolutional_box_predictor':
  561. config_box_predictor = box_predictor_config.convolutional_box_predictor
  562. conv_hyperparams = conv_hyperparams_fn(
  563. config_box_predictor.conv_hyperparams)
  564. return build_convolutional_keras_box_predictor(
  565. is_training=is_training,
  566. num_classes=num_classes,
  567. add_background_class=add_background_class,
  568. conv_hyperparams=conv_hyperparams,
  569. freeze_batchnorm=freeze_batchnorm,
  570. inplace_batchnorm_update=inplace_batchnorm_update,
  571. num_predictions_per_location_list=num_predictions_per_location_list,
  572. use_dropout=config_box_predictor.use_dropout,
  573. dropout_keep_prob=config_box_predictor.dropout_keep_probability,
  574. box_code_size=config_box_predictor.box_code_size,
  575. kernel_size=config_box_predictor.kernel_size,
  576. num_layers_before_predictor=(
  577. config_box_predictor.num_layers_before_predictor),
  578. min_depth=config_box_predictor.min_depth,
  579. max_depth=config_box_predictor.max_depth,
  580. class_prediction_bias_init=(
  581. config_box_predictor.class_prediction_bias_init),
  582. use_depthwise=config_box_predictor.use_depthwise)
  583. raise ValueError(
  584. 'Unknown box predictor for Keras: {}'.format(box_predictor_oneof))