AI Logic

Architectures

TransNet V2

Updated:

Architecture of TransNet V2. Left: the overall flow (48 × 27 frames pass three times through two DDCNN V2 cells, an addition, and average pooling; the learnable similarity and the RGB color-histogram similarity are concatenated; after a fully connected layer and dropout, the network splits into two heads that predict the middle frame of a transition and all frames of a transition). Top right: inside a DDCNN V2 cell (four branches of a spatial 1×3×3 convolution followed by a temporal 3×1×1 convolution with dilation rates 1, 2, 4, and 8 are concatenated, then batch normalization and ReLU). Bottom right: computing the learnable similarity (50 frames before and after are taken from the cosine-similarity matrix).

Background and Overview

TransNet V2 is a shot boundary detection network that shrinks a sequence of video frames, reads it with 3D convolutions, and predicts whether each frame is a shot change (transition). It was presented in 2020 by Souček and Lokoč of Charles University in Prague, who released the trained model along with the training and evaluation code.

A shot is a continuous sequence of frames captured by one camera without interruption. Shot changes include cuts, which switch in a single frame, and gradual transitions, which take several frames or more (such as dissolves, where the preceding and following footage overlap). Splitting a video into shots is the first step for video retrieval, summarization, and tasks such as segmenting a film into scenes.

Although the problem is long-standing, the paper states that it cannot yet be considered solved.

  • When fast camera or object motion abruptly changes the appearance, it is mistaken for a transition (false positives).
  • Long transitions may be missed even when the training data contains the same kind.
  • Trained models may fail to handle new kinds of transitions from editing software.

TransNet V2 improves on the authors' earlier TransNet in the following four ways.

  1. Factorize 3D convolutions into spatial (height and width) and temporal convolutions
  2. Add batch normalization and connections that skip over cells and are added back
  3. Add frame-to-frame similarities as features
  4. Use two prediction heads (the middle frame of a transition, and all frames of a transition)

On three datasets, ClipShots, BBC Planet Earth, and RAI, all compared methods were re-evaluated with the same evaluation script. TransNet V2 achieved the best F1 scores on ClipShots and BBC and values comparable to the other methods on RAI.

Theory: Architecture and Prediction

TransNet V2 takes NN consecutive frames (N=100N = 100 in both training and inference) and outputs, for each frame, the probability that it is a transition (left of the figure at the top of the article).

Overall flow

  1. Downscale: Each frame is resized to 48 × 27 pixels, a setting inherited from the earlier TransNet.
  2. Stack two DDCNN V2 cells, add, and downsample: Two DDCNN V2 cells (described below) are stacked, the output of the first cell is added to the output of the second (residual connection), and 2 × 2 average pooling is applied spatially. This is repeated three times, increasing the number of channels 64 → 128 → 256. The shape becomes N×6×3×256N \times 6 \times 3 \times 256.
  3. Concatenate with similarities: This is flattened to N×4608N \times 4608 and concatenated with the learnable similarity (N×128N \times 128) and the RGB color-histogram similarity (N×128N \times 128), giving N×4864N \times 4864.
  4. Predict: A fully connected layer with ReLU produces N×1024N \times 1024, dropout (rate 0.5) is applied, and two heads (fully connected layer and sigmoid) output per-frame probabilities.

DDCNN V2 cell (factorized 3D convolution)

The earlier TransNet stacked six cells (DDCNN), each consisting of four 3 × 3 × 3 3D convolutions in parallel with temporal dilation rates of 1, 2, 4, and 8, giving a receptive field of 97 frames. TransNet V2 factorizes each branch as follows (top right of the figure at the top of the article).

  1. Spatial convolution: 1 × 3 × 3 (time × height × width) captures patterns within a single frame (2F2F filters).
  2. Temporal convolution: 3 × 1 × 1 compares temporally distant frames in each of the four branches with dilation rates 1, 2, 4, and 8 (FF filters).
  3. Concatenation and normalization: The four branches are concatenated into 4F4F channels, followed by batch normalization and ReLU.

