Debian Codegraph @

util/apply_cal_diff_from_icc.py

raw
1 #!/usr/bin/env python3
2 import os, sys
3
4 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
5
6 from DisplayCAL import argyll_cgats, config, colormath as cm
7 from DisplayCAL.cgats import CGATS
8 from DisplayCAL.icc_profile import ICCProfile
9 from DisplayCAL.worker import Worker, Xicclu, get_argyll_util, _applycal_bug_workaround
10
11
12 cgats_header = """CAL
13 ORIGINATOR "Argyll dispcal"
14 CREATED "Thu Aug 01 00:00:00 2019"
15 DEVICE_CLASS "DISPLAY"
16 COLOR_REP "RGB"
17 VIDEO_LUT_CALIBRATION_POSSIBLE "YES"
18 TV_OUTPUT_ENCODING "NO"
19
20 NUMBER_OF_FIELDS 4
21 BEGIN_DATA_FORMAT
22 RGB_I RGB_R RGB_G RGB_B
23 END_DATA_FORMAT
24
25 NUMBER_OF_SETS 256
26 BEGIN_DATA
27 """
28
29
30 def get_cal(
31 num_cal_entries,
32 target_whitepoint,
33 gamma,
34 profile,
35 intent="r",
36 direction="if",
37 order="n",
38 slope_limit=0,
39 ):
40 maxval = num_cal_entries - 1.0
41
42 # Get profile black and white point XYZ
43 XYZbp, XYZwp = get_bkpt_wtpt(profile, intent, "f", order)
44
45 if target_whitepoint:
46 XYZwp = target_whitepoint
47
48 # Calibrated XYZ
49 idata = []
50 for i in range(num_cal_entries):
51 XYZ = cm.adapt(
52 *[cm.special_pow(i / maxval, gamma, slope_limit)] * 3,
53 whitepoint_source=(1, 1, 1),
54 whitepoint_destination=XYZwp
55 )
56 XYZ = cm.blend_blackpoint(*XYZ, bp_in=(0, 0, 0), bp_out=XYZbp, wp=XYZwp)
57 idata.append(XYZ)
58
59 # Lookup calibration (target) XYZ through profile (inverse forward)
60 xicclu_invfwd = Xicclu(profile, intent, direction, order, "x")
61 xicclu_invfwd(idata)
62 xicclu_invfwd.exit()
63
64 # Get calibrated RGB
65 odata = xicclu_invfwd.get(get_clip=direction == "if")
66
67 if direction == "if":
68 Lbp = 0
69
70 # Deal with values that got clipped (below black as well as white)
71 do_low_clip = True
72 for i, values in enumerate(odata):
73 if values[3] is True or i == 0:
74 if do_low_clip and (i / maxval * 100 < Lbp or i == 0):
75 # Set to black
76 values[:] = [0.0, 0.0, 0.0]
77 elif i == maxval and [round(v, 4) for v in values[:3]] == [1, 1, 1]:
78 # Set to white
79 values[:] = [1.0, 1.0, 1.0]
80 else:
81 # First non-clipping value disables low clipping
82 do_low_clip = False
83 if len(values) > 3:
84 values.pop()
85
86 return odata
87
88
89 def get_interp(cal, inverse=False, smooth=False):
90 num_cal_entries = len(cal)
91 cal_entry_max = num_cal_entries - 1.0
92
93 linear = [(i / cal_entry_max,) * 3 for i in range(num_cal_entries)]
94
95 if smooth:
96 for lower, row in enumerate(cal[1:], 1):
97 v = min(row) * cal_entry_max
98 print(lower / cal_entry_max * 255, "->", v / cal_entry_max * 255)
99 if lower + 1 >= v >= lower or lower / cal_entry_max * 255 >= 8:
100 # Use max index of 4 (+ 2 = 6 = ~2% signal)
101 if lower == 1:
102 # First value already above threshold, disable smoothing
103 lower = 0
104 else:
105 print("lower", lower)
106 break
107 t = num_cal_entries // 128
108 for i in range(3):
109 values = cm.make_monotonically_increasing([v[i] for v in cal])
110 if lower:
111 # values[:lower] = cm.smooth_avg(values[:lower], 3, (1,) * 3)
112 values[:lower] = [
113 j / float(lower) * values[lower] for j in range(lower)
114 ]
115 if lower < num_cal_entries:
116 # Smooth up to ~5% signal
117 start, end = max(lower - t * 2, 0), lower + t * 2
118 print("start, end", start, end)
119 values[start:end] = cm.smooth_avg(
120 values[start:end], 1, (1,) * (t + 1)
121 )
122 values[:] = cm.smooth_avg(values[:], 1, (1,) * (t + 1))
123 for j, v in enumerate(values):
124 cal[j][i] = v
125
126 if inverse:
127 xp = cal
128 fp = linear
129 else:
130 xp = linear
131 fp = cal
132
133 interp = []
134 for i in range(3):
135 interp.append(cm.Interp([v[i] for v in xp], [v[i] for v in fp], use_numpy=True))
136
137 return interp
138
139
140 def get_bkpt_wtpt(profile, intent, direction="f", order="n"):
141 xicclu_fwd = Xicclu(profile, intent, direction, order, "x")
142 xicclu_fwd([(0, 0, 0), (1, 1, 1)])
143 xicclu_fwd.exit()
144 return xicclu_fwd.get()
145
146
147 def main(icc_profile_filename, target_whitepoint=None, gamma=2.2, skip_cal=False):
148 profile = ICCProfile(icc_profile_filename)
149
150 worker = Worker()
151
152 if target_whitepoint:
153 intent = "a"
154 else:
155 intent = "r"
156
157 gamma = float(gamma)
158
159 num_cal_entries = 4096
160 # cal_entry_max = num_cal_entries - 1.0
161
162 ogamma = {
163 -2.4: "sRGB",
164 -3.0: "LStar",
165 -2084: "SMPTE2084",
166 -709: "BT709",
167 -240: "SMPTE240M",
168 -601: "BT601",
169 }.get(gamma, gamma)
170 owtpt = target_whitepoint and ".%s" % target_whitepoint or ""
171
172 filename, ext = os.path.splitext(icc_profile_filename)
173
174 # Get existing calibration CGATS from profile
175 existing_cgats = argyll_cgats.extract_cal_from_profile(
176 profile, raise_on_missing_cal=False
177 )
178
179 # Enabling this will do a linear blend below interpolation threshold, which
180 # is probably not what we want - rather, the original cal should blend into
181 # the linear portion
182 applycal = False
183
184 applycal_inverse = not list(
185 filter(
186 lambda tagname: tagname.startswith("A2B") or tagname.startswith("B2A"),
187 profile.tags,
188 )
189 )
190 print("Use applycal to apply cal?", applycal)
191 print("Use applycal to apply inverse cal?", applycal_inverse)
192 print("Ensuring 256 entry TRC tags")
193 _applycal_bug_workaround(profile)
194 existing_cgats_filename = f"{filename}.tmp.cal"
195 input_color_profile_filename = f"{filename}.tmp{ext}"
196 out_color_profile_filename = f"{filename}.calapplied{ext}"
197 if (applycal or applycal_inverse) and existing_cgats:
198 print("Writing TMP profile for applycal")
199 profile.write(input_color_profile_filename)
200
201 if applycal and existing_cgats:
202 # Apply cal
203 existing_cgats.write(existing_cgats_filename)
204 result = worker.exec_cmd(
205 get_argyll_util("applycal"),
206 [
207 "-v",
208 existing_cgats_filename,
209 input_color_profile_filename,
210 out_color_profile_filename,
211 ],
212 capture_output=True,
213 log_output=True,
214 )
215 if not result and not os.path.isfile(out_color_profile_filename):
216 raise Exception("applycal returned a non-zero exit code")
217 elif isinstance(result, Exception):
218 raise result
219 calapplied = ICCProfile(out_color_profile_filename)
220 else:
221 calapplied = profile
222
223 if target_whitepoint:
224 try:
225 target_whitepoint = float(target_whitepoint)
226 except ValueError:
227 pass
228 target_whitepoint = cm.get_whitepoint(target_whitepoint)
229
230 # target_whitepoint = cm.adapt(*target_whitepoint,
231 # whitepoint_source=profile.tags.wtpt.ir.values())
232
233 logfiles = sys.stdout
234
235 # Lookup scaled down white XYZ
236 logfiles.write("Looking for solution...\n")
237 for n in range(9):
238 XYZscaled = []
239 for i in range(2001):
240 XYZscaled.append(
241 [v * (1 - (n * 2001 + i) / 20000.0) for v in target_whitepoint]
242 )
243 RGBscaled = worker.xicclu(
244 profile, XYZscaled, intent, "if", pcs="x", get_clip=True
245 )
246 # Find point at which it no longer clips
247 XYZwscaled = None
248 for i, RGBclip in enumerate(RGBscaled):
249 if RGBclip[3] is True or max(RGBclip[:3]) > 1:
250 # Clipped, skip
251 continue
252 # Found
253 XYZwscaled = XYZscaled[i]
254 logfiles.write(
255 "Solution found at index %i " "(step size %f)\n" % (i, 1 / 2000.0)
256 )
257 logfiles.write("RGB white %6.4f %6.4f %6.4f\n" % tuple(RGBclip[:3]))
258 logfiles.write(
259 "XYZ white %6.4f %6.4f %6.4f, "
260 "CCT %.1f K\n" % tuple(XYZscaled[i] + [cm.XYZ2CCT(*XYZwscaled)])
261 )
262 break
263 else:
264 if n == 8:
265 break
266 if XYZwscaled:
267 # Found solution
268 break
269 if not XYZwscaled:
270 raise Exception(
271 "No solution found in %i " "iterations with %i steps" % (n, i)
272 )
273 target_whitepoint = XYZwscaled
274 del RGBscaled
275
276 if not applycal or applycal_inverse:
277 ccal = get_cal(
278 num_cal_entries,
279 target_whitepoint,
280 gamma,
281 profile,
282 intent,
283 "if",
284 slope_limit=0,
285 )
286
287 out_color_profile_filename = (
288 filename
289 + " %s%s" % (target_whitepoint and "%s " % owtpt[1:] or "", ogamma)
290 + ext
291 )
292
293 if target_whitepoint is False: # NEVER
294 # Apply inverse CAL with PCS white
295 main(icc_profile_filename, gamma=gamma, skip_cal=True)
296 else:
297 # Generate inverse calibration
298
299 # Apply inverse CAL and write output file
300 if not applycal_inverse:
301 # Use our own code
302
303 TRC = []
304
305 seen = []
306
307 for tagname in (
308 "A2B0",
309 "A2B1",
310 "A2B2",
311 "B2A0",
312 "B2A1",
313 "B2A2",
314 "rTRC",
315 "gTRC",
316 "bTRC",
317 ):
318 if tagname not in profile.tags:
319 continue
320 print(tagname)
321 if profile.tags[tagname] in seen:
322 print("Already seen")
323 continue
324 seen.append(profile.tags[tagname])
325 if tagname.startswith("A2B"):
326 # Apply calibration to input curves
327 cal = get_cal(num_cal_entries, None, gamma, profile, intent, "if")
328 interp_i = get_interp(cal, True)
329 entries = profile.tags[tagname].input
330 elif tagname.startswith("B2A"):
331 # Apply inverse calibration to output curves
332 if profile.tags[tagname].clut_grid_steps <= 9:
333 # Low quality. Skip.
334 print("Low quality, skipping")
335 continue
336 cal = get_cal(num_cal_entries, None, gamma, profile, intent, "b")
337 interp_i = get_interp(cal, True)
338 entries = profile.tags[tagname].output
339 else:
340 entries = profile.tags[tagname]
341 TRC.append(entries[:])
342 num_entries = len(entries)
343 j = "rgb".index(tagname[0])
344 cal = get_cal(
345 num_cal_entries, None, gamma, profile, intent, "if", "r"
346 )
347 interp_i = get_interp(cal, True)
348 cinterp = cm.Interp(
349 [
350 interp_i[j](i / (num_entries - 1.0))
351 for i in range(num_entries)
352 ],
353 entries,
354 use_numpy=True,
355 )
356 entries[:] = [
357 cinterp(i / (num_entries - 1.0)) for i in range(num_entries)
358 ]
359 continue
360 for j in range(3):
361 num_entries = len(entries[j])
362 if tagname.startswith("A2B"):
363 cinterp = cm.Interp(
364 [
365 interp_i[j](i / (num_entries - 1.0))
366 for i in range(num_entries)
367 ],
368 [v / 65535.0 for v in entries[j]],
369 use_numpy=True,
370 )
371 elif tagname.startswith("B2A"):
372 rinterp = cm.Interp(
373 [v / 65535.0 for v in entries[j]],
374 [i / (num_entries - 1.0) for i in range(num_entries)],
375 use_numpy=True,
376 )
377 cinterp = cm.Interp(
378 [
379 rinterp(i / (num_entries - 1.0))
380 for i in range(num_entries)
381 ],
382 [
383 interp_i[j](i / (num_entries - 1.0))
384 for i in range(num_entries)
385 ],
386 use_numpy=True,
387 )
388 entries[j] = []
389 num_entries = max(num_entries, 256)
390 for i in range(num_entries):
391 entries[j].append(
392 min(max(cinterp(i / (num_entries - 1.0)) * 65535, 0), 65535)
393 )
394
395 # Check for identical initial TRC tags, and force them identical again
396 if TRC and TRC.count(TRC[0]) == 3:
397 print("Forcing identical TRC tags")
398 for channel in "rb":
399 profile.tags[channel + "TRC"] = profile.tags.gTRC
400
401 elif existing_cgats:
402 # Use Argyll applycal
403 # XXX: Want to derive different cals for cLUT and TRC tags.
404 # Not possible with applycal unless applying cals separately and
405 # combining the profile parts later?
406
407 # Get inverse calibration
408 interp_i = get_interp(ccal, True)
409 ical = []
410 # Argyll can only deal with 256 cal entries
411 for i in range(256):
412 ical.append([cinterp(i / 255.0) for cinterp in interp_i])
413
414 # Write inverse CAL
415 icgats = cgats_header
416 for i, (R, G, B) in enumerate(ical):
417 icgats += "%.7f %.7f %.7f %.7f\n" % (i / 255.0, R, G, B)
418 icgats += "END_DATA\n"
419 ical_filename = icc_profile_filename + owtpt + ".%s.inverse.cal" % ogamma
420 with open(ical_filename, "wb") as f:
421 f.write(icgats.encode())
422
423 result = worker.exec_cmd(
424 get_argyll_util("applycal"),
425 ["-v", ical_filename, filename + ".tmp" + ext, out_color_profile_filename],
426 capture_output=True,
427 log_output=True,
428 )
429 if not result and not os.path.isfile(out_color_profile_filename):
430 raise Exception("applycal returned a non-zero exit code")
431 elif isinstance(result, Exception):
432 raise result
433
434 profile = ICCProfile(out_color_profile_filename)
435
436 out_profile = profile
437
438 if not skip_cal:
439 # Improve existing calibration with new calibration
440
441 if applycal:
442 ccal = get_cal(
443 256, target_whitepoint, gamma, calapplied, intent, "if", slope_limit=0
444 )
445 num_cal_entries = len(ccal)
446 else:
447 if not existing_cgats:
448 existing_cgats = CGATS(config.get_data_path("linear.cal"))
449
450 num_cal_entries = len(existing_cgats[0].DATA)
451
452 cal_entry_max = num_cal_entries - 1.0
453
454 if not applycal:
455 interp = get_interp(ccal, False, True)
456
457 # Create CAL diff
458 cgats = cgats_header
459 for i in range(num_cal_entries):
460 RGB = [cinterp(i / cal_entry_max) for cinterp in interp]
461 R, G, B = (min(max(v, 0), 1) for v in RGB)
462 cgats += "%.7f %.7f %.7f %.7f\n" % (i / cal_entry_max, R, G, B)
463 cgats += "END_DATA\n"
464 with open(
465 icc_profile_filename + owtpt + ".%s.diff.cal" % ogamma, "wb"
466 ) as f:
467 f.write(cgats.encode())
468
469 cgats_cal_interp = []
470 for _i in range(3):
471 cgats_cal_interp.append(
472 cm.Interp([v / cal_entry_max for v in range(num_cal_entries)], [])
473 )
474 for _i, row in existing_cgats[0].DATA.items():
475 for j, channel in enumerate("RGB"):
476 cgats_cal_interp[j].fp.append(row["RGB_" + channel])
477
478 # Create CAL
479 cgats = cgats_header
480 for i in range(num_cal_entries):
481 if applycal:
482 RGB = [ccal[i][j] for j in range(3)]
483 else:
484 RGB = [
485 cgats_cal_interp[j](cinterp(i / cal_entry_max))
486 for j, cinterp in enumerate(interp)
487 ]
488 R, G, B = (min(max(v, 0), 1) for v in RGB)
489 cgats += "%.7f %.7f %.7f %.7f\n" % (i / cal_entry_max, R, G, B)
490 cgats += "END_DATA\n"
491 with open(icc_profile_filename + owtpt + ".%s.cal" % ogamma, "wb") as f:
492 f.write(cgats.encode())
493
494 # Add CAL as vcgt to profile
495 out_profile.tags.vcgt = argyll_cgats.cal_to_vcgt(cgats)
496
497 if target_whitepoint:
498 # Update wtpt tag
499 (
500 out_profile.tags.wtpt.X,
501 out_profile.tags.wtpt.Y,
502 out_profile.tags.wtpt.Z,
503 ) = target_whitepoint
504
505 # Write updated profile
506 out_profile.setDescription(
507 out_profile.getDescription()
508 + " %s%s" % (target_whitepoint and "%s " % owtpt[1:] or "", ogamma)
509 )
510 out_profile.calculate_id()
511 out_profile.write(out_color_profile_filename)
512
513
514 if __name__ == "__main__":
515 config.initcfg()
516 main(*sys.argv[1:4])