"tasks/knwl_dialo/README.md" did not exist on "492fdf83983c4791ed423a51dbc5bbaba25d8a27"
video_input.py 14.9 KB
Newer Older
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
1
# Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
2
3
4
5
6
7
8
9
10
11
12
13
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Yeqing Li's avatar
Yeqing Li committed
14

Abdullah Rashwan's avatar
Abdullah Rashwan committed
15
16
"""Parser for video and label datasets."""

Yeqing Li's avatar
Yeqing Li committed
17
from typing import Dict, Optional, Tuple, Union
Abdullah Rashwan's avatar
Abdullah Rashwan committed
18
19
20
21
22
23
24

from absl import logging
import tensorflow as tf

from official.vision.beta.configs import video_classification as exp_cfg
from official.vision.beta.dataloaders import decoder
from official.vision.beta.dataloaders import parser
Dan Kondratyuk's avatar
Dan Kondratyuk committed
25
from official.vision.beta.ops import augment
Abdullah Rashwan's avatar
Abdullah Rashwan committed
26
27
28
29
30
31
from official.vision.beta.ops import preprocess_ops_3d

IMAGE_KEY = 'image/encoded'
LABEL_KEY = 'clip/label/index'


32
33
34
35
def process_image(image: tf.Tensor,
                  is_training: bool = True,
                  num_frames: int = 32,
                  stride: int = 1,
36
                  random_stride_range: int = 0,
37
38
39
40
41
42
43
44
45
                  num_test_clips: int = 1,
                  min_resize: int = 256,
                  crop_size: int = 224,
                  num_crops: int = 1,
                  zero_centering_image: bool = False,
                  min_aspect_ratio: float = 0.5,
                  max_aspect_ratio: float = 2,
                  min_area_ratio: float = 0.49,
                  max_area_ratio: float = 1.0,
Dan Kondratyuk's avatar
Dan Kondratyuk committed
46
                  augmenter: Optional[augment.ImageAugment] = None,
47
                  seed: Optional[int] = None) -> tf.Tensor:
Abdullah Rashwan's avatar
Abdullah Rashwan committed
48
49
50
51
52
53
54
55
56
  """Processes a serialized image tensor.

  Args:
    image: Input Tensor of shape [timesteps] and type tf.string of serialized
      frames.
    is_training: Whether or not in training mode. If True, random sample, crop
      and left right flip is used.
    num_frames: Number of frames per subclip.
    stride: Temporal stride to sample frames.
57
58
59
60
61
    random_stride_range: An int indicating the min and max bounds to uniformly
      sample different strides from the video. E.g., a value of 1 with stride=2
      will uniformly sample a stride in {1, 2, 3} for each video in a batch.
      Only used enabled training for the purposes of frame-rate augmentation.
      Defaults to 0, which disables random sampling.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
62
63
64
65
66
67
68
    num_test_clips: Number of test clips (1 by default). If more than 1, this
      will sample multiple linearly spaced clips within each video at test time.
      If 1, then a single clip in the middle of the video is sampled. The clips
      are aggreagated in the batch dimension.
    min_resize: Frames are resized so that min(height, width) is min_resize.
    crop_size: Final size of the frame after cropping the resized frames. Both
      height and width are the same.
Yin Cui's avatar
Yin Cui committed
69
    num_crops: Number of crops to perform on the resized frames.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
70
71
    zero_centering_image: If True, frames are normalized to values in [-1, 1].
      If False, values in [0, 1].
Yeqing Li's avatar
Yeqing Li committed
72
73
74
75
    min_aspect_ratio: The minimum aspect range for cropping.
    max_aspect_ratio: The maximum aspect range for cropping.
    min_area_ratio: The minimum area range for cropping.
    max_area_ratio: The maximum area range for cropping.
Dan Kondratyuk's avatar
Dan Kondratyuk committed
76
    augmenter: Image augmenter to distort each image.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
77
78
79
80
81
82
83
84
85
86
87
88
    seed: A deterministic seed to use when sampling.

  Returns:
    Processed frames. Tensor of shape
      [num_frames * num_test_clips, crop_size, crop_size, 3].
  """
  # Validate parameters.
  if is_training and num_test_clips != 1:
    logging.warning(
        '`num_test_clips` %d is ignored since `is_training` is `True`.',
        num_test_clips)

