| 77 | |
| 78 | |
| 79 | def gaussianBlurDynamic(image, apply_prob=0.5): |
| 80 | expand_batch_dim = len(image.size()) == 3 |
| 81 | if expand_batch_dim: |
| 82 | image = image.unsqueeze(0) |
| 83 | |
| 84 | batch_size = image.size(0) |
| 85 | result = torch.zeros_like(image, device=image.device) |
| 86 | |
| 87 | for index in range(batch_size): |
| 88 | if random.random() < apply_prob: |
| 89 | sigma = random.uniform(0.1, 2.0) |
| 90 | kernel_size = int(sigma * 4 + 0.5) |
| 91 | radius = int(kernel_size / 2) |
| 92 | kernel_size = radius * 2 + 1 |
| 93 | |
| 94 | # x = torch.arange(-radius, radius + 1).cuda() |
| 95 | x = torch.arange(-radius, radius + 1, device=image.device) |
| 96 | x = x.to(image.dtype) |
| 97 | blur_filter = torch.exp(-torch.pow(x, 2.0) / (2.0 * (sigma**2))) |
| 98 | blur_filter = blur_filter.div(blur_filter.sum()) |
| 99 | blur_v = torch.reshape(blur_filter, [1, 1, kernel_size, 1]) |
| 100 | blur_h = torch.reshape(blur_filter, [1, 1, 1, kernel_size]) |
| 101 | |
| 102 | num_channels, _, _ = image.size(1), image.size(2), image.size(3) |
| 103 | blur_h = blur_h.repeat(num_channels, 1, 1, 1) |
| 104 | blur_v = blur_v.repeat(num_channels, 1, 1, 1) |
| 105 | pad_length = int((kernel_size - 1) / 2) |
| 106 | blurred = F.conv2d( |
| 107 | image[index:index + 1], |
| 108 | blur_h, |
| 109 | stride=1, |
| 110 | padding=(0, pad_length), |
| 111 | groups=3) |
| 112 | blurred = F.conv2d( |
| 113 | blurred, blur_v, stride=1, padding=(pad_length, 0), groups=3) |
| 114 | if expand_batch_dim: |
| 115 | blurred = blurred.squeeze(0) |
| 116 | result[index] = blurred |
| 117 | else: |
| 118 | result[index] = image[index] |
| 119 | |
| 120 | return result |
| 121 | |
| 122 | |
| 123 | def gaussianBlur(image, kernel_size=22, apply_prob=0.5): |