The paper argues that factorizing a 3D convolution into "a spatial 2D convolution → a temporal 1D convolution" makes the network learn image feature extraction and temporal comparison separately, and that with fewer spatial filters the parameter count also drops, which helps prevent overfitting to the synthetically generated training data.

Frame-to-frame similarities

Frames become dissimilar across a transition. To use this cue directly, two kinds of similarity are added (bottom right of the figure at the top of the article).

  1. The outputs of the three average-pooling stages are each averaged spatially and concatenated (N×448N \times 448), then projected to N×128N \times 128 by a fully connected layer and normalized. The RGB color distribution is represented as a histogram with 83=5128^3 = 512 bins.
  2. The cosine similarity is computed for every pair of frames, forming an N×NN \times N matrix.
  3. For each frame, the similarities with the 50 frames before and the 50 frames after are extracted into a 101-dimensional vector (0 outside the range).
  4. A fully connected layer with ReLU produces N×128N \times 128.

Two prediction heads

  • First head: Regardless of the transition length, only the single middle frame of a transition is labeled 1 during training. Only this head is used for prediction.
  • Second head: All frames of a transition are labeled 1 during training. It is used only during training, to teach the network what a transition is and how long it lasts.

Determining transitions from per-frame probabilities

  1. The video is fed in windows of 100 frames, and only the predictions for the middle 50 frames are used, excluding the edges where context before or after is insufficient.
  2. Each run of consecutive frames whose first-head probability exceeds the threshold θ\theta (0.5 for TransNet V2) is treated as one transition.
  3. The frames between transitions form one shot.

Training Data and Training Setup

Shot boundary detection requires large amounts of labeled data containing both cuts and gradual transitions. Following prior work, TransNet V2 generates transitions synthetically during training.

Generating synthetic transitions

  1. From TRECVID IACC.3 and ClipShots, which have hundreds of thousands of annotated shot boundaries, 300 frames each are extracted from the beginning, middle, and end of every scene in advance.
  2. At each training step, two random segments are chosen and cropped to 100 frames.
  3. The two are joined at a random position with a random type of transition (a cut, or a dissolve of 2–30 frames). Sequences without a transition are not used (because the sequences already used are considered to contain confusing examples).

Real vs. synthetic transitions (Table 1 of the paper; F1 score on the validation data, mean and standard deviation over the best 3 epochs of each of 3 training runs)

Training dataClipShotsBBCRAI
100% real transitions66.4 ± 1.396.3 ± 0.586.4 ± 1.2
50% real, 50% synthetic cuts68.2 ± 0.796.6 ± 0.784.4 ± 0.6
50% real, 50% synthetic dissolves75.3 ± 0.896.3 ± 0.590.7 ± 0.7
15% real, 35% synthetic cuts, 50% synthetic dissolves77.0 ± 0.896.5 ± 0.591.2 ± 1.1
50% synthetic cuts, 50% synthetic dissolves77.5 ± 0.395.1 ± 0.593.2 ± 0.9

Mixing in synthetic transitions was clearly better than training only on the real transitions of ClipShots (4039 videos, 128,636 cuts, 38,120 gradual transitions). The paper states that synthetic transitions improve performance substantially and that it is also important for the training data to contain many gradual dissolves; the final model is trained with "15% real, 35% synthetic cuts, 50% synthetic dissolves".

Data augmentation

All frames within a single shot receive the same augmentation, because varying it per frame would turn appearance changes into fake transitions.

  • Horizontal flip (probability 0.5), vertical flip (probability 0.1)
  • Changes to saturation, contrast, brightness, and hue
  • With probability 0.05, the Equalize, Posterize, and Color operations also found in the AutoAugment implementation
  • When generating synthetic transitions, for 10% of sequences, a color-matching step before joining (mimicking the visual similarity of shots from the same video)

