| 1 | import numpy as np |
| 2 | import scipy |
| 3 | import scipy.ndimage |
| 4 | import scipy.interpolate |
| 5 | import scipy.stats |
| 6 | |
| 7 | from spatiallm.pcd.registry import Registry |
| 8 | |
| 9 | TRANSFORMS = Registry("transforms") |
| 10 | |
| 11 | """ |
| 12 | 3D Point Cloud Preprocessing |
| 13 | |
| 14 | Reference: PointCept |
| 15 | |
| 16 | @misc{pointcept2023, |
| 17 | title={Pointcept: A Codebase for Point Cloud Perception Research}, |
| 18 | author={Pointcept Contributors}, |
| 19 | year={2023} |
| 20 | } |
| 21 | """ |
| 22 | |
| 23 | |
| 24 | class Compose(object): |
| 25 | def __init__(self, cfg=None): |
| 26 | self.cfg = cfg if cfg is not None else [] |
| 27 | self.transforms = [] |
| 28 | for t_cfg in self.cfg: |
| 29 | self.transforms.append(TRANSFORMS.build(t_cfg)) |
| 30 | |
| 31 | def __call__(self, data_dict): |
| 32 | for t in self.transforms: |
| 33 | data_dict = t(data_dict) |
| 34 | return data_dict |
| 35 | |
| 36 | |
| 37 | @TRANSFORMS.register_module() |
| 38 | class PositiveShift(object): |
| 39 | def __call__(self, data_dict): |
| 40 | if "coord" in data_dict.keys(): |
| 41 | coord_min = np.min(data_dict["coord"], 0) |
| 42 | data_dict["coord"] -= coord_min |
| 43 | return data_dict |
| 44 | |
| 45 | |
| 46 | @TRANSFORMS.register_module() |
| 47 | class NormalizeColor(object): |
| 48 | def __call__(self, data_dict): |
| 49 | if "color" in data_dict.keys(): |
| 50 | data_dict["color"] = data_dict["color"] / 127.5 - 1 |
| 51 | return data_dict |
| 52 | |
| 53 | |
| 54 | @TRANSFORMS.register_module() |
| 55 | class RandomColorGrayScale(object): |
| 56 | def __init__(self, p): |
| 57 | self.p = p |
| 58 | |
| 59 | @staticmethod |
| 60 | def rgb_to_grayscale(color, num_output_channels=1): |
| 61 | if color.shape[-1] < 3: |
| 62 | raise TypeError( |
| 63 | "Input color should have at least 3 dimensions, but found {}".format( |
| 64 | color.shape[-1] |
| 65 | ) |
| 66 | ) |
| 67 | |
| 68 | if num_output_channels not in (1, 3): |
| 69 | raise ValueError("num_output_channels should be either 1 or 3") |
| 70 | |
| 71 | r, g, b = color[..., 0], color[..., 1], color[..., 2] |
| 72 | gray = (0.2989 * r + 0.587 * g + 0.114 * b).astype(color.dtype) |
| 73 | gray = np.expand_dims(gray, axis=-1) |
| 74 | |
| 75 | if num_output_channels == 3: |
| 76 | gray = np.broadcast_to(gray, color.shape) |
| 77 | |
| 78 | return gray |
| 79 | |
| 80 | def __call__(self, data_dict): |
| 81 | if np.random.rand() < self.p: |
| 82 | data_dict["color"] = self.rgb_to_grayscale(data_dict["color"], 3).copy() |
| 83 | return data_dict |
| 84 | |
| 85 | |
| 86 | @TRANSFORMS.register_module() |
| 87 | class ChromaticAutoContrast(object): |
| 88 | def __init__(self, p=0.2, blend_factor=None): |
| 89 | self.p = p |
| 90 | self.blend_factor = blend_factor |
| 91 | |
| 92 | def __call__(self, data_dict): |
| 93 | if "color" in data_dict.keys() and np.random.rand() < self.p: |
| 94 | lo = np.min(data_dict["color"], 0, keepdims=True) |
| 95 | hi = np.max(data_dict["color"], 0, keepdims=True) |
| 96 | scale = 255 / (hi - lo) |
| 97 | contrast_feat = (data_dict["color"][:, :3] - lo) * scale |
| 98 | blend_factor = ( |
| 99 | np.random.rand() if self.blend_factor is None else self.blend_factor |
| 100 | ) |
| 101 | data_dict["color"][:, :3] = (1 - blend_factor) * data_dict["color"][ |
| 102 | :, :3 |
| 103 | ] + blend_factor * contrast_feat |
| 104 | return data_dict |
| 105 | |
| 106 | |
| 107 | @TRANSFORMS.register_module() |
| 108 | class ChromaticTranslation(object): |
| 109 | def __init__(self, p=0.95, ratio=0.05): |
| 110 | self.p = p |
| 111 | self.ratio = ratio |
| 112 | |
| 113 | def __call__(self, data_dict): |
| 114 | if "color" in data_dict.keys() and np.random.rand() < self.p: |
| 115 | tr = (np.random.rand(1, 3) - 0.5) * 255 * 2 * self.ratio |
| 116 | data_dict["color"][:, :3] = np.clip(tr + data_dict["color"][:, :3], 0, 255) |
| 117 | return data_dict |
| 118 | |
| 119 | |
| 120 | @TRANSFORMS.register_module() |
| 121 | class ChromaticJitter(object): |
| 122 | def __init__(self, p=0.95, std=0.005): |
| 123 | self.p = p |
| 124 | self.std = std |
| 125 | |
| 126 | def __call__(self, data_dict): |
| 127 | if "color" in data_dict.keys() and np.random.rand() < self.p: |
| 128 | noise = np.random.randn(data_dict["color"].shape[0], 3) |
| 129 | noise *= self.std * 255 |
| 130 | data_dict["color"][:, :3] = np.clip( |
| 131 | noise + data_dict["color"][:, :3], 0, 255 |
| 132 | ) |
| 133 | return data_dict |
| 134 | |
| 135 | |
| 136 | @TRANSFORMS.register_module() |
| 137 | class HueSaturationTranslation(object): |
| 138 | @staticmethod |
| 139 | def rgb_to_hsv(rgb): |
| 140 | # Translated from source of colorsys.rgb_to_hsv |
| 141 | # r,g,b should be a numpy arrays with values between 0 and 255 |
| 142 | # rgb_to_hsv returns an array of floats between 0.0 and 1.0. |
| 143 | rgb = rgb.astype("float") |
| 144 | hsv = np.zeros_like(rgb) |
| 145 | # in case an RGBA array was passed, just copy the A channel |
| 146 | hsv[..., 3:] = rgb[..., 3:] |
| 147 | r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2] |
| 148 | maxc = np.max(rgb[..., :3], axis=-1) |
| 149 | minc = np.min(rgb[..., :3], axis=-1) |
| 150 | hsv[..., 2] = maxc |
| 151 | mask = maxc != minc |
| 152 | hsv[mask, 1] = (maxc - minc)[mask] / maxc[mask] |
| 153 | rc = np.zeros_like(r) |
| 154 | gc = np.zeros_like(g) |
| 155 | bc = np.zeros_like(b) |
| 156 | rc[mask] = (maxc - r)[mask] / (maxc - minc)[mask] |
| 157 | gc[mask] = (maxc - g)[mask] / (maxc - minc)[mask] |
| 158 | bc[mask] = (maxc - b)[mask] / (maxc - minc)[mask] |
| 159 | hsv[..., 0] = np.select( |
| 160 | [r == maxc, g == maxc], [bc - gc, 2.0 + rc - bc], default=4.0 + gc - rc |
| 161 | ) |
| 162 | hsv[..., 0] = (hsv[..., 0] / 6.0) % 1.0 |
| 163 | return hsv |
| 164 | |
| 165 | @staticmethod |
| 166 | def hsv_to_rgb(hsv): |
| 167 | # Translated from source of colorsys.hsv_to_rgb |
| 168 | # h,s should be a numpy arrays with values between 0.0 and 1.0 |
| 169 | # v should be a numpy array with values between 0.0 and 255.0 |
| 170 | # hsv_to_rgb returns an array of uints between 0 and 255. |
| 171 | rgb = np.empty_like(hsv) |
| 172 | rgb[..., 3:] = hsv[..., 3:] |
| 173 | h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2] |
| 174 | i = (h * 6.0).astype("uint8") |
| 175 | f = (h * 6.0) - i |
| 176 | p = v * (1.0 - s) |
| 177 | q = v * (1.0 - s * f) |
| 178 | t = v * (1.0 - s * (1.0 - f)) |
| 179 | i = i % 6 |
| 180 | conditions = [s == 0.0, i == 1, i == 2, i == 3, i == 4, i == 5] |
| 181 | rgb[..., 0] = np.select(conditions, [v, q, p, p, t, v], default=v) |
| 182 | rgb[..., 1] = np.select(conditions, [v, v, v, q, p, p], default=t) |
| 183 | rgb[..., 2] = np.select(conditions, [v, p, t, v, v, q], default=p) |
| 184 | return rgb.astype("uint8") |
| 185 | |
| 186 | def __init__(self, hue_max=0.5, saturation_max=0.2): |
| 187 | self.hue_max = hue_max |
| 188 | self.saturation_max = saturation_max |
| 189 | |
| 190 | def __call__(self, data_dict): |
| 191 | if "color" in data_dict.keys(): |
| 192 | # Assume color[:, :3] is rgb |
| 193 | hsv = HueSaturationTranslation.rgb_to_hsv(data_dict["color"][:, :3]) |
| 194 | hue_val = (np.random.rand() - 0.5) * 2 * self.hue_max |
| 195 | sat_ratio = 1 + (np.random.rand() - 0.5) * 2 * self.saturation_max |
| 196 | hsv[..., 0] = np.remainder(hue_val + hsv[..., 0] + 1, 1) |
| 197 | hsv[..., 1] = np.clip(sat_ratio * hsv[..., 1], 0, 1) |
| 198 | data_dict["color"][:, :3] = np.clip( |
| 199 | HueSaturationTranslation.hsv_to_rgb(hsv), 0, 255 |
| 200 | ) |
| 201 | return data_dict |
| 202 | |
| 203 | |
| 204 | @TRANSFORMS.register_module() |
| 205 | class RandomColorDrop(object): |
| 206 | def __init__(self, p=0.2, color_augment=0.0): |
| 207 | self.p = p |
| 208 | self.color_augment = color_augment |
| 209 | |
| 210 | def __call__(self, data_dict): |
| 211 | if "color" in data_dict.keys() and np.random.rand() < self.p: |
| 212 | data_dict["color"] = data_dict["color"].astype(np.float64) |
| 213 | data_dict["color"] *= self.color_augment |
| 214 | return data_dict |
| 215 | |
| 216 | def __repr__(self): |
| 217 | return "RandomColorDrop(color_augment: {}, p: {})".format( |
| 218 | self.color_augment, self.p |
| 219 | ) |
| 220 | |
| 221 | |
| 222 | @TRANSFORMS.register_module() |
| 223 | class RandomJitter(object): |
| 224 | def __init__(self, sigma=0.01, clip=0.05, ratio=0.5, p=0.5): |
| 225 | assert clip > 0 |
| 226 | self.sigma = sigma |
| 227 | self.clip = clip |
| 228 | self.ratio = ratio |
| 229 | self.p = p |
| 230 | |
| 231 | def __call__(self, data_dict): |
| 232 | if "coord" in data_dict.keys() and np.random.rand() < self.p: |
| 233 | jitter = np.clip( |
| 234 | self.sigma * np.random.randn(data_dict["coord"].shape[0], 3), |
| 235 | -self.clip, |
| 236 | self.clip, |
| 237 | ) |
| 238 | idx = np.random.rand(data_dict["coord"].shape[0]) < self.ratio |
| 239 | data_dict["coord"][idx] += jitter[idx] |
| 240 | return data_dict |
| 241 | |
| 242 | |
| 243 | @TRANSFORMS.register_module() |
| 244 | class ElasticDistortion(object): |
| 245 | def __init__(self, distortion_params=None, p=[0.8, 0.5]): |
| 246 | self.distortion_params = ( |
| 247 | [[0.2, 0.4], [0.8, 1.6]] if distortion_params is None else distortion_params |
| 248 | ) |
| 249 | self.p = p |
| 250 | |
| 251 | @staticmethod |
| 252 | def elastic_distortion(coords, granularity, magnitude): |
| 253 | """ |
| 254 | Apply elastic distortion on sparse coordinate space. |
| 255 | pointcloud: numpy array of (number of points, at least 3 spatial dims) |
| 256 | granularity: size of the noise grid (in same scale[m/cm] as the voxel grid) |
| 257 | magnitude: noise multiplier |
| 258 | """ |
| 259 | blurx = np.ones((3, 1, 1, 1)).astype("float32") / 3 |
| 260 | blury = np.ones((1, 3, 1, 1)).astype("float32") / 3 |
| 261 | blurz = np.ones((1, 1, 3, 1)).astype("float32") / 3 |
| 262 | coords_min = coords.min(0) |
| 263 | |
| 264 | # Create Gaussian noise tensor of the size given by granularity. |
| 265 | noise_dim = ((coords - coords_min).max(0) // granularity).astype(int) + 3 |
| 266 | noise = np.random.randn(*noise_dim, 3).astype(np.float32) |
| 267 | |
| 268 | # Smoothing. |
| 269 | for _ in range(2): |
| 270 | noise = scipy.ndimage.convolve(noise, blurx, mode="constant", cval=0) |
| 271 | noise = scipy.ndimage.convolve(noise, blury, mode="constant", cval=0) |
| 272 | noise = scipy.ndimage.convolve(noise, blurz, mode="constant", cval=0) |
| 273 | |
| 274 | # Trilinear interpolate noise filters for each spatial dimensions. |
| 275 | ax = [ |
| 276 | np.linspace(d_min, d_max, d) |
| 277 | for d_min, d_max, d in zip( |
| 278 | coords_min - granularity, |
| 279 | coords_min + granularity * (noise_dim - 2), |
| 280 | noise_dim, |
| 281 | ) |
| 282 | ] |
| 283 | interp = scipy.interpolate.RegularGridInterpolator( |
| 284 | ax, noise, bounds_error=False, fill_value=0 |
| 285 | ) |
| 286 | coords += interp(coords) * magnitude |
| 287 | return coords |
| 288 | |
| 289 | def __call__(self, data_dict): |
| 290 | if "coord" in data_dict.keys() and self.distortion_params is not None: |
| 291 | count = 0 |
| 292 | for granularity, magnitude in self.distortion_params: |
| 293 | if np.random.rand() > self.p[count]: |
| 294 | continue |
| 295 | data_dict["coord"] = self.elastic_distortion( |
| 296 | data_dict["coord"], granularity, magnitude |
| 297 | ) |
| 298 | if "normal" in data_dict.keys(): |
| 299 | data_dict["normal"] = self.elastic_distortion( |
| 300 | data_dict["normal"], granularity, magnitude |
| 301 | ) |
| 302 | count += 1 |
| 303 | return data_dict |
| 304 | |
| 305 | |
| 306 | @TRANSFORMS.register_module() |
| 307 | class GridSample(object): |
| 308 | def __init__( |
| 309 | self, |
| 310 | grid_size=0.05, |
| 311 | hash_type="fnv", |
| 312 | mode="train", |
| 313 | keys=("coord", "color", "normal", "segment"), |
| 314 | return_inverse=False, |
| 315 | return_grid_coord=False, |
| 316 | return_min_coord=False, |
| 317 | return_displacement=False, |
| 318 | project_displacement=False, |
| 319 | max_grid_coord=None, |
| 320 | ): |
| 321 | self.grid_size = grid_size |
| 322 | self.hash = self.fnv_hash_vec if hash_type == "fnv" else self.ravel_hash_vec |
| 323 | assert mode in ["train", "test"] |
| 324 | self.mode = mode |
| 325 | self.keys = keys |
| 326 | self.return_inverse = return_inverse |
| 327 | self.return_grid_coord = return_grid_coord |
| 328 | self.return_min_coord = return_min_coord |
| 329 | self.return_displacement = return_displacement |
| 330 | self.project_displacement = project_displacement |
| 331 | self.max_grid_coord = max_grid_coord |
| 332 | |
| 333 | def __call__(self, data_dict): |
| 334 | assert "coord" in data_dict.keys() |
| 335 | scaled_coord = data_dict["coord"] / np.array(self.grid_size) |
| 336 | grid_coord = np.floor(scaled_coord).astype(int) |
| 337 | min_coord = grid_coord.min(0) |
| 338 | grid_coord -= min_coord |
| 339 | scaled_coord -= min_coord |
| 340 | min_coord = min_coord * np.array(self.grid_size) |
| 341 | if self.max_grid_coord is not None: |
| 342 | grid_coord = np.clip(grid_coord, 0, self.max_grid_coord - 1) |
| 343 | key = self.hash(grid_coord) |
| 344 | idx_sort = np.argsort(key) |
| 345 | key_sort = key[idx_sort] |
| 346 | _, inverse, count = np.unique(key_sort, return_inverse=True, return_counts=True) |
| 347 | if self.mode == "train": # train mode |
| 348 | idx_select = ( |
| 349 | np.cumsum(np.insert(count, 0, 0)[0:-1]) |
| 350 | + np.random.randint(0, count.max(), count.size) % count |
| 351 | ) |
| 352 | idx_unique = idx_sort[idx_select] |
| 353 | if "sampled_index" in data_dict: |
| 354 | # for ScanNet data efficient, we need to make sure labeled point is sampled. |
| 355 | idx_unique = np.unique( |
| 356 | np.append(idx_unique, data_dict["sampled_index"]) |
| 357 | ) |
| 358 | mask = np.zeros_like(data_dict["segment"]).astype(bool) |
| 359 | mask[data_dict["sampled_index"]] = True |
| 360 | data_dict["sampled_index"] = np.where(mask[idx_unique])[0] |
| 361 | if self.return_inverse: |
| 362 | data_dict["inverse"] = np.zeros_like(inverse) |
| 363 | data_dict["inverse"][idx_sort] = inverse |
| 364 | if self.return_grid_coord: |
| 365 | data_dict["grid_coord"] = grid_coord[idx_unique] |
| 366 | if self.return_min_coord: |
| 367 | data_dict["min_coord"] = min_coord.reshape([1, 3]) |
| 368 | if self.return_displacement: |
| 369 | displacement = ( |
| 370 | scaled_coord - grid_coord - 0.5 |
| 371 | ) # [0, 1] -> [-0.5, 0.5] displacement to center |
| 372 | if self.project_displacement: |
| 373 | displacement = np.sum( |
| 374 | displacement * data_dict["normal"], axis=-1, keepdims=True |
| 375 | ) |
| 376 | data_dict["displacement"] = displacement[idx_unique] |
| 377 | for key in self.keys: |
| 378 | data_dict[key] = data_dict[key][idx_unique] |
| 379 | return data_dict |
| 380 | |
| 381 | elif self.mode == "test": # test mode |
| 382 | idx_select = ( |
| 383 | np.cumsum(np.insert(count, 0, 0)[0:-1]) + (count.max() // 2) % count |
| 384 | ) |
| 385 | idx_part = idx_sort[idx_select] |
| 386 | data_part = dict(index=idx_part) |
| 387 | if self.return_inverse: |
| 388 | data_dict["inverse"] = np.zeros_like(inverse) |
| 389 | data_dict["inverse"][idx_sort] = inverse |
| 390 | if self.return_grid_coord: |
| 391 | data_part["grid_coord"] = grid_coord[idx_part] |
| 392 | if self.return_min_coord: |
| 393 | data_part["min_coord"] = min_coord.reshape([1, 3]) |
| 394 | for key in data_dict.keys(): |
| 395 | if key in self.keys: |
| 396 | data_part[key] = data_dict[key][idx_part] |
| 397 | else: |
| 398 | data_part[key] = data_dict[key] |
| 399 | return data_part |
| 400 | else: |
| 401 | raise NotImplementedError |
| 402 | |
| 403 | @staticmethod |
| 404 | def ravel_hash_vec(arr): |
| 405 | """ |
| 406 | Ravel the coordinates after subtracting the min coordinates. |
| 407 | """ |
| 408 | assert arr.ndim == 2 |
| 409 | arr = arr.copy() |
| 410 | arr -= arr.min(0) |
| 411 | arr = arr.astype(np.uint64, copy=False) |
| 412 | arr_max = arr.max(0).astype(np.uint64) + 1 |
| 413 | |
| 414 | keys = np.zeros(arr.shape[0], dtype=np.uint64) |
| 415 | # Fortran style indexing |
| 416 | for j in range(arr.shape[1] - 1): |
| 417 | keys += arr[:, j] |
| 418 | keys *= arr_max[j + 1] |
| 419 | keys += arr[:, -1] |
| 420 | return keys |
| 421 | |
| 422 | @staticmethod |
| 423 | def fnv_hash_vec(arr): |
| 424 | """ |
| 425 | FNV64-1A |
| 426 | """ |
| 427 | assert arr.ndim == 2 |
| 428 | # Floor first for negative coordinates |
| 429 | arr = arr.copy() |
| 430 | arr = arr.astype(np.uint64, copy=False) |
| 431 | hashed_arr = np.uint64(14695981039346656037) * np.ones( |
| 432 | arr.shape[0], dtype=np.uint64 |
| 433 | ) |
| 434 | for j in range(arr.shape[1]): |
| 435 | hashed_arr *= np.uint64(1099511628211) |
| 436 | hashed_arr = np.bitwise_xor(hashed_arr, arr[:, j]) |
| 437 | return hashed_arr |