File size: 7,979 Bytes
205a7af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
import os

os.environ["OPENCV_IO_ENABLE_OPENEXR"] = "1"
import argparse

import cv2
import matplotlib.pyplot as plt
import numpy as np
import torch
from matplotlib import colors
from tqdm import tqdm

# flake8: noqa
# mypy: ignore-errors


class tonemap:
    def __init__(self):
        pass

    def process(self, img):
        return img

    def inv_process(self, img):
        return img


# Log correction
class log_tonemap(tonemap):
    # Constructor
    # Base of log
    # Scale of tonemapped
    # Offset
    def __init__(self, base, scale=1, offset=1):
        self.base = base
        self.scale = scale
        self.offset = offset

    def process(self, img):
        tonemapped = (np.log(img + self.offset) / np.log(self.base)) * self.scale
        return tonemapped

    def inv_process(self, img):
        inverse_tonemapped = np.power(self.base, (img) / self.scale) - self.offset
        return inverse_tonemapped


class log_tonemap_clip(tonemap):
    # Constructor
    # Base of log
    # Scale of tonemapped
    # Offset
    def __init__(self, base, scale=1, offset=1):
        self.base = base
        self.scale = scale
        self.offset = offset

    def process(self, img):
        tonemapped = np.clip((np.log(img * self.scale + self.offset) / np.log(self.base)), 0, 2) - 1
        return tonemapped

    def inv_process(self, img):
        inverse_tonemapped = (np.power(self.base, (img + 1)) - self.offset) / self.scale
        return inverse_tonemapped


# Gamma Tonemap
class gamma_tonemap(tonemap):
    def __init__(
        self,
        gamma,
    ):
        self.gamma = gamma

    def process(self, img):
        tonemapped = np.power(img, 1 / self.gamma)
        return tonemapped

    def inv_process(self, img):
        inverse_tonemapped = np.power(img, self.gamma)
        return inverse_tonemapped


class linear_clip(tonemap):
    def __init__(self, scale, mean):
        self.scale = scale
        self.mean = mean

    def process(self, img):
        tonemapped = np.clip((img - self.mean) / self.scale, -1, 1)
        return tonemapped

    def inv_process(self, img):
        inverse_tonemapped = img * self.scale + self.mean
        return inverse_tonemapped


def make_tonemap_HDR(opt):
    if opt.mode == "luminance":
        res_tonemap = log_tonemap_clip(10, 1.0, 1.0)
    else:  # temperature
        res_tonemap = linear_clip(5000.0, 5000.0)
    return res_tonemap


class LDRfromHDR:
    def __init__(
        self, tonemap="none", orig_scale=False, clip=True, quantization=0, color_jitter=0, noise=0
    ):
        self.tonemap_str, val = tonemap
        if tonemap[0] == "gamma":
            self.tonemap = gamma_tonemap(val)
        elif tonemap[0] == "log10":
            self.tonemap = log_tonemap(val)
        else:
            print("Warning: No tonemap specified, using linear")

        self.clip = clip
        self.orig_scale = orig_scale
        self.bits = quantization
        self.jitter = color_jitter
        self.noise = noise

        self.wbModel = None

    def process(self, HDR):
        LDR, normalized_scale = self.rescale(HDR)
        LDR = self.apply_clip(LDR)
        LDR = self.apply_scale(LDR, normalized_scale)
        LDR = self.apply_tonemap(LDR)
        LDR = self.colorJitter(LDR)
        LDR = self.gaussianNoise(LDR)
        LDR = self.quantize(LDR)
        LDR = self.apply_white_balance(LDR)
        return LDR, normalized_scale

    def rescale(self, img, percentile=90, max_mapping=0.8):
        r_percentile = np.percentile(img, percentile)
        alpha = max_mapping / (r_percentile + 1e-10)

        img_reexposed = img * alpha

        normalized_scale = normalizeScale(1 / alpha)

        return img_reexposed, normalized_scale

    def rescaleAlpha(self, img, percentile=90, max_mapping=0.8):
        r_percentile = np.percentile(img, percentile)
        alpha = max_mapping / (r_percentile + 1e-10)

        return alpha

    def apply_clip(self, img):
        if self.clip:
            img = np.clip(img, 0, 1)
        return img

    def apply_scale(self, img, scale):
        if self.orig_scale:
            scale = unNormalizeScale(scale)
            img = img * scale
        return img

    def apply_tonemap(self, img):
        if self.tonemap_str == "none":
            return img
        gammaed = self.tonemap.process(img)
        return gammaed

    def quantize(self, img):
        if self.bits == 0:
            return img
        max_val = np.power(2, self.bits)
        img = img * max_val
        img = np.floor(img)
        img = img / max_val
        return img

    def colorJitter(self, img):
        if self.jitter == 0:
            return img
        hsv = colors.rgb_to_hsv(img)
        hue_offset = np.random.normal(0, self.jitter, 1)
        hsv[:, :, 0] = (hsv[:, :, 0] + hue_offset) % 1.0
        rgb = colors.hsv_to_rgb(hsv)
        return rgb

    def gaussianNoise(self, img):
        if self.noise == 0:
            return img
        noise_amount = np.random.uniform(0, self.noise, 1)
        noise_img = np.random.normal(0, noise_amount, img.shape)
        img = img + noise_img
        img = np.clip(img, 0, 1).astype(np.float32)
        return img

    def apply_white_balance(self, img):
        if self.wbModel is None:
            return img
        img = self.wbModel.correctImage(img)
        return img.copy()


