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
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.

import random
from typing import Dict, List, Optional, Sequence

import cv2
import numpy as np
import torchvision.transforms as T
from sapiens.registry import TRANSFORMS

from .base_transform import BaseTransform, to_tensor


@TRANSFORMS.register_module()
class ImageResize(BaseTransform):
    def __init__(
        self,
        image_height: int,
        image_width: int,
    ):
        self.image_height = image_height
        self.image_width = image_width

    def transform(self, results: Dict) -> Optional[Dict]:
        image = results["image"]
        image = cv2.resize(
            image, (self.image_width, self.image_height), interpolation=cv2.INTER_AREA
        )
        results["image"] = image

        return results


@TRANSFORMS.register_module()
class ImagePackInputs(BaseTransform):
    def __init__(self, meta_keys: List[str]):
        self.meta_keys = meta_keys
        self.to_tensor = T.ToTensor()

    def transform(self, results: Dict) -> Optional[Dict]:
        packed_results = dict()

        raw_image = results["image"]
        image = raw_image.copy()
        if len(image.shape) < 3:
            image = np.expand_dims(image, -1)
        if not image.flags.c_contiguous:
            image = to_tensor(np.ascontiguousarray(image.transpose(2, 0, 1)))
        else:
            image = image.transpose(2, 0, 1)
            image = to_tensor(image).contiguous()
        packed_results["inputs"] = image

        data_samples = dict()

        # Pack the specified meta keys
        for key in self.meta_keys:
            if key in results:
                data_samples[key] = results[key]

        data_samples["image"] = self.to_tensor(raw_image)
        packed_results["data_samples"] = data_samples

        return packed_results


@TRANSFORMS.register_module()
class PhotoMetricDistortion(BaseTransform):
    def __init__(
        self,
        brightness_delta: int = 32,
        contrast_range: Sequence[float] = (0.5, 1.5),
        saturation_range: Sequence[float] = (0.5, 1.5),
        hue_delta: int = 18,
    ):
        self.brightness_delta = brightness_delta
        self.contrast_lower, self.contrast_upper = contrast_range
        self.saturation_lower, self.saturation_upper = saturation_range
        self.hue_delta = hue_delta

    def convert(self, img: np.ndarray, alpha: int = 1, beta: int = 0) -> np.ndarray:
        img = img.astype(np.float32) * alpha + beta
        img = np.clip(img, 0, 255)
        return img.astype(np.uint8)

    def brightness(self, img: np.ndarray) -> np.ndarray:
        if random.randint(0, 1):
            return self.convert(
                img, beta=random.uniform(-self.brightness_delta, self.brightness_delta)
            )
        return img

    def contrast(self, img: np.ndarray) -> np.ndarray:
        if random.randint(0, 1):
            return self.convert(
                img, alpha=random.uniform(self.contrast_lower, self.contrast_upper)
            )
        return img

    def saturation(self, img: np.ndarray) -> np.ndarray:
        if random.randint(0, 1):
            img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
            img[:, :, 1] = self.convert(
                img[:, :, 1],
                alpha=random.uniform(self.saturation_lower, self.saturation_upper),
            )
            img = cv2.cvtColor(img, cv2.COLOR_HSV2BGR)
        return img

    def hue(self, img: np.ndarray) -> np.ndarray:
        if random.randint(0, 1):
            img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
            img[:, :, 0] = (
                img[:, :, 0].astype(int)
                + random.randint(-self.hue_delta, self.hue_delta)
            ) % 180
            img = cv2.cvtColor(img, cv2.COLOR_HSV2BGR)
        return img

    def transform(self, results: dict) -> dict:
        img = results["img"]
        # random brightness
        img = self.brightness(img)

        # mode == 0 --> do random contrast first
        # mode == 1 --> do random contrast last
        mode = random.randint(0, 1)
        if mode == 1:
            img = self.contrast(img)

        # random saturation
        img = self.saturation(img)

        # random hue
        img = self.hue(img)

        # random contrast
        if mode == 0:
            img = self.contrast(img)

        results["img"] = img
        return results

    def __repr__(self):
        repr_str = self.__class__.__name__
        repr_str += (
            f"(brightness_delta={self.brightness_delta}, "
            f"contrast_range=({self.contrast_lower}, "
            f"{self.contrast_upper}), "
            f"saturation_range=({self.saturation_lower}, "
            f"{self.saturation_upper}), "
            f"hue_delta={self.hue_delta})"
        )
        return repr_str


