Post

03.23~24 Progress

03.23~24 Progress
  • GEBD 모델 Test
  • Audio Base Model 생각하기

image-19 오픈 소스이면서 체크포인트가 있는 모델들로 선정

EfficientGEBD

입력

mp4 영상을 3프레임마다 1장 샘플링 (60fps → 20fps) 224×224 리사이즈 → ImageNet 정규화 각 프레임마다 앞뒤 10프레임 묶음(window) 을 함께 입력

추론

CSN(Channel-Separated Network) 백본으로 시각 특징 추출 각 프레임 위치에서 “전후 장면이 얼마나 다른가”를 비교해 0~1 사이 경계 score 출력

CSN(Channel-Separated Network)? 비디오에서 시각 특징을 뽑는 3D CNN 백본 일반 이미지는 2D CNN(H×W)으로 특징을 뽑는데, 비디오는 시간 축이 추가돼서 3D CNN(H×W×T)이 필요하다. 그래서 CSN 사용

후처리

10프레임 window 내 score를 midmax 방식으로 집계 (중간 4프레임의 최대값) 연속으로 threshold(0.35) 넘는 구간을 하나의 그룹으로 묶음 그룹 내 score 최대 지점만 경계로 선택 (group_peaks)

midmax 10프레임 중 앞 뒤 3개씩은 제외하고 가운데 4개 중 max값을 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
## inference.py

# gradient를 추적하지 않게 하는 데코레이터
# 추론 과정이기 때문에 역전파하지 말라고 적어놓은 것
@torch.no_grad()
def main(args):
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model = E2EModel()
    # checkpoint
    state_dict = torch.load('E2EModel.pth')
    # 가중치 넣기
    model.load_state_dict(state_dict)

	# 모델 device에 올리기
    model = model.to(device)
    model.eval()

	# video 가져와서 정보들 가져왔음.
    imgs, frame_indices, fps, total_frames = load_video(args.video)
    seconds = total_frames / fps

	# 이미지들도 device에 올리기
	"""
	Image의 형식은 (T, C, H, W)
	T: 시간축 프레임 수
	C: 채널
	H, W: 이미지 크기
	로 구성되어 있음. 원래 학습 때는 Batch Size만큼 처리하기 때문에
	None을 통해 배치 사이즈 1을 설정하고 넣어주는 거
	"""
    inputs = imgs.to(device)[None]
    # 모델에 넣고 score 계산하기
    scores = model(inputs)[0].cpu().numpy()

	# 
    threshold = args.threshold
    det_t = np.array(get_idx_from_score_by_threshold(threshold=threshold,
                                                     seq_indices=frame_indices,
                                                     seq_scores=scores)) / fps

    print(f'Video path: {args.video}')
    print(f'Sampled frames: {len(frame_indices)}')
    print(f'Video FPS: {fps:.0f}')
    print(f'Video Duration: {seconds:.1f}s')
    print(f'Number Boundaries: {len(det_t)}')
    print(list(map(lambda t: round(t, 1), det_t)))

load_video

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def load_video(video_path, dim=224, sample_rate=3):
    ## 비디오 열기
    vidcap = cv2.VideoCapture(video_path)
    ## meta 정보가져오기
    nb_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = vidcap.get(cv2.CAP_PROP_FPS)
    width = vidcap.get(cv2.CAP_PROP_FRAME_WIDTH)  # float
    height = vidcap.get(cv2.CAP_PROP_FRAME_HEIGHT)  # float
    if (width == 0) or (height == 0):
        print(video_path, 'not successfully loaded, drop ..')
        quit()

    images = []
    frame_indices = []
    
    ## 프레임 변환 규칙 준비
    ## 각 프레임에 대해 ToTensor(), ImageNet mean/std 정규화를 적용할 transformer
    transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406],
                             std=[0.229, 0.224, 0.225])
    ])

    success, image = vidcap.read()
    count = 1
    ## frame을 하나씩 읽으면서 sampling
    while success:
	    ## sample_rate에 해당할때만 처리 sample_rate == 3 -> 1, 4, 7 ....
        if count % sample_rate == 1:
	        ## 선택된 프레임을 모델 입력 형태로 변환
	        ## 사이즈
            image = cv2.resize(image, (dim, dim), interpolation=cv2.INTER_LINEAR)
            ## OpenCV 기본BGR를 RGB로 변환
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            ## transform(image)로 적용
            ## 각 frame은 (3, 224, 224) 텐서가 된다.
            images.append(transform(image))
            ## 프레임 번호도 같이 저장
            frame_indices.append(count)
        success, image = vidcap.read()
        count += 1
    vidcap.release()

	## 프레임 리스트를 하나의 텐서로 만들기
    images = torch.stack(images, dim=0)
    ## 최종 Images shape는 (T, 3, 224, 224)
    ## T는 sampling된 frame number
    return images, frame_indices, fps, nb_frames

