File size: 4,003 Bytes
78b768f
7ea733c
 
 
 
 
 
 
 
 
 
78b768f
7ea733c
 
 
 
 
 
 
 
78b768f
7ea733c
 
 
 
78b768f
 
 
 
 
7ea733c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78b768f
7ea733c
78b768f
7ea733c
78b768f
7ea733c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78b768f
7ea733c
 
 
 
 
 
 
 
 
 
 
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
# ✅ src/video_utils.py(返回 <image> prefix 支持多轮对话)
import numpy as np
import torch
from PIL import Image
from decord import VideoReader, cpu
import torchvision.transforms as T
from torchvision.transforms.functional import InterpolationMode

IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)

# 图像预处理 transform
def build_transform(input_size=448):
    return T.Compose([
        T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
        T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
        T.ToTensor(),
        T.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
    ])

# 视频帧采样策略
def get_frame_indices(num_frames, total_frames):
    indices = np.linspace(0, total_frames - 1, num_frames, dtype=int)
    return indices

# 构建 <image> token 的前缀信息
def build_image_prefix(num_frames: int) -> str:
    return ''.join([f"Frame{i+1}: <image>\n" for i in range(num_frames)])

# 视频处理为 patch tensor,并返回 <image> 前缀
def process_video_for_internvl3(video_path, num_segments=8, max_patch_per_frame=1, input_size=448):
    vr = VideoReader(video_path, ctx=cpu(0))
    total_frames = len(vr)
    frame_indices = get_frame_indices(num_segments, total_frames)
    transform = build_transform(input_size)

    pixel_values_list, num_patches_list = [], []
    for idx in frame_indices:
        img = Image.fromarray(vr[idx].asnumpy()).convert("RGB")
        patches = dynamic_preprocess(img, image_size=input_size, max_num=max_patch_per_frame)
        patch_tensors = [transform(tile) for tile in patches]
        patch_tensor = torch.stack(patch_tensors)
        pixel_values_list.append(patch_tensor)
        num_patches_list.append(patch_tensor.shape[0])

    pixel_values = torch.cat(pixel_values_list, dim=0).to(torch.bfloat16).cuda()
    image_prefix = build_image_prefix(len(num_patches_list))

    return pixel_values, num_patches_list, image_prefix

# 图像切块
def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=True):
    orig_width, orig_height = image.size
    aspect_ratio = orig_width / orig_height

    target_ratios = set(
        (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1)
        if i * j <= max_num and i * j >= min_num
    )
    target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])

    best_ratio = find_closest_aspect_ratio(aspect_ratio, target_ratios, orig_width, orig_height, image_size)
    target_width = image_size * best_ratio[0]
    target_height = image_size * best_ratio[1]
    blocks = best_ratio[0] * best_ratio[1]

    resized_img = image.resize((target_width, target_height))
    processed_images = []
    for i in range(blocks):
        box = (
            (i % (target_width // image_size)) * image_size,
            (i // (target_width // image_size)) * image_size,
            ((i % (target_width // image_size)) + 1) * image_size,
            ((i // (target_width // image_size)) + 1) * image_size
        )
        split_img = resized_img.crop(box)
        processed_images.append(split_img)

    if use_thumbnail and len(processed_images) != 1:
        thumbnail_img = image.resize((image_size, image_size))
        processed_images.append(thumbnail_img)

    return processed_images

# 找最接近原图比例的切块方案
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
    best_ratio_diff = float('inf')
    best_ratio = (1, 1)
    area = width * height
    for ratio in target_ratios:
        target_aspect = ratio[0] / ratio[1]
        diff = abs(aspect_ratio - target_aspect)
        if diff < best_ratio_diff or (diff == best_ratio_diff and area > 0.5 * image_size**2 * ratio[0] * ratio[1]):
            best_ratio_diff = diff
            best_ratio = ratio
    return best_ratio