def make_LDRfromHDR(opt):
    LDR_from_HDR = LDRfromHDR(
        opt.tonemap_LDR, opt.orig_scale, opt.clip, opt.quantization, opt.color_jitter, opt.noise
    )
    return LDR_from_HDR


def torchnormalizeEV(EV, mean=5.12, scale=6, clip=True):
    # Normalize based on the computed distribution between -1 1
    EV -= mean
    EV = EV / scale

    if clip:
        EV = torch.clip(EV, min=-1, max=1)

    return EV


def torchnormalizeEV0(EV, mean=5.12, scale=6, clip=True):
    # Normalize based on the computed distribution between 0 1
    EV -= mean
    EV = EV / scale

    if clip:
        EV = torch.clip(EV, min=-1, max=1)

    EV += 0.5
    EV = EV / 2

    return EV


def normalizeScale(x, scale=4):
    x = np.log10(x + 1)

    x = x / (scale / 2)
    x = x - 1

    return x


def unNormalizeScale(x, scale=4):
    x = x + 1
    x = x * (scale / 2)

    x = np.power(10, x) - 1

    return x


def normalizeIlluminance(x, scale=5):
    x = np.log10(x + 1)

    x = x / (scale / 2)
    x = x - 1

    return x


def unNormalizeIlluminance(x, scale=5):
    x = x + 1
    x = x * (scale / 2)

    x = np.power(10, x) - 1

    return x


def main(args):
    processor = LDRfromHDR(
        # tonemap=("log10", 10),
        tonemap=("gamma", args.gamma),
        orig_scale=False,
        clip=True,
        quantization=0,
        color_jitter=0,
        noise=0,
    )

    img_list = list(os.listdir(args.hdr_dir))
    img_list = [f for f in img_list if f.endswith(args.extension)]
    img_list = [f for f in img_list if not f.startswith("._")]

    if not os.path.exists(args.out_dir):
        os.makedirs(args.out_dir)

    for fname in tqdm(img_list):
        fname_out = ".".join(fname.split(".")[:-1])
        out = os.path.join(args.out_dir, f"{fname_out}.jpg")
        if os.path.exists(out) and not args.overwrite:
            continue

        fpath = os.path.join(args.hdr_dir, fname)
        img = cv2.imread(fpath, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        ldr, scale = processor.process(img)

        ldr = (ldr * 255).astype(np.uint8)
        ldr = cv2.cvtColor(ldr, cv2.COLOR_RGB2BGR)
        cv2.imwrite(out, ldr)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--hdr_dir", type=str, default="hdr")
    parser.add_argument("--out_dir", type=str, default="ldr")
    parser.add_argument("--extension", type=str, default=".exr")
    parser.add_argument("--overwrite", action="store_true")
    parser.add_argument("--gamma", type=float, default=2)
    args = parser.parse_args()

    main(args)