@TRANSFORMS.register_module()
class RandomPhotoMetricDistortion(PhotoMetricDistortion):
    def __init__(
        self,
        prob: float = 0.5,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.prob = prob

    def transform(self, results: Dict) -> Optional[Dict]:
        if np.random.rand() > self.prob:
            return results
        return super().transform(results)


@TRANSFORMS.register_module()
class RandomDownUpSampleImage(BaseTransform):
    _INTERP_LIST = [
        cv2.INTER_NEAREST,
        cv2.INTER_LINEAR,
        cv2.INTER_CUBIC,
        cv2.INTER_AREA,
        cv2.INTER_LANCZOS4,
    ]

    def __init__(self, scale_range=(0.1, 0.5), prob=0.4):
        super().__init__()
        self.scale_range = scale_range
        self.prob = prob

    def transform(self, results: dict) -> dict:
        if np.random.rand() > self.prob:
            return results  # Skip with probability (1 - prob)

        img = results["img"]
        orig_h, orig_w = img.shape[:2]

        # Pick a random factor in [min_scale, max_scale]
        min_scale, max_scale = self.scale_range
        scale_factor = np.random.uniform(min_scale, max_scale)

        # Randomly select interpolation modes for downsampling and upsampling
        down_interp = random.choice(self._INTERP_LIST)
        up_interp = random.choice(self._INTERP_LIST)

        # Compute downsample size
        down_w = max(1, int(orig_w * scale_factor))
        down_h = max(1, int(orig_h * scale_factor))

        # Downsample
        img_down = cv2.resize(img, (down_w, down_h), interpolation=down_interp)
        img_up = cv2.resize(img_down, (orig_w, orig_h), interpolation=up_interp)

        # Replace the original image with the heavily down-up-sampled version
        results["img"] = img_up
        return results

    def __repr__(self):
        return (
            f"{self.__class__.__name__}(scale_range={self.scale_range}, "
            f"prob={self.prob})"
        )


@TRANSFORMS.register_module()
class RandomGaussianBlur(BaseTransform):
    def __init__(self, prob=0.4, kernel_size=(3, 3), sigma_range=(0.1, 2.0)):
        super().__init__()
        self.prob = prob
        self.kernel_size = kernel_size
        self.sigma_range = sigma_range

    def transform(self, results: dict) -> dict:
        if np.random.rand() > self.prob:
            return results

        img = results["img"]
        if self.sigma_range is not None:
            sigma = np.random.uniform(self.sigma_range[0], self.sigma_range[1])
        else:
            sigma = 0  # OpenCV auto-calculates

        blurred = cv2.GaussianBlur(img, self.kernel_size, sigma)
        results["img"] = blurred
        return results

    def __repr__(self):
        return (
            f"{self.__class__.__name__}(prob={self.prob}, "
            f"kernel_size={self.kernel_size}, sigma_range={self.sigma_range})"
        )


@TRANSFORMS.register_module()
class RandomJPEGCompression(BaseTransform):
    def __init__(self, prob=0.4, quality_range=(30, 60)):
        super().__init__()
        self.prob = prob
        self.quality_range = quality_range

    def transform(self, results: dict) -> dict:
        if np.random.rand() > self.prob:
            return results

        img = results["img"]
        q_min, q_max = self.quality_range
        quality = np.random.randint(q_min, q_max + 1)

        encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
        success, enc_img = cv2.imencode(".jpg", img, encode_param)
        if success:
            dec_img = cv2.imdecode(enc_img, cv2.IMREAD_COLOR)
            results["img"] = dec_img
        return results

    def __repr__(self):
        return (
            f"{self.__class__.__name__}(prob={self.prob}, "
            f"quality_range={self.quality_range})"
        )


@TRANSFORMS.register_module()
class RandomGaussianNoise(BaseTransform):
    def __init__(self, prob=0.4, mean=0.0, var_range=(5.0, 20.0)):
        super().__init__()
        self.prob = prob
        self.mean = mean
        self.var_range = var_range

    def transform(self, results: dict) -> dict:
        if np.random.rand() > self.prob:
            return results

        img = results["img"].astype(np.float32)
        var = np.random.uniform(self.var_range[0], self.var_range[1])
        sigma = var**0.5

        noise = np.random.normal(self.mean, sigma, img.shape).astype(np.float32)
        noisy_img = img + noise
        noisy_img = np.clip(noisy_img, 0, 255).astype(np.uint8)

        results["img"] = noisy_img
        return results

    def __repr__(self):
        return (
            f"{self.__class__.__name__}(prob={self.prob}, "
            f"mean={self.mean}, var_range={self.var_range})"
        )


@TRANSFORMS.register_module()
class RandomGamma(BaseTransform):
    def __init__(self, prob=0.4, gamma_range=(0.7, 1.3)):
        super().__init__()
        self.prob = prob
        self.gamma_range = gamma_range

    def transform(self, results: dict) -> dict:
        if np.random.rand() > self.prob:
            return results

        img = results["img"]
        gamma = np.random.uniform(self.gamma_range[0], self.gamma_range[1])

        # Build a lookup table for [0..255]
        table = (
            np.array([(i / 255.0) ** gamma * 255 for i in range(256)])
            .clip(0, 255)
            .astype(np.uint8)
        )
        img_corrected = cv2.LUT(img, table)
        results["img"] = img_corrected
        return results

    def __repr__(self):
        return (
            f"{self.__class__.__name__}(prob={self.prob}, "
            f"gamma_range={self.gamma_range})"
        )


@TRANSFORMS.register_module()
class RandomGrayscale(BaseTransform):
    def __init__(self, prob=0.4):
        super().__init__()
        self.prob = prob

    def transform(self, results: dict) -> dict:
        if np.random.rand() > self.prob:
            return results

        img = results["img"]
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray_3ch = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
        results["img"] = gray_3ch
        return results

    def __repr__(self):
        return f"{self.__class__.__name__}(prob={self.prob})"


@TRANSFORMS.register_module()
class RandomChannelShuffle(BaseTransform):
    def __init__(self, prob=0.4):
        super().__init__()
        self.prob = prob

    def transform(self, results: dict) -> dict:
        if np.random.rand() > self.prob:
            return results

        img = results["img"]
        channels = [0, 1, 2]
        np.random.shuffle(channels)
        img = img[..., channels]
        results["img"] = img
        return results

    def __repr__(self):
        return f"{self.__class__.__name__}(prob={self.prob})"


@TRANSFORMS.register_module()
class RandomInvert(BaseTransform):
    def __init__(self, prob=0.4):
        super().__init__()
        self.prob = prob

    def transform(self, results: dict) -> dict:
        if np.random.rand() > self.prob:
            return results

        img = results["img"]
        results["img"] = 255 - img
        return results

    def __repr__(self):
        return f"{self.__class__.__name__}(prob={self.prob})"


@TRANSFORMS.register_module()
class RandomSolarize(BaseTransform):
    def __init__(self, prob=0.4, threshold=128):
        super().__init__()
        self.prob = prob
        self.threshold = threshold

    def transform(self, results: dict) -> dict:
        if np.random.rand() > self.prob:
            return results

        img = results["img"]
        mask = img > self.threshold
        img[mask] = 255 - img[mask]
        results["img"] = img
        return results

    def __repr__(self):
        return (
            f"{self.__class__.__name__}(prob={self.prob}, threshold={self.threshold})"
        )


@TRANSFORMS.register_module()
class RandomPosterize(BaseTransform):
    def __init__(self, prob=0.4, bits=(2, 5)):
        super().__init__()
        self.prob = prob
        self.bits = bits

    def transform(self, results: dict) -> dict:
        if np.random.rand() > self.prob:
            return results

        img = results["img"]
        # pick random bits
        bits_chosen = random.randint(self.bits[0], self.bits[1])
        shift = 8 - bits_chosen
        img = (img >> shift) << shift
        results["img"] = img
        return results

    def __repr__(self):
        return f"{self.__class__.__name__}(prob={self.prob}, bits={self.bits})"