Daankular commited on
Commit
e7dbf22
·
verified ·
1 Parent(s): 7d6d7f7

Upload patches/TripoSG_image_process.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. patches/TripoSG_image_process.py +165 -0
patches/TripoSG_image_process.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Patched: resize BEFORE squeeze to fix "ValueError: spatial dimensions of [1024]"
3
+ # Original bug: alpha_gpu_rmbg was squeezed to [H,W] before resize_transform([H,W])
4
+ # which expects [C,H,W] input. Fix: resize first, then squeeze(0).
5
+ import os
6
+ from skimage.morphology import remove_small_objects
7
+ from skimage.measure import label
8
+ import numpy as np
9
+ from PIL import Image
10
+ import cv2
11
+ from torchvision import transforms
12
+ import torch
13
+ import torch.nn.functional as F
14
+ import torchvision.transforms.functional as TF
15
+
16
+ def find_bounding_box(gray_image):
17
+ _, binary_image = cv2.threshold(gray_image, 1, 255, cv2.THRESH_BINARY)
18
+ contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
19
+ max_contour = max(contours, key=cv2.contourArea)
20
+ x, y, w, h = cv2.boundingRect(max_contour)
21
+ return x, y, w, h
22
+
23
+ def load_image(img_path, bg_color=None, rmbg_net=None, padding_ratio=0.1):
24
+ img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)
25
+ if img is None:
26
+ return f"invalid image path {img_path}"
27
+
28
+ def is_valid_alpha(alpha, min_ratio = 0.01):
29
+ bins = 20
30
+ if isinstance(alpha, np.ndarray):
31
+ hist = cv2.calcHist([alpha], [0], None, [bins], [0, 256])
32
+ else:
33
+ hist = torch.histc(alpha, bins=bins, min=0, max=1)
34
+ min_hist_val = alpha.shape[0] * alpha.shape[1] * min_ratio
35
+ return hist[0] >= min_hist_val and hist[-1] >= min_hist_val
36
+
37
+ def rmbg(image: torch.Tensor) -> torch.Tensor:
38
+ model_class = type(rmbg_net).__name__
39
+ if 'BriaRMBG' in model_class:
40
+ # RMBG-1.4: normalize to [-0.5, 0.5] range, take finest prediction d1
41
+ img_v1 = TF.normalize(image, [0.5, 0.5, 0.5], [1.0, 1.0, 1.0]).unsqueeze(0)
42
+ result = rmbg_net(img_v1)
43
+ # BriaRMBG returns (d1, d2, ..., d7); d1 is finest
44
+ d1 = result[0] if isinstance(result, (list, tuple)) else result
45
+ return d1[0] # [B,1,H,W] -> [1,H,W]
46
+ else:
47
+ # RMBG-2.0 (BiRefNet): ImageNet normalization, last item is finest
48
+ img_v2 = TF.normalize(image, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]).unsqueeze(0)
49
+ result = rmbg_net(img_v2)
50
+ last = result[-1] if isinstance(result, (list, tuple)) else result
51
+ return last[0] # [B,1,H,W] -> [1,H,W]
52
+
53
+ if len(img.shape) == 2:
54
+ num_channels = 1
55
+ else:
56
+ num_channels = img.shape[2]
57
+
58
+ # check if too large
59
+ height, width = img.shape[:2]
60
+ if height > width:
61
+ scale = 2000 / height
62
+ else:
63
+ scale = 2000 / width
64
+ if scale < 1:
65
+ new_size = (int(width * scale), int(height * scale))
66
+ img = cv2.resize(img, new_size, interpolation=cv2.INTER_AREA)
67
+
68
+ if img.dtype != 'uint8':
69
+ img = (img * (255. / np.iinfo(img.dtype).max)).astype(np.uint8)
70
+
71
+ rgb_image = None
72
+ alpha = None
73
+
74
+ if num_channels == 1:
75
+ rgb_image = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
76
+ elif num_channels == 3:
77
+ rgb_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
78
+ elif num_channels == 4:
79
+ rgb_image = cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
80
+
81
+ b, g, r, alpha = cv2.split(img)
82
+ if not is_valid_alpha(alpha):
83
+ alpha = None
84
+ else:
85
+ alpha_gpu = torch.from_numpy(alpha).unsqueeze(0).cuda().float() / 255.
86
+ else:
87
+ return f"invalid image: channels {num_channels}"
88
+
89
+ rgb_image_gpu = torch.from_numpy(rgb_image).cuda().float().permute(2, 0, 1) / 255.
90
+ if alpha is None:
91
+ resize_transform = transforms.Resize((384, 384), antialias=True)
92
+ rgb_image_resized = resize_transform(rgb_image_gpu)
93
+ normalize_image = rgb_image_resized * 2 - 1
94
+
95
+ mean_color = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1).cuda()
96
+ resize_transform = transforms.Resize((1024, 1024), antialias=True)
97
+ rgb_image_resized = resize_transform(rgb_image_gpu)
98
+ max_value = rgb_image_resized.flatten().max()
99
+ if max_value < 1e-3:
100
+ return "invalid image: pure black image"
101
+ normalize_image = rgb_image_resized / max_value - mean_color
102
+ normalize_image = normalize_image.unsqueeze(0)
103
+ resize_transform = transforms.Resize((rgb_image_gpu.shape[1], rgb_image_gpu.shape[2]), antialias=True)
104
+
105
+ # seg from rmbg
106
+ alpha_gpu_rmbg = rmbg(rgb_image_resized)
107
+ # FIX: resize FIRST (needs [C,H,W]), THEN squeeze to [H,W]
108
+ alpha_gpu_rmbg = resize_transform(alpha_gpu_rmbg)
109
+ alpha_gpu_rmbg = alpha_gpu_rmbg.squeeze(0)
110
+ mi = alpha_gpu_rmbg.min()
111
+ ma = alpha_gpu_rmbg.max()
112
+ alpha_gpu_rmbg = (alpha_gpu_rmbg - mi) / (ma - mi)
113
+
114
+ alpha_gpu = alpha_gpu_rmbg
115
+
116
+ alpha_gpu_tmp = alpha_gpu * 255
117
+ alpha = alpha_gpu_tmp.to(torch.uint8).squeeze().cpu().numpy()
118
+
119
+ _, alpha = cv2.threshold(alpha, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
120
+ labeled_alpha = label(alpha)
121
+ cleaned_alpha = remove_small_objects(labeled_alpha, min_size=200)
122
+ cleaned_alpha = (cleaned_alpha > 0).astype(np.uint8)
123
+ alpha = cleaned_alpha * 255
124
+ alpha_gpu = torch.from_numpy(cleaned_alpha).cuda().float().unsqueeze(0)
125
+ x, y, w, h = find_bounding_box(alpha)
126
+
127
+ # If alpha is provided, the bounds of all foreground are used
128
+ else:
129
+ rows, cols = np.where(alpha > 0)
130
+ if rows.size > 0 and cols.size > 0:
131
+ x_min = np.min(cols)
132
+ y_min = np.min(rows)
133
+ x_max = np.max(cols)
134
+ y_max = np.max(rows)
135
+
136
+ width = x_max - x_min + 1
137
+ height = y_max - y_min + 1
138
+ x, y, w, h = x_min, y_min, width, height
139
+
140
+ if np.all(alpha==0):
141
+ raise ValueError(f"input image too small")
142
+
143
+ bg_gray = bg_color[0]
144
+ bg_color = torch.from_numpy(bg_color).float().cuda().repeat(alpha_gpu.shape[1], alpha_gpu.shape[2], 1).permute(2, 0, 1)
145
+ rgb_image_gpu = rgb_image_gpu * alpha_gpu + bg_color * (1 - alpha_gpu)
146
+ padding_size = [0] * 6
147
+ if w > h:
148
+ padding_size[0] = int(w * padding_ratio)
149
+ padding_size[2] = int(padding_size[0] + (w - h) / 2)
150
+ else:
151
+ padding_size[2] = int(h * padding_ratio)
152
+ padding_size[0] = int(padding_size[2] + (h - w) / 2)
153
+ padding_size[1] = padding_size[0]
154
+ padding_size[3] = padding_size[2]
155
+ padded_tensor = F.pad(rgb_image_gpu[:, y:(y+h), x:(x+w)], pad=tuple(padding_size), mode='constant', value=bg_gray)
156
+
157
+ return padded_tensor
158
+
159
+ def prepare_image(image_path, bg_color, rmbg_net=None):
160
+ if os.path.isfile(image_path):
161
+ img_tensor = load_image(image_path, bg_color=bg_color, rmbg_net=rmbg_net)
162
+ img_np = img_tensor.permute(1,2,0).cpu().numpy()
163
+ img_pil = Image.fromarray((img_np*255).astype(np.uint8))
164
+
165
+ return img_pil