-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathutils.py
More file actions
122 lines (100 loc) · 3.24 KB
/
utils.py
File metadata and controls
122 lines (100 loc) · 3.24 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import os
import random
import numpy as np
import torch
from torch.nn import functional as F
import kornia as K
from torchvision import transforms
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed) # GPU随机种子确定
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
os.environ["PYTHONHASHSEED"] = str(seed)
torch.use_deterministic_algorithms(True)
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
def get_rot_mat(theta):
theta = torch.tensor(theta)
return torch.tensor(
[
[torch.cos(theta), -torch.sin(theta), 0],
[torch.sin(theta), torch.cos(theta), 0],
]
)
def get_translation_mat(a, b):
return torch.tensor([[1, 0, a], [0, 1, b]])
def rot_img(x, scale):
theta = scale
dtype = torch.FloatTensor
if x.dim() == 3:
x = x.unsqueeze(0)
rot_mat = get_rot_mat(theta)[None, ...].type(dtype).repeat(x.shape[0], 1, 1)
grid = F.affine_grid(rot_mat, x.size()).type(dtype)
x = F.grid_sample(x, grid, padding_mode="reflection")
x = x.squeeze(0)
return x
def translation_img(x, translation):
a, b = translation
dtype = torch.FloatTensor
if x.dim() == 3:
x = x.unsqueeze(0)
rot_mat = get_translation_mat(a, b)[None, ...].type(dtype).repeat(x.shape[0], 1, 1)
grid = F.affine_grid(rot_mat, x.size()).type(dtype)
x = F.grid_sample(x, grid, padding_mode="reflection")
x = x.squeeze(0)
return x
def hflip_img(x, **kwargs):
if x.dim() == 3:
x = x.unsqueeze(0)
x = K.geometry.transform.hflip(x)
x = x.squeeze(0)
return x
def vflip_img(x, **kwargs):
if x.dim() == 3:
x = x.unsqueeze(0)
x = K.geometry.transform.vflip(x)
x = x.squeeze(0)
return x
def add_gaussian_noise(x, scale=0.05):
std = scale
noise_mask = torch.randn(x.shape[-2:]) > 3
noise = torch.randn_like(x) * std # mean = 0
noised_img = (x + noise) * noise_mask
noise_img = torch.where(noised_img > 0, noised_img, x)
return noise_img
def cos_sim(a_norm, b_norm):
if len(a_norm.shape) == 2:
sim_mt = b_norm @ a_norm.transpose(1, 0)
elif len(a_norm.shape) == 1:
sim_mt = b_norm @ a_norm
else:
raise NotImplementedError
return sim_mt
# 定义一个自定义的噪音类
class AddGaussianNoise(object):
def __init__(self, std=1.0, p=0.5):
"""
mean: 高斯噪声的均值
std: 高斯噪声的标准差
p: 添加噪音的概率
"""
self.std = std
self.p = p
def __call__(self, x):
"""
在数据张量上应用噪音
"""
if random.random() < self.p:
return x
if not isinstance(x, torch.Tensor):
x = transforms.ToTensor()(x)
noise_mask = (torch.randn(x.shape[-2:]) > 3).int()
noise = torch.randn_like(x) * self.std # mean = 0
noised_img = (1 - noise_mask) * x + noise * x * noise_mask
noised_img = torch.clamp(noised_img, 0.0, 1.0)
return transforms.ToPILImage()(noised_img)
def __repr__(self):
return self.__class__.__name__ + f"(std={self.std}, p={self.p})"