get_idx_from_score_by_threshold

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def get_idx_from_score_by_threshold(threshold=0.5, seq_indices=None, seq_scores=None):
	## 시퀀스 np로 변경하기
    seq_indices = np.array(seq_indices)
    seq_scores = np.array(seq_scores)
    bdy_indices = []
    internals_indices = []
    for i in range(len(seq_scores)):
        if seq_scores[i] >= threshold:
            internals_indices.append(i)
        elif seq_scores[i] < threshold and len(internals_indices) != 0:
            bdy_indices.append(internals_indices)
            internals_indices = []

        if i == len(seq_scores) - 1 and len(internals_indices) != 0:
            bdy_indices.append(internals_indices)

    bdy_indices_in_video = []
    if len(bdy_indices) != 0:
        for internals in bdy_indices:
            center = int(np.mean(internals))
            bdy_indices_in_video.append(seq_indices[center])
    return bdy_indices_in_video

E2EModel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
class E2EModel(Module):
    def __init__(self):
        super().__init__()
        ## 백본이 뽑아내는 원본 feature 차원을 2048
        in_feat_dim = 2048
        ## 내부 표현 차원을 512로 줄여서 사용
        dim = 512
        ## 좌/우 문맥을 볼 떄 사용할 시간 커널 크기
        self.kernel_size = 8
        ## backbone
        self.backbone = CSN()
        ## 2048 차원에서 512차원으로 투영하는 MLP
        self.trans_imgs_embedding = nn.Sequential(
            nn.Linear(in_feat_dim, dim),
            nn.ReLU(),
            nn.Linear(dim, dim),
        )

		## 현재 시점 기준으로 왼쪽 구간, 오른쪽 구간 feature를 뽑는 모듈
        self.extractor = LeftRightFeatureExtractor(dim, stride=1, kernel_size=self.kernel_size)

		"""
		시간축 1D convolution 블록입니다.
		- 각 시점 feature를 주변 시점과 섞어 temporal context를 반영
		- 채널 수는 계속 512 유지
		- kernel_size=3, padding=1이라 길이는 유지
		- Conv-BN-ReLU를 4번 반복
		"""
        self.temporal_embedding = nn.Sequential(
            nn.Conv1d(dim, dim, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm1d(dim),
            nn.ReLU(),
            nn.Conv1d(dim, dim, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm1d(dim),
            nn.ReLU(),
            nn.Conv1d(dim, dim, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm1d(dim),
            nn.ReLU(),
            nn.Conv1d(dim, dim, kernel_size=3, stride=1, padding=1),
            nn.BatchNorm1d(dim),
            nn.ReLU(),
        )

        self.left_temporal_model = SelfAttention(dim)
        self.right_temporal_model = SelfAttention(dim)

        self.output = nn.Sequential(
            nn.Linear(dim * 2 + dim * 2, dim),
            nn.ReLU(),
            nn.Linear(dim, dim * 2),
            nn.Dropout(0.2),
            nn.LayerNorm(dim * 2)
        )

        self.classifier = nn.Linear(
            in_features=dim * 2,
            out_features=1,
        )

    def forward(self, x):
		## x의 shape가 (B, T, C, H, W) [0]은 배치 크기
        B = x.shape[0]
        ## CSN backbone으로 비디오 feature를 추출, x는 비디오 프레임 시퀀스
        ## 출력은 시공간 feature map
        x = self.backbone(x)
        ## 5차원 텐서를 시간 별로 spatial pooling -> B T를 합침
        x = einops.rearrange(x, 'b c t h w -> (b t) c h w')

		## 각 시간 위치에 spatial feature map을 전역 평균 풀링해서 벡터로 만든다.
		## 2D feature map을 1개의 벡터로 압축하는 역할
		## [PyTorch Quantization에서 AdaptiveAvgPool2d를 다루는 3가지 팁](https://runebook.dev/ko/docs/pytorch/generated/torch.ao.nn.quantized.functional.adaptive_avg_pool2d#google_vignette)
        x = F.adaptive_avg_pool2d(x, 1).flatten(1)
        x = self.trans_imgs_embedding(x)
        
        ## 아까 합쳤던 B T를 다시 배치와 시간축으로 나눈다.
        x = einops.rearrange(x, '(b t) c -> b c t', b=B)  # (4, 512, 100)
		## 현재 시점의 원번 temporal feature를 따로 저장
		## 나중에 left/right self-attention 계산에 적용
        origin_x = x

		## 1D convolution 블록으로 시간축 문맥을 반영
        x = self.temporal_embedding(x)

		## LeftRightFeatureExtractor를 통해 좌측 window와 우측 window feature를 뽑는다. feats에는 현재 시점 기준으로 앞/뒤 문맥이 들어있다.
        feats = self.extractor(x)  # b t c

		## origin_x를 이용해 왼쪽 문맥만 따로 attention으로 요약
		## => 현재 시점을 볼 때 "이전 흐름"을 요약한 feature
        left_temporal_feats = temporal_features(origin_x, self.left_temporal_model, k=self.kernel_size, mode='left')
        ## 오른쪽 문맥도 흐름을 요약
        right_temporal_feats = temporal_features(origin_x, self.right_temporal_model, k=self.kernel_size, mode='right')
        #
        
        ## 세 종류의 feature를 이어붙이기
        ## 현재 시점 판단에 필요한 문맥 정보를 한 feature로 모은 것
        feats = torch.cat([feats, left_temporal_feats, right_temporal_feats], dim=-1)
        ## 합쳐진 feature를 최종 분류용 표현으로 다시 변환
        feats = self.output(feats)
        ## 각 시간 위치마다 boundary 여부를 나타내는 logit 1개를 계산
        logits = self.classifier(feats)  # b t 1
        ## logit을 0~1 사이로 바꾼다. -> boundary score
        ## shape은 (B,T)
        scores = torch.sigmoid(logits)[:, :, 0]  
        return scores

DDM-net

입력

프레임을 미리 이미지로 추출해서 디스크에 저장 (kinetics_GEBD_RGB/) DataAssets/multi-frames-GEBD-test-5.pkl — 각 프레임 중심으로 앞뒤 5프레임씩 묶은 멀티프레임 묶음

추론

ResNet 백본으로 각 프레임 특징 추출 Dual-level 구조: 프레임 간 차이(local)와 시퀀스 전체 흐름(global)을 동시에 봄 Softmax로 각 프레임이 경계일 확률 출력 → bdy_scores

후처리

score pkl 파일로 저장 후 별도로 NMS 적용 NMS window 안에서 최대 score 지점만 남김

Non-Maximum Suppression(NMS)


비교

| | EfficientGEBD | DDM | | —– | ——————– | ————————— | | 입력 단위 | 10프레임 묶음 (앞뒤 window) | 10프레임 묶음 (앞뒤 5장) | | 백본 | 3D CSN (시공간 동시 추출) | 2D ResNet (프레임별 독립 추출 후 합산) |


실험

입력 데이터

image-20

결과

image-21


Audio Base Model

image-22

This post is licensed under CC BY 4.0 by the author.