Fabrice-TIERCELIN commited on
Commit
9e7447b
·
verified ·
1 Parent(s): 9f557af

Upload 2 files

Browse files
video_super_resolution/color_fix.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ # --------------------------------------------------------------------------------
3
+ # Color fixed script from Li Yi (https://github.com/pkuliyi2015/sd-webui-stablesr/blob/master/srmodule/colorfix.py)
4
+ # --------------------------------------------------------------------------------
5
+ '''
6
+
7
+ import torch
8
+ from PIL import Image
9
+ from torch import Tensor
10
+ from torch.nn import functional as F
11
+
12
+ from torchvision.transforms import ToTensor, ToPILImage
13
+ from einops import rearrange
14
+
15
+ def adain_color_fix(target: Image, source: Image):
16
+ # Convert images to tensors
17
+ target = rearrange(target, 'T H W C -> T C H W') / 255
18
+ source = (source + 1) / 2
19
+
20
+ # Apply adaptive instance normalization
21
+ result_tensor_list = []
22
+ for i in range(0, target.shape[0]):
23
+ result_tensor_list.append(adaptive_instance_normalization(target[i].unsqueeze(0), source[i].unsqueeze(0)))
24
+
25
+ # Convert tensor back to image
26
+ result_tensor = torch.cat(result_tensor_list, dim=0).clamp_(0.0, 1.0)
27
+ result_video = rearrange(result_tensor, "T C H W -> T H W C") * 255
28
+
29
+ return result_video
30
+
31
+ def wavelet_color_fix(target, source):
32
+ # Convert images to tensors
33
+ target = rearrange(target, 'T H W C -> T C H W') / 255
34
+ source = (source + 1) / 2
35
+
36
+ # Apply wavelet reconstruction
37
+ result_tensor_list = []
38
+ for i in range(0, target.shape[0]):
39
+ result_tensor_list.append(wavelet_reconstruction(target[i].unsqueeze(0), source[i].unsqueeze(0)))
40
+
41
+ # Convert tensor back to image
42
+ result_tensor = torch.cat(result_tensor_list, dim=0).clamp_(0.0, 1.0)
43
+ result_video = rearrange(result_tensor, "T C H W -> T H W C") * 255
44
+
45
+ return result_video
46
+
47
+ def calc_mean_std(feat: Tensor, eps=1e-5):
48
+ """Calculate mean and std for adaptive_instance_normalization.
49
+ Args:
50
+ feat (Tensor): 4D tensor.
51
+ eps (float): A small value added to the variance to avoid
52
+ divide-by-zero. Default: 1e-5.
53
+ """
54
+ size = feat.size()
55
+ assert len(size) == 4, 'The input feature should be 4D tensor.'
56
+ b, c = size[:2]
57
+ feat_var = feat.reshape(b, c, -1).var(dim=2) + eps
58
+ feat_std = feat_var.sqrt().reshape(b, c, 1, 1)
59
+ feat_mean = feat.reshape(b, c, -1).mean(dim=2).reshape(b, c, 1, 1)
60
+ return feat_mean, feat_std
61
+
62
+ def adaptive_instance_normalization(content_feat:Tensor, style_feat:Tensor):
63
+ """Adaptive instance normalization.
64
+ Adjust the reference features to have the similar color and illuminations
65
+ as those in the degradate features.
66
+ Args:
67
+ content_feat (Tensor): The reference feature.
68
+ style_feat (Tensor): The degradate features.
69
+ """
70
+ size = content_feat.size()
71
+ style_mean, style_std = calc_mean_std(style_feat)
72
+ content_mean, content_std = calc_mean_std(content_feat)
73
+ normalized_feat = (content_feat - content_mean.expand(size)) / content_std.expand(size)
74
+ return normalized_feat * style_std.expand(size) + style_mean.expand(size)
75
+
76
+ def wavelet_blur(image: Tensor, radius: int):
77
+ """
78
+ Apply wavelet blur to the input tensor.
79
+ """
80
+ # input shape: (1, 3, H, W)
81
+ # convolution kernel
82
+ kernel_vals = [
83
+ [0.0625, 0.125, 0.0625],
84
+ [0.125, 0.25, 0.125],
85
+ [0.0625, 0.125, 0.0625],
86
+ ]
87
+ kernel = torch.tensor(kernel_vals, dtype=image.dtype, device=image.device)
88
+ # add channel dimensions to the kernel to make it a 4D tensor
89
+ kernel = kernel[None, None]
90
+ # repeat the kernel across all input channels
91
+ kernel = kernel.repeat(3, 1, 1, 1)
92
+ image = F.pad(image, (radius, radius, radius, radius), mode='replicate')
93
+ # apply convolution
94
+ output = F.conv2d(image, kernel, groups=3, dilation=radius)
95
+ return output
96
+
97
+ def wavelet_decomposition(image: Tensor, levels=5):
98
+ """
99
+ Apply wavelet decomposition to the input tensor.
100
+ This function only returns the low frequency & the high frequency.
101
+ """
102
+ high_freq = torch.zeros_like(image)
103
+ for i in range(levels):
104
+ radius = 2 ** i
105
+ low_freq = wavelet_blur(image, radius)
106
+ high_freq += (image - low_freq)
107
+ image = low_freq
108
+
109
+ return high_freq, low_freq
110
+
111
+ def wavelet_reconstruction(content_feat:Tensor, style_feat:Tensor):
112
+ """
113
+ Apply wavelet decomposition, so that the content will have the same color as the style.
114
+ """
115
+ # calculate the wavelet decomposition of the content feature
116
+ content_high_freq, content_low_freq = wavelet_decomposition(content_feat)
117
+ del content_low_freq
118
+ # calculate the wavelet decomposition of the style feature
119
+ style_high_freq, style_low_freq = wavelet_decomposition(style_feat)
120
+ del style_high_freq
121
+ # reconstruct the content feature with the style's high frequency
122
+ return content_high_freq + style_low_freq
video_super_resolution/dataset.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import glob
4
+ import torchvision
5
+ from einops import rearrange
6
+ from torch.utils import data as data
7
+ import torch.nn.functional as F
8
+ from torchvision import transforms
9
+ from PIL import Image
10
+
11
+ class PairedCaptionVideoDataset(data.Dataset):
12
+ def __init__(
13
+ self,
14
+ root_folders=None,
15
+ null_text_ratio=0.5,
16
+ num_frames=16
17
+ ):
18
+ super(PairedCaptionVideoDataset, self).__init__()
19
+
20
+ self.null_text_ratio = null_text_ratio
21
+ self.lr_list = []
22
+ self.gt_list = []
23
+ self.tag_path_list = []
24
+ self.num_frames = num_frames
25
+
26
+ # root_folders = root_folders.split(',')
27
+ for root_folder in root_folders:
28
+ lr_path = root_folder +'/lq'
29
+ tag_path = root_folder +'/text'
30
+ gt_path = root_folder +'/gt'
31
+
32
+ self.lr_list += glob.glob(os.path.join(lr_path, '*.mp4'))
33
+ self.gt_list += glob.glob(os.path.join(gt_path, '*.mp4'))
34
+ self.tag_path_list += glob.glob(os.path.join(tag_path, '*.txt'))
35
+
36
+ assert len(self.lr_list) == len(self.gt_list)
37
+ assert len(self.lr_list) == len(self.tag_path_list)
38
+
39
+ def __getitem__(self, index):
40
+
41
+ gt_path = self.gt_list[index]
42
+ vframes_gt, _, info = torchvision.io.read_video(filename=gt_path, pts_unit="sec", output_format="TCHW")
43
+ fps = info['video_fps']
44
+ vframes_gt = (rearrange(vframes_gt, "T C H W -> C T H W") / 255) * 2 - 1
45
+ # gt = self.trandform(vframes_gt)
46
+
47
+ lq_path = self.lr_list[index]
48
+ vframes_lq, _, _ = torchvision.io.read_video(filename=lq_path, pts_unit="sec", output_format="TCHW")
49
+ vframes_lq = (rearrange(vframes_lq, "T C H W -> C T H W") / 255) * 2 - 1
50
+ # lq = self.trandform(vframes_lq)
51
+
52
+ if random.random() < self.null_text_ratio:
53
+ tag = ''
54
+ else:
55
+ tag_path = self.tag_path_list[index]
56
+ with open(tag_path, 'r', encoding='utf-8') as file:
57
+ tag = file.read()
58
+
59
+ return {"gt": vframes_gt[:, :self.num_frames, :, :], "lq": vframes_lq[:, :self.num_frames, :, :], "text": tag, 'fps': fps}
60
+
61
+ def __len__(self):
62
+ return len(self.gt_list)
63
+
64
+
65
+ class PairedCaptionImageDataset(data.Dataset):
66
+ def __init__(
67
+ self,
68
+ root_folder=None,
69
+ ):
70
+ super(PairedCaptionImageDataset, self).__init__()
71
+
72
+ self.lr_list = []
73
+ self.gt_list = []
74
+ self.tag_path_list = []
75
+
76
+ lr_path = root_folder +'/sr_bicubic'
77
+ gt_path = root_folder +'/gt'
78
+
79
+ self.lr_list += glob.glob(os.path.join(lr_path, '*.png'))
80
+ self.gt_list += glob.glob(os.path.join(gt_path, '*.png'))
81
+
82
+ assert len(self.lr_list) == len(self.gt_list)
83
+
84
+ self.img_preproc = transforms.Compose([
85
+ transforms.ToTensor(),
86
+ ])
87
+
88
+ # Define the crop size (e.g., 256x256)
89
+ crop_size = (720, 1280)
90
+
91
+ # CenterCrop transform
92
+ self.center_crop = transforms.CenterCrop(crop_size)
93
+
94
+ def __getitem__(self, index):
95
+
96
+ gt_path = self.gt_list[index]
97
+ gt_img = Image.open(gt_path).convert('RGB')
98
+ gt_img = self.center_crop(self.img_preproc(gt_img))
99
+
100
+ lq_path = self.lr_list[index]
101
+ lq_img = Image.open(lq_path).convert('RGB')
102
+ lq_img = self.center_crop(self.img_preproc(lq_img))
103
+
104
+ example = dict()
105
+
106
+ example["lq"] = (lq_img.squeeze(0) * 2.0 - 1.0).unsqueeze(1)
107
+ example["gt"] = (gt_img.squeeze(0) * 2.0 - 1.0).unsqueeze(1)
108
+ example["text"] = ""
109
+
110
+ return example
111
+
112
+ def __len__(self):
113
+ return len(self.gt_list)