89
90
91
92
  if random_stride_range < 0:
    raise ValueError('Random stride range should be >= 0, got {}'.format(
        random_stride_range))

Abdullah Rashwan's avatar
Abdullah Rashwan committed
93
94
  # Temporal sampler.
  if is_training:
95
96
97
98
99
100
101
102
    if random_stride_range > 0:
      # Uniformly sample different frame-rates
      stride = tf.random.uniform(
          [],
          tf.maximum(stride - random_stride_range, 1),
          stride + random_stride_range,
          dtype=tf.int32)

Abdullah Rashwan's avatar
Abdullah Rashwan committed
103
104
105
106
107
108
109
110
111
112
113
114
    # Sample random clip.
    image = preprocess_ops_3d.sample_sequence(image, num_frames, True, stride,
                                              seed)
  elif num_test_clips > 1:
    # Sample linspace clips.
    image = preprocess_ops_3d.sample_linspace_sequence(image, num_test_clips,
                                                       num_frames, stride)
  else:
    # Sample middle clip.
    image = preprocess_ops_3d.sample_sequence(image, num_frames, False, stride)

  # Decode JPEG string to tf.uint8.
115
116
  if image.dtype == tf.string:
    image = preprocess_ops_3d.decode_jpeg(image, 3)
Abdullah Rashwan's avatar
Abdullah Rashwan committed
117
118

  if is_training:
Yin Cui's avatar
Yin Cui committed
119
120
    # Standard image data augmentation: random resized crop and random flip.
    image = preprocess_ops_3d.random_crop_resize(
Yeqing Li's avatar
Yeqing Li committed
121
122
123
        image, crop_size, crop_size, num_frames, 3,
        (min_aspect_ratio, max_aspect_ratio),
        (min_area_ratio, max_area_ratio))
Abdullah Rashwan's avatar
Abdullah Rashwan committed
124
    image = preprocess_ops_3d.random_flip_left_right(image, seed)
Dan Kondratyuk's avatar
Dan Kondratyuk committed
125
126
127

    if augmenter is not None:
      image = augmenter.distort(image)
Abdullah Rashwan's avatar
Abdullah Rashwan committed
128
  else:
Yin Cui's avatar
Yin Cui committed
129
130
    # Resize images (resize happens only if necessary to save compute).
    image = preprocess_ops_3d.resize_smallest(image, min_resize)
Yin Cui's avatar
Yin Cui committed
131
132
133
    # Crop of the frames.
    image = preprocess_ops_3d.crop_image(image, crop_size, crop_size, False,
                                         num_crops)
Abdullah Rashwan's avatar
Abdullah Rashwan committed
134
135
136
137
138

  # Cast the frames in float32, normalizing according to zero_centering_image.
  return preprocess_ops_3d.normalize_image(image, zero_centering_image)


139
140
141
142
143
def postprocess_image(image: tf.Tensor,
                      is_training: bool = True,
                      num_frames: int = 32,
                      num_test_clips: int = 1,
                      num_test_crops: int = 1) -> tf.Tensor:
Abdullah Rashwan's avatar
Abdullah Rashwan committed
144
145
146
147
148
149
150
151
152
153
154
155
156
  """Processes a batched Tensor of frames.

  The same parameters used in process should be used here.

  Args:
    image: Input Tensor of shape [batch, timesteps, height, width, 3].
    is_training: Whether or not in training mode. If True, random sample, crop
      and left right flip is used.
    num_frames: Number of frames per subclip.
    num_test_clips: Number of test clips (1 by default). If more than 1, this
      will sample multiple linearly spaced clips within each video at test time.
      If 1, then a single clip in the middle of the video is sampled. The clips
      are aggreagated in the batch dimension.
Yin Cui's avatar
Yin Cui committed
157
158
159
    num_test_crops: Number of test crops (1 by default). If more than 1, there
      are multiple crops for each clip at test time. If 1, there is a single
      central crop. The crops are aggreagated in the batch dimension.
Abdullah Rashwan's avatar
Abdullah Rashwan committed
160
161
162

  Returns:
    Processed frames. Tensor of shape
Yin Cui's avatar
Yin Cui committed
163
      [batch * num_test_clips * num_test_crops, num_frames, height, width, 3].
Abdullah Rashwan's avatar
Abdullah Rashwan committed
164
  """
