Mr7Explorer commited on
Commit
67390a4
·
verified ·
1 Parent(s): 4127e60

Upload image_proc.py

Browse files
Files changed (1) hide show
  1. image_proc.py +182 -0
image_proc.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ from PIL import Image, ImageEnhance
3
+ import numpy as np
4
+ import cv2
5
+ import torch
6
+ from torchvision import transforms
7
+
8
+
9
+ ## CPU version refinement
10
+ def FB_blur_fusion_foreground_estimator_cpu(image, FG, B, alpha, r=90):
11
+ if isinstance(image, Image.Image):
12
+ image = np.array(image) / 255.0
13
+ blurred_alpha = cv2.blur(alpha, (r, r))[:, :, None]
14
+
15
+ blurred_FGA = cv2.blur(FG * alpha, (r, r))
16
+ blurred_FG = blurred_FGA / (blurred_alpha + 1e-5)
17
+
18
+ blurred_B1A = cv2.blur(B * (1 - alpha), (r, r))
19
+ blurred_B = blurred_B1A / ((1 - blurred_alpha) + 1e-5)
20
+ FG = blurred_FG + alpha * (image - alpha * blurred_FG - (1 - alpha) * blurred_B)
21
+ FG = np.clip(FG, 0, 1)
22
+ return FG, blurred_B
23
+
24
+
25
+ def FB_blur_fusion_foreground_estimator_cpu_2(image, alpha, r=90):
26
+ # Thanks to the source: https://github.com/Photoroom/fast-foreground-estimation
27
+ alpha = alpha[:, :, None]
28
+ FG, blur_B = FB_blur_fusion_foreground_estimator_cpu(image, image, image, alpha, r)
29
+ return FB_blur_fusion_foreground_estimator_cpu(image, FG, blur_B, alpha, r=6)[0]
30
+
31
+
32
+ ## GPU version refinement
33
+ def mean_blur(x, kernel_size):
34
+ """
35
+ equivalent to cv.blur
36
+ x: [B, C, H, W]
37
+ """
38
+ if kernel_size % 2 == 0:
39
+ pad_l = kernel_size // 2 - 1
40
+ pad_r = kernel_size // 2
41
+ pad_t = kernel_size // 2 - 1
42
+ pad_b = kernel_size // 2
43
+ else:
44
+ pad_l = pad_r = pad_t = pad_b = kernel_size // 2
45
+
46
+ x_padded = torch.nn.functional.pad(x, (pad_l, pad_r, pad_t, pad_b), mode='replicate')
47
+
48
+ return torch.nn.functional.avg_pool2d(x_padded, kernel_size=(kernel_size, kernel_size), stride=1, count_include_pad=False)
49
+
50
+ def FB_blur_fusion_foreground_estimator_gpu(image, FG, B, alpha, r=90):
51
+ as_dtype = lambda x, dtype: x.to(dtype) if x.dtype != dtype else x
52
+
53
+ input_dtype = image.dtype
54
+ # convert image to float to avoid overflow
55
+ image = as_dtype(image, torch.float32)
56
+ FG = as_dtype(FG, torch.float32)
57
+ B = as_dtype(B, torch.float32)
58
+ alpha = as_dtype(alpha, torch.float32)
59
+
60
+ blurred_alpha = mean_blur(alpha, kernel_size=r)
61
+
62
+ blurred_FGA = mean_blur(FG * alpha, kernel_size=r)
63
+ blurred_FG = blurred_FGA / (blurred_alpha + 1e-5)
64
+
65
+ blurred_B1A = mean_blur(B * (1 - alpha), kernel_size=r)
66
+ blurred_B = blurred_B1A / ((1 - blurred_alpha) + 1e-5)
67
+
68
+ FG_output = blurred_FG + alpha * (image - alpha * blurred_FG - (1 - alpha) * blurred_B)
69
+ FG_output = torch.clamp(FG_output, 0, 1)
70
+
71
+ return as_dtype(FG_output, input_dtype), as_dtype(blurred_B, input_dtype)
72
+
73
+
74
+ def FB_blur_fusion_foreground_estimator_gpu_2(image, alpha, r=90):
75
+ # Thanks to the source: https://github.com/ZhengPeng7/BiRefNet/issues/226#issuecomment-3016433728
76
+ FG, blur_B = FB_blur_fusion_foreground_estimator_gpu(image, image, image, alpha, r)
77
+ return FB_blur_fusion_foreground_estimator_gpu(image, FG, blur_B, alpha, r=6)[0]
78
+
79
+
80
+ def refine_foreground(image, mask, r=90, device='cuda'):
81
+ """both image and mask are in range of [0, 1]"""
82
+ if mask.size != image.size:
83
+ mask = mask.resize(image.size)
84
+
85
+ if device == 'cuda':
86
+ image = transforms.functional.to_tensor(image).float().cuda()
87
+ mask = transforms.functional.to_tensor(mask).float().cuda()
88
+ image = image.unsqueeze(0)
89
+ mask = mask.unsqueeze(0)
90
+
91
+ estimated_foreground = FB_blur_fusion_foreground_estimator_gpu_2(image, mask, r=r)
92
+
93
+ estimated_foreground = estimated_foreground.squeeze()
94
+ estimated_foreground = (estimated_foreground.mul(255.0)).to(torch.uint8)
95
+ estimated_foreground = estimated_foreground.permute(1, 2, 0).contiguous().cpu().numpy().astype(np.uint8)
96
+ else:
97
+ image = np.array(image, dtype=np.float32) / 255.0
98
+ mask = np.array(mask, dtype=np.float32) / 255.0
99
+ estimated_foreground = FB_blur_fusion_foreground_estimator_cpu_2(image, mask, r=r)
100
+ estimated_foreground = (estimated_foreground * 255.0).astype(np.uint8)
101
+
102
+ estimated_foreground = Image.fromarray(np.ascontiguousarray(estimated_foreground))
103
+
104
+ return estimated_foreground
105
+
106
+
107
+ def preproc(image, label, preproc_methods=['flip']):
108
+ if 'flip' in preproc_methods:
109
+ image, label = cv_random_flip(image, label)
110
+ if 'crop' in preproc_methods:
111
+ image, label = random_crop(image, label)
112
+ if 'rotate' in preproc_methods:
113
+ image, label = random_rotate(image, label)
114
+ if 'enhance' in preproc_methods:
115
+ image = color_enhance(image)
116
+ if 'pepper' in preproc_methods:
117
+ image = random_pepper(image)
118
+ return image, label
119
+
120
+
121
+ def cv_random_flip(img, label):
122
+ if random.random() > 0.5:
123
+ img = img.transpose(Image.FLIP_LEFT_RIGHT)
124
+ label = label.transpose(Image.FLIP_LEFT_RIGHT)
125
+ return img, label
126
+
127
+
128
+ def random_crop(image, label):
129
+ border = 30
130
+ image_width = image.size[0]
131
+ image_height = image.size[1]
132
+ border = int(min(image_width, image_height) * 0.1)
133
+ crop_win_width = np.random.randint(image_width - border, image_width)
134
+ crop_win_height = np.random.randint(image_height - border, image_height)
135
+ random_region = (
136
+ (image_width - crop_win_width) >> 1, (image_height - crop_win_height) >> 1, (image_width + crop_win_width) >> 1,
137
+ (image_height + crop_win_height) >> 1)
138
+ return image.crop(random_region), label.crop(random_region)
139
+
140
+
141
+ def random_rotate(image, label, angle=15):
142
+ mode = Image.BICUBIC
143
+ if random.random() > 0.8:
144
+ random_angle = np.random.randint(-angle, angle)
145
+ image = image.rotate(random_angle, mode)
146
+ label = label.rotate(random_angle, mode)
147
+ return image, label
148
+
149
+
150
+ def color_enhance(image):
151
+ bright_intensity = random.randint(5, 15) / 10.0
152
+ image = ImageEnhance.Brightness(image).enhance(bright_intensity)
153
+ contrast_intensity = random.randint(5, 15) / 10.0
154
+ image = ImageEnhance.Contrast(image).enhance(contrast_intensity)
155
+ color_intensity = random.randint(0, 20) / 10.0
156
+ image = ImageEnhance.Color(image).enhance(color_intensity)
157
+ sharp_intensity = random.randint(0, 30) / 10.0
158
+ image = ImageEnhance.Sharpness(image).enhance(sharp_intensity)
159
+ return image
160
+
161
+
162
+ def random_gaussian(image, mean=0.1, sigma=0.35):
163
+ def gaussianNoisy(im, mean=mean, sigma=sigma):
164
+ for _i in range(len(im)):
165
+ im[_i] += random.gauss(mean, sigma)
166
+ return im
167
+
168
+ img = np.asarray(image)
169
+ width, height = img.shape
170
+ img = gaussianNoisy(img[:].flatten(), mean, sigma)
171
+ img = img.reshape([width, height])
172
+ return Image.fromarray(np.uint8(img))
173
+
174
+
175
+ def random_pepper(img, N=0.0015):
176
+ img = np.array(img)
177
+ noiseNum = int(N * img.shape[0] * img.shape[1])
178
+ for i in range(noiseNum):
179
+ randX = random.randint(0, img.shape[0] - 1)
180
+ randY = random.randint(0, img.shape[1] - 1)
181
+ img[randX, randY] = random.randint(0, 1) * 255
182
+ return Image.fromarray(img)