|
| 1 | +# Copyright 2022 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 | +"""COCO data loader for DETR.""" |
| 16 | + |
| 17 | +import dataclasses |
| 18 | +from typing import Optional, Tuple |
| 19 | +import tensorflow as tf |
| 20 | + |
| 21 | +from official.core import config_definitions as cfg |
| 22 | +from official.core import input_reader |
| 23 | +from official.vision.beta.ops import box_ops |
| 24 | +from official.vision.beta.ops import preprocess_ops |
| 25 | + |
| 26 | + |
| 27 | +@dataclasses.dataclass |
| 28 | +class COCODataConfig(cfg.DataConfig): |
| 29 | + """Data config for COCO.""" |
| 30 | + output_size: Tuple[int, int] = (1333, 1333) |
| 31 | + max_num_boxes: int = 100 |
| 32 | + resize_scales: Tuple[int, ...] = ( |
| 33 | + 480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800) |
| 34 | + |
| 35 | + |
| 36 | +class COCODataLoader(): |
| 37 | + """A class to load dataset for COCO detection task.""" |
| 38 | + |
| 39 | + def __init__(self, params: COCODataConfig): |
| 40 | + self._params = params |
| 41 | + |
| 42 | + def preprocess(self, inputs): |
| 43 | + """Preprocess COCO for DETR.""" |
| 44 | + image = inputs['image'] |
| 45 | + boxes = inputs['objects']['bbox'] |
| 46 | + classes = inputs['objects']['label'] + 1 |
| 47 | + is_crowd = inputs['objects']['is_crowd'] |
| 48 | + |
| 49 | + image = preprocess_ops.normalize_image(image) |
| 50 | + if self._params.is_training: |
| 51 | + image, boxes, _ = preprocess_ops.random_horizontal_flip(image, boxes) |
| 52 | + |
| 53 | + do_crop = tf.greater(tf.random.uniform([]), 0.5) |
| 54 | + if do_crop: |
| 55 | + # Rescale |
| 56 | + boxes = box_ops.denormalize_boxes(boxes, tf.shape(image)[:2]) |
| 57 | + index = tf.random.categorical(tf.zeros([1, 3]), 1)[0] |
| 58 | + scales = tf.gather([400.0, 500.0, 600.0], index, axis=0) |
| 59 | + short_side = scales[0] |
| 60 | + image, image_info = preprocess_ops.resize_image(image, short_side) |
| 61 | + boxes = preprocess_ops.resize_and_crop_boxes(boxes, |
| 62 | + image_info[2, :], |
| 63 | + image_info[1, :], |
| 64 | + image_info[3, :]) |
| 65 | + boxes = box_ops.normalize_boxes(boxes, image_info[1, :]) |
| 66 | + |
| 67 | + # Do croping |
| 68 | + shape = tf.cast(image_info[1], dtype=tf.int32) |
| 69 | + h = tf.random.uniform( |
| 70 | + [], 384, tf.math.minimum(shape[0], 600), dtype=tf.int32) |
| 71 | + w = tf.random.uniform( |
| 72 | + [], 384, tf.math.minimum(shape[1], 600), dtype=tf.int32) |
| 73 | + i = tf.random.uniform([], 0, shape[0] - h + 1, dtype=tf.int32) |
| 74 | + j = tf.random.uniform([], 0, shape[1] - w + 1, dtype=tf.int32) |
| 75 | + image = tf.image.crop_to_bounding_box(image, i, j, h, w) |
| 76 | + boxes = tf.clip_by_value( |
| 77 | + (boxes[..., :] * tf.cast( |
| 78 | + tf.stack([shape[0], shape[1], shape[0], shape[1]]), |
| 79 | + dtype=tf.float32) - |
| 80 | + tf.cast(tf.stack([i, j, i, j]), dtype=tf.float32)) / |
| 81 | + tf.cast(tf.stack([h, w, h, w]), dtype=tf.float32), 0.0, 1.0) |
| 82 | + scales = tf.constant( |
| 83 | + self._params.resize_scales, |
| 84 | + dtype=tf.float32) |
| 85 | + index = tf.random.categorical(tf.zeros([1, 11]), 1)[0] |
| 86 | + scales = tf.gather(scales, index, axis=0) |
| 87 | + else: |
| 88 | + scales = tf.constant([self._params.resize_scales[-1]], tf.float32) |
| 89 | + |
| 90 | + image_shape = tf.shape(image)[:2] |
| 91 | + boxes = box_ops.denormalize_boxes(boxes, image_shape) |
| 92 | + gt_boxes = boxes |
| 93 | + short_side = scales[0] |
| 94 | + image, image_info = preprocess_ops.resize_image( |
| 95 | + image, |
| 96 | + short_side, |
| 97 | + max(self._params.output_size)) |
| 98 | + boxes = preprocess_ops.resize_and_crop_boxes(boxes, |
| 99 | + image_info[2, :], |
| 100 | + image_info[1, :], |
| 101 | + image_info[3, :]) |
| 102 | + boxes = box_ops.normalize_boxes(boxes, image_info[1, :]) |
| 103 | + |
| 104 | + # Filters out ground truth boxes that are all zeros. |
| 105 | + indices = box_ops.get_non_empty_box_indices(boxes) |
| 106 | + boxes = tf.gather(boxes, indices) |
| 107 | + classes = tf.gather(classes, indices) |
| 108 | + is_crowd = tf.gather(is_crowd, indices) |
| 109 | + boxes = box_ops.yxyx_to_cycxhw(boxes) |
| 110 | + |
| 111 | + image = tf.image.pad_to_bounding_box( |
| 112 | + image, 0, 0, self._params.output_size[0], self._params.output_size[1]) |
| 113 | + labels = { |
| 114 | + 'classes': |
| 115 | + preprocess_ops.clip_or_pad_to_fixed_size( |
| 116 | + classes, self._params.max_num_boxes), |
| 117 | + 'boxes': |
| 118 | + preprocess_ops.clip_or_pad_to_fixed_size( |
| 119 | + boxes, self._params.max_num_boxes) |
| 120 | + } |
| 121 | + if not self._params.is_training: |
| 122 | + labels.update({ |
| 123 | + 'id': |
| 124 | + inputs['image/id'], |
| 125 | + 'image_info': |
| 126 | + image_info, |
| 127 | + 'is_crowd': |
| 128 | + preprocess_ops.clip_or_pad_to_fixed_size( |
| 129 | + is_crowd, self._params.max_num_boxes), |
| 130 | + 'gt_boxes': |
| 131 | + preprocess_ops.clip_or_pad_to_fixed_size( |
| 132 | + gt_boxes, self._params.max_num_boxes), |
| 133 | + }) |
| 134 | + |
| 135 | + return image, labels |
| 136 | + |
| 137 | + def _transform_and_batch_fn( |
| 138 | + self, |
| 139 | + dataset, |
| 140 | + input_context: Optional[tf.distribute.InputContext] = None): |
| 141 | + """Preprocess and batch.""" |
| 142 | + dataset = dataset.map( |
| 143 | + self.preprocess, num_parallel_calls=tf.data.experimental.AUTOTUNE) |
| 144 | + per_replica_batch_size = input_context.get_per_replica_batch_size( |
| 145 | + self._params.global_batch_size |
| 146 | + ) if input_context else self._params.global_batch_size |
| 147 | + dataset = dataset.batch( |
| 148 | + per_replica_batch_size, drop_remainder=self._params.is_training) |
| 149 | + return dataset |
| 150 | + |
| 151 | + def load(self, input_context: Optional[tf.distribute.InputContext] = None): |
| 152 | + """Returns a tf.dataset.Dataset.""" |
| 153 | + reader = input_reader.InputReader( |
| 154 | + params=self._params, |
| 155 | + decoder_fn=None, |
| 156 | + transform_and_batch_fn=self._transform_and_batch_fn) |
| 157 | + return reader.read(input_context) |
0 commit comments