Yin Cui's avatar
Yin Cui committed
165
166
167
168
169
  num_views = num_test_clips * num_test_crops
  if num_views > 1 and not is_training:
    # In this case, multiple views are merged together in batch dimenstion which
    # will be batch * num_views.
    image = tf.reshape(image, [-1, num_frames] + image.shape[2:].as_list())
Abdullah Rashwan's avatar
Abdullah Rashwan committed
170
171
172
173

  return image


174
175
176
def process_label(label: tf.Tensor,
                  one_hot_label: bool = True,
                  num_classes: Optional[int] = None) -> tf.Tensor:
Abdullah Rashwan's avatar
Abdullah Rashwan committed
177
178
179
180
181
182
183
184
185
186
187
188
  """Processes label Tensor."""
  # Validate parameters.
  if one_hot_label and not num_classes:
    raise ValueError(
        '`num_classes` should be given when requesting one hot label.')

  # Cast to tf.int32.
  label = tf.cast(label, dtype=tf.int32)

  if one_hot_label:
    # Replace label index by one hot representation.
    label = tf.one_hot(label, num_classes)
Yeqing Li's avatar
Yeqing Li committed
189
190
191
192
193
    if len(label.shape.as_list()) > 1:
      label = tf.reduce_sum(label, axis=0)
    if num_classes == 1:
      # The trick for single label.
      label = 1 - label
Abdullah Rashwan's avatar
Abdullah Rashwan committed
194
195
196
197
198
199
200
201
202
203

  return label


class Decoder(decoder.Decoder):
  """A tf.Example decoder for classification task."""

  def __init__(self, image_key: str = IMAGE_KEY, label_key: str = LABEL_KEY):
    self._context_description = {
        # One integer stored in context.
204
        label_key: tf.io.VarLenFeature(tf.int64),
Abdullah Rashwan's avatar
Abdullah Rashwan committed
205
206
207
    }
    self._sequence_description = {
        # Each image is a string encoding JPEG.
208
        image_key: tf.io.FixedLenSequenceFeature((), tf.string),
Abdullah Rashwan's avatar
Abdullah Rashwan committed
209
210
    }

Yeqing Li's avatar
Yeqing Li committed
211
212
213
214
215
216
217
218
219
220
221
222
  def add_feature(self, feature_name: str,
                  feature_type: Union[tf.io.VarLenFeature,
                                      tf.io.FixedLenFeature,
                                      tf.io.FixedLenSequenceFeature]):
    self._sequence_description[feature_name] = feature_type

  def add_context(self, feature_name: str,
                  feature_type: Union[tf.io.VarLenFeature,
                                      tf.io.FixedLenFeature,
                                      tf.io.FixedLenSequenceFeature]):
    self._context_description[feature_name] = feature_type

Abdullah Rashwan's avatar
Abdullah Rashwan committed
223
224
  def decode(self, serialized_example):
    """Parses a single tf.Example into image and label tensors."""
Yeqing Li's avatar
Yeqing Li committed
225
    result = {}
Abdullah Rashwan's avatar
Abdullah Rashwan committed
226
227
228
    context, sequences = tf.io.parse_single_sequence_example(
        serialized_example, self._context_description,
        self._sequence_description)
Yeqing Li's avatar
Yeqing Li committed
229
230
231
232
233
234
    result.update(context)
    result.update(sequences)
    for key, value in result.items():
      if isinstance(value, tf.SparseTensor):
        result[key] = tf.sparse.to_dense(value)
    return result
Abdullah Rashwan's avatar
Abdullah Rashwan committed
235
236