Training setup (Section 2.2.4 of the paper)

  • Loss: cross-entropy for each of the two heads. For the first head, transition frames are weighted 5×; the loss of the second head is multiplied by 0.1. L2 weight regularization (coefficient 0.0001) is also added.
  • Optimization: SGD with momentum 0.9, fixed learning rate 0.01
  • Amount: one epoch is 750 batches of size 16, for 50 epochs (600,000 transitions in total). The best model is selected on a validation set split from the ClipShots training data.
  • Time: about 17 hours including validation on a single Tesla V100 (16GB)

Experimental Results

The paper compares F1 scores that combine cuts and gradual transitions on three datasets: the official ClipShots test set, BBC Planet Earth (BBC documentaries), and RAI (footage from an Italian broadcaster) (evaluation of shot boundary detection).

Comparison with prior work (Table 2 of the paper, F1 score)

ModelClipShotsBBCRAI
TransNet (earlier version)73.592.994.3
Hassanien et al. (DeepSBD)*75.992.693.9
Tang et al. (ResNet baseline)*76.189.392.8
TransNet V277.996.293.9

Entries marked * were re-evaluated by the paper's authors, with the best threshold selected on the test data.

TransNet V2 was the best on ClipShots and BBC and comparable to the others on RAI. All methods scored low on ClipShots; the paper notes that this largest dataset contains unannotated parts and frames incorrectly labeled as transitions.

Evaluation protocol

  • Detections off by up to 2 frames from a ground-truth transition are counted as hits. This is because the ground truth of some test sets contains small errors; the paper states that, against correct ground truth, the difference from the original evaluation method is small.
  • Because the released code of the compared methods covered only the network, their cut and gradual-transition probabilities were summed into one, assigned to the middle 8 frames of the 16-frame input, and re-evaluated. Their thresholds are the values that worked best on the test data (0.9 for DeepSBD, 0.8 for Tang et al.).
  • The threshold for TransNet V2 is fixed at 0.5 (0.1 for the earlier TransNet).

Practical Considerations

Keep the following points in mind when using TransNet V2.

  • Frames are read at 48 × 27: Because the input is very small, fine details are lost. The paper notes that sudden appearance changes caused by fast camera or object motion can be mistaken for transitions.
  • Do not use predictions at the edges: Of the 100-frame input, only the predictions for the middle 50 frames are used, excluding the edges where context is insufficient. When building inference yourself, shift the input by 50 frames so the windows overlap.
  • Only the first head is used for prediction: The second head (all frames of a transition) is for training and is not used in the paper's evaluation either. The released code returns the probabilities of both heads.
  • Changing the threshold trades precision against recall: The paper's 0.5 is a good starting value as is. If detections are too many or too few on your data, tune it on validation data.
  • Mainly cuts and dissolves are handled: Synthetic transitions are generated only as cuts and dissolves of 2–30 frames. For footage with many special transitions such as wipes, check for misses.