237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
class VideoTfdsDecoder(decoder.Decoder):
  """A tf.SequenceExample decoder for tfds video classification datasets."""

  def __init__(self, image_key: str = IMAGE_KEY, label_key: str = LABEL_KEY):
    self._image_key = image_key
    self._label_key = label_key

  def decode(self, features):
    """Decode the TFDS FeatureDict.

    Args:
      features: features from TFDS video dataset.
        See https://www.tensorflow.org/datasets/catalog/ucf101 for example.
    Returns:
      Dict of tensors.
    """
    sample_dict = {
        self._image_key: features['video'],
        self._label_key: features['label'],
    }
    return sample_dict


Abdullah Rashwan's avatar
Abdullah Rashwan committed
260
261
262
263
264
265
266
267
268
class Parser(parser.Parser):
  """Parses a video and label dataset."""

  def __init__(self,
               input_params: exp_cfg.DataConfig,
               image_key: str = IMAGE_KEY,
               label_key: str = LABEL_KEY):
    self._num_frames = input_params.feature_shape[0]
    self._stride = input_params.temporal_stride
269
    self._random_stride_range = input_params.random_stride_range
Abdullah Rashwan's avatar
Abdullah Rashwan committed
270
271
272
    self._num_test_clips = input_params.num_test_clips
    self._min_resize = input_params.min_image_size
    self._crop_size = input_params.feature_shape[1]
Yin Cui's avatar
Yin Cui committed
273
    self._num_crops = input_params.num_test_crops
Abdullah Rashwan's avatar
Abdullah Rashwan committed
274
275
276
277
    self._one_hot_label = input_params.one_hot
    self._num_classes = input_params.num_classes
    self._image_key = image_key
    self._label_key = label_key
278
    self._dtype = tf.dtypes.as_dtype(input_params.dtype)
Yeqing Li's avatar
Yeqing Li committed
279
    self._output_audio = input_params.output_audio
Yeqing Li's avatar
Yeqing Li committed
280
281
282
283
    self._min_aspect_ratio = input_params.aug_min_aspect_ratio
    self._max_aspect_ratio = input_params.aug_max_aspect_ratio
    self._min_area_ratio = input_params.aug_min_area_ratio
    self._max_area_ratio = input_params.aug_max_area_ratio
Yeqing Li's avatar
Yeqing Li committed
284
285
286
    if self._output_audio:
      self._audio_feature = input_params.audio_feature
      self._audio_shape = input_params.audio_feature_shape
Abdullah Rashwan's avatar
Abdullah Rashwan committed
287

Dan Kondratyuk's avatar
Dan Kondratyuk committed
288
289
290
291
292
293
294
295
296
297
298
299
300
    self._augmenter = None
    if input_params.aug_type is not None:
      aug_type = input_params.aug_type
      if aug_type == 'autoaug':
        logging.info('Using AutoAugment.')
        self._augmenter = augment.AutoAugment()
      elif aug_type == 'randaug':
        logging.info('Using RandAugment.')
        self._augmenter = augment.RandAugment()
      else:
        raise ValueError('Augmentation policy {} is not supported.'.format(
            aug_type))

Abdullah Rashwan's avatar
Abdullah Rashwan committed
301
302
303
304
305
306
  def _parse_train_data(
      self, decoded_tensors: Dict[str, tf.Tensor]
  ) -> Tuple[Dict[str, tf.Tensor], tf.Tensor]:
    """Parses data for training."""
    # Process image and label.
    image = decoded_tensors[self._image_key]
307
    image = process_image(
Abdullah Rashwan's avatar
Abdullah Rashwan committed
308
309
310
311
        image=image,
        is_training=True,
        num_frames=self._num_frames,
        stride=self._stride,
312
        random_stride_range=self._random_stride_range,
Abdullah Rashwan's avatar
Abdullah Rashwan committed
313
314
        num_test_clips=self._num_test_clips,
        min_resize=self._min_resize,
Yeqing Li's avatar
Yeqing Li committed
315
316
317
318
        crop_size=self._crop_size,
        min_aspect_ratio=self._min_aspect_ratio,
        max_aspect_ratio=self._max_aspect_ratio,
        min_area_ratio=self._min_area_ratio,
Dan Kondratyuk's avatar
Dan Kondratyuk committed
319
320
        max_area_ratio=self._max_area_ratio,
        augmenter=self._augmenter)
321
    image = tf.cast(image, dtype=self._dtype)
Dan Kondratyuk's avatar
Dan Kondratyuk committed
322

Yeqing Li's avatar
Yeqing Li committed
323
    features = {'image': image}
Yeqing Li's avatar
Yeqing Li committed
324
325

    label = decoded_tensors[self._label_key]
326
    label = process_label(label, self._one_hot_label, self._num_classes)
Abdullah Rashwan's avatar
Abdullah Rashwan committed
327

Yeqing Li's avatar
Yeqing Li committed
328
329
330
331
332
333
334
335
336
337
    if self._output_audio:
      audio = decoded_tensors[self._audio_feature]
      audio = tf.cast(audio, dtype=self._dtype)
      # TODO(yeqing): synchronize audio/video sampling. Especially randomness.
      audio = preprocess_ops_3d.sample_sequence(
          audio, self._audio_shape[0], random=False, stride=1)
      audio = tf.ensure_shape(audio, self._audio_shape)
      features['audio'] = audio

    return features, label
Abdullah Rashwan's avatar
Abdullah Rashwan committed
338
339
340
341
342
343

  def _parse_eval_data(
      self, decoded_tensors: Dict[str, tf.Tensor]
  ) -> Tuple[Dict[str, tf.Tensor], tf.Tensor]:
    """Parses data for evaluation."""
    image = decoded_tensors[self._image_key]
344
    image = process_image(
Abdullah Rashwan's avatar
Abdullah Rashwan committed
345
346
347
348
349
350
        image=image,
        is_training=False,
        num_frames=self._num_frames,
        stride=self._stride,
        num_test_clips=self._num_test_clips,
        min_resize=self._min_resize,
Yin Cui's avatar
Yin Cui committed
351
352
        crop_size=self._crop_size,
        num_crops=self._num_crops)
353
    image = tf.cast(image, dtype=self._dtype)
Yeqing Li's avatar
Yeqing Li committed
354
    features = {'image': image}
Yeqing Li's avatar
Yeqing Li committed
355
356

    label = decoded_tensors[self._label_key]
357
    label = process_label(label, self._one_hot_label, self._num_classes)
Abdullah Rashwan's avatar
Abdullah Rashwan committed
358

Yeqing Li's avatar
Yeqing Li committed
359
360
361
362
    if self._output_audio:
      audio = decoded_tensors[self._audio_feature]
      audio = tf.cast(audio, dtype=self._dtype)
      audio = preprocess_ops_3d.sample_sequence(
363
          audio, self._audio_shape[0], random=False, stride=1)
364
      audio = tf.ensure_shape(audio, self._audio_shape)
Yeqing Li's avatar
Yeqing Li committed
365
366
367
      features['audio'] = audio

    return features, label
Abdullah Rashwan's avatar
Abdullah Rashwan committed
368
369
370
371
372
373
374
375
376
377


class PostBatchProcessor(object):
  """Processes a video and label dataset which is batched."""

  def __init__(self, input_params: exp_cfg.DataConfig):
    self._is_training = input_params.is_training

    self._num_frames = input_params.feature_shape[0]
    self._num_test_clips = input_params.num_test_clips
Yin Cui's avatar
Yin Cui committed
378
    self._num_test_crops = input_params.num_test_crops
Abdullah Rashwan's avatar
Abdullah Rashwan committed
379

Yeqing Li's avatar
Yeqing Li committed
380
381
  def __call__(self, features: Dict[str, tf.Tensor],
               label: tf.Tensor) -> Tuple[Dict[str, tf.Tensor], tf.Tensor]:
Abdullah Rashwan's avatar
Abdullah Rashwan committed
382
    """Parses a single tf.Example into image and label tensors."""
383
    for key in ['image']:
Yeqing Li's avatar
Yeqing Li committed
384
      if key in features:
385
        features[key] = postprocess_image(
Yeqing Li's avatar
Yeqing Li committed
386
387
388
            image=features[key],
            is_training=self._is_training,
            num_frames=self._num_frames,
Yin Cui's avatar
Yin Cui committed
389
390
            num_test_clips=self._num_test_clips,
            num_test_crops=self._num_test_crops)
Yeqing Li's avatar
Yeqing Li committed
391
392

    return features, label