The F1 scores in the paper cannot be compared directly with values from other papers. Deviations of up to 2 frames from the ground truth count as hits, and the compared methods were re-evaluated with the best threshold chosen on the test data (the paper notes that this may make the compared methods' scores somewhat optimistic). When comparing with values from another paper, re-evaluate with the same tolerance, handling of transition types, and threshold selection.

Comparison with Other Methods

Comparing deep learning methods for shot boundary detection from the same viewpoints gives the following.

MethodTemporal modelingPost-processingTraining dataNotes
Hassanien et al. (DeepSBD)Outputs cut and gradual-transition probabilities for every 16 frames with C3DReduces false positives with an SVM and color-histogram differencesSynthetic transitionsOnly the network part is used in the paper's evaluation
Gygli3D convolutions onlyNoneSynthetic transitionsSmall network; falls short of Hassanien et al.
TransNet (earlier version)Six cells of 3 × 3 × 3 convolutions in parallel with dilation rates 1, 2, 4, 8 (receptive field of 97 frames)NoneSynthetic transitionsGygli's design without post-processing; accuracy comparable to Hassanien et al. (RAI)
TransNet V2Factorized spatial and temporal convolutions + frame-to-frame similaritiesNone (threshold only)15% real + 85% syntheticTwo prediction heads; trained model released

Rather than computing image CNN features per frame and then aggregating them, TransNet V2 belongs to the line of methods that process space and time together with 3D convolutions. On top of that, it explicitly adds "how similar the surrounding frames are", a cue for transitions, using both color histograms and learned features.

The relationship between shot boundary detection and the processing that follows is as follows.

  • Splitting into shots: Use shot boundary detection such as TransNet V2.
  • Grouping shots into story units (scenes): Use a method such as LGSS, which decides which shot boundaries are scene boundaries.

Rough guidelines for choosing:

  • To split large amounts of video into shots quickly: TransNet V2, whose trained model can be used as is, is a candidate.
  • To compare against prior work in an evaluation: Compare with the values from TransNet V2's released code using the same evaluation script (tolerance and datasets).

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
TransNet V2 (Souček & Lokoč 2020, Section 2.1 / Figure 1): DDCNN V2 cell and a small version without the similarities
Input: frames of shape (B, 3, T, 27, 48)  Output: per-frame transition scores (two heads)

To just use the trained model, use inference from the released code (github.com/soCzech/TransNetV2):
  model = TransNetV2("/path/to/weights_dir/")
  video_frames, single_frame_p, all_frame_p = model.predict_video("/path/to/video.mp4")
"""


class DDCNNV2Cell(nn.Module):
  def __init__(self, in_ch, F_, activation=True):
    super().__init__()
    self.branches = nn.ModuleList()
    for d in (1, 2, 4, 8):                           # temporal dilation rates
      self.branches.append(nn.Sequential(
        nn.Conv3d(in_ch, 2 * F_, (1, 3, 3), padding=(0, 1, 1), bias=False),                 # spatial convolution
        nn.Conv3d(2 * F_, F_, (3, 1, 1), padding=(d, 0, 0), dilation=(d, 1, 1), bias=False),  # temporal convolution
      ))
    self.bn = nn.BatchNorm3d(4 * F_, eps=1e-3)
    self.activation = activation

  def forward(self, x):
    x = self.bn(torch.cat([b(x) for b in self.branches], dim=1))   # concatenate the 4 branches: 4F channels
    return F.relu(x) if self.activation else x


class StackedDDCNNV2(nn.Module):
  """2 cells -> add the output of the first -> spatial 2x2 average pooling"""
  def __init__(self, in_ch, F_):
    super().__init__()
    self.cell1 = DDCNNV2Cell(in_ch, F_)
    self.cell2 = DDCNNV2Cell(4 * F_, F_, activation=False)
    self.pool = nn.AvgPool3d((1, 2, 2))

  def forward(self, x):
    shortcut = self.cell1(x)
    x = F.relu(self.cell2(shortcut)) + shortcut
    return self.pool(x)


class TinyTransNetV2(nn.Module):
  def __init__(self, F_=16):
    super().__init__()
    self.blocks = nn.Sequential(
      StackedDDCNNV2(3, F_),              # 64 channels
      StackedDDCNNV2(4 * F_, 2 * F_),     # 128 channels
      StackedDDCNNV2(8 * F_, 4 * F_),     # 256 channels
    )
    self.fc = nn.Linear(16 * F_ * 3 * 6, 1024)   # 256 x 3 x 6 = 4608 (the 128 + 128 similarities are omitted)
    self.drop = nn.Dropout(0.5)
    self.head_single = nn.Linear(1024, 1)        # middle frame of a transition (used for prediction)
    self.head_all = nn.Linear(1024, 1)           # all frames of a transition (training only)

  def forward(self, x):                          # x: (B, 3, T, 27, 48), values in 0-1
    x = self.blocks(x)                           # (B, 256, T, 3, 6)
    x = x.permute(0, 2, 1, 3, 4).flatten(2)      # (B, T, 4608)
    x = self.drop(F.relu(self.fc(x)))
    return self.head_single(x).squeeze(-1), self.head_all(x).squeeze(-1)


def loss_fn(single, all_, y_single, y_all):
  """Weight the middle transition frame 5x and the second head 0.1x (Section 2.2.4)"""
  l1 = F.binary_cross_entropy_with_logits(single, y_single, pos_weight=torch.tensor(5.0))
  l2 = F.binary_cross_entropy_with_logits(all_, y_all)
  return l1 + 0.1 * l2


def to_transitions(prob, threshold=0.5):
  """Turn each run of frames above the threshold into one transition (start, end)"""
  above = (prob > threshold).tolist()
  out, start = [], None
  for i, a in enumerate(above + [False]):
    if a and start is None:
      start = i
    elif not a and start is not None:
      out.append((start, i - 1))
      start = None
  return out


model = TinyTransNetV2()
frames = torch.rand(2, 3, 100, 27, 48)           # 2 clips, 100 frames, 48 x 27 pixels
y_single = torch.zeros(2, 100); y_single[:, 50] = 1          # middle frame of the transition
y_all = torch.zeros(2, 100); y_all[:, 46:55] = 1             # all frames of the transition (9-frame dissolve)

model.train()                                    # training: dropout and batch-norm statistic updates are active
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=1e-4)
s, a = model(frames)
loss = loss_fn(s, a, y_single, y_all)
optimizer.zero_grad()
loss.backward()
optimizer.step()

model.eval()                                     # inference: no dropout, batch norm uses the stored statistics
with torch.no_grad():
  s, _ = model(frames)
  prob = torch.sigmoid(s[0, 25:75])              # use only the middle 50 frames
  print(to_transitions(prob))

FAQ

Q. How does TransNet V2 differ from the earlier TransNet?
A.

There are four main differences. First, the 3 × 3 × 3 3D convolution is factorized into a spatial 1 × 3 × 3 convolution and a temporal 3 × 1 × 1 convolution. Second, batch normalization, an additive connection every two cells (residual connection), and spatial average pooling are introduced. Third, similarities with the 50 frames before and after are computed from RGB color histograms and learned features and added as features. Fourth, there are two heads, one predicting the middle frame of a transition and one predicting all frames of a transition.

Q. Why train on synthetically generated transitions?
A.

Because joining two segments with annotated shot boundaries makes it possible to create as many cuts and dissolves as needed, with exactly known ground-truth positions. In Table 1 of the paper, training only on the real transitions of ClipShots gave an F1 of 66.4 on the ClipShots validation data, while mixing in synthetic cuts and dissolves raised it to 77.0–77.5. The final model is trained with 15% real, 35% synthetic cuts, and 50% synthetic dissolves.

Q. What is the difference between shot boundary detection and scene segmentation?
A.

Shot boundary detection finds the points where the camera switches (cuts and dissolves) from changes in appearance between neighboring frames. Scene segmentation is the task of grouping many shots into story units, putting shots of the same event into the same scene even if they look different. TransNet V2 is a shot boundary detection model; to split into scenes, its output is passed to a method such as LGSS.

References

  1. Souček, T., & Lokoč, J. (2020). TransNet V2: An effective deep network architecture for fast shot transition detection. arXiv:2008.04838.
  2. soCzech/TransNetV2 (the authors' released code and trained models; inference-pytorch/transnetv2_pytorch.py).
  3. Hassanien, A., Elgharib, M., Selim, A., Hefeeda, M., & Matusik, W. (2017). Large-scale, Fast and Accurate Shot Boundary Detection through Spatio-temporal Convolutional Neural Networks. arXiv:1705.03281.
  4. Tang, S., Feng, L., Kuang, Z., Chen, Y., & Zhang, W. (2018). Fast Video Shot Transition Localization with Deep Structured Models. arXiv:1808.04234.
  5. Xie, S., Sun, C., Huang, J., Tu, Z., & Murphy, K. (2018). Rethinking Spatiotemporal Feature Learning: Speed-Accuracy Trade-offs in Video Classification. ECCV 2018. arXiv:1712.04851.