-
Notifications
You must be signed in to change notification settings - Fork 0
/
ICCProfile.py
7392 lines (6653 loc) · 234 KB
/
ICCProfile.py
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
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from __future__ import with_statement
from copy import copy
from hashlib import md5
import atexit
import binascii
import ctypes
import datetime
import locale
import math
import os
import re
import struct
import sys
import warnings
import zlib
from itertools import izip, imap
from time import localtime, mktime, strftime
from UserString import UserString
from weakref import WeakValueDictionary
if sys.platform == "win32":
import _winreg
else:
import subprocess as sp
if sys.platform == "darwin":
from platform import mac_ver
if sys.platform == "win32":
try:
import win32api
import win32gui
except ImportError:
pass
try:
import colord
except ImportError:
class Colord:
Colord = None
def quirk_manufacturer(self, manufacturer):
return manufacturer
def which(self, executable, paths=None):
return None
colord = Colord()
import colormath
import edid
import imfile
from colormath import NumberTuple
from defaultpaths import iccprofiles, iccprofiles_home
from encoding import get_encodings
from options import test_input_curve_clipping
from ordereddict import OrderedDict
try:
from log import safe_print
except ImportError:
from safe_print import safe_print
from util_decimal import float2dec
from util_list import intlist
from util_str import hexunescape, safe_str, safe_unicode
if sys.platform not in ("darwin", "win32"):
from defaultpaths import xdg_config_dirs, xdg_config_home
from edid import get_edid
from util_x import get_display
try:
import xrandr
except ImportError:
xrandr = None
from util_os import dlopen, which
elif sys.platform == "win32":
import util_win
if sys.getwindowsversion() < (6, ):
# WCS only available under Vista and later
mscms = None
else:
from win_handles import (get_process_handles, get_handle_name,
get_handle_type)
mscms = util_win._get_mscms_windll()
win_ver = util_win.win_ver()
win10_1903 = (win_ver[0].startswith("Windows 10") and
win_ver[2] >= "Version 1903")
elif sys.platform == "darwin":
from util_mac import osascript
# Gamut volumes in cubic colorspace units (L*a*b*) as reported by Argyll's
# iccgamut
GAMUT_VOLUME_SRGB = 833675.435316 # rel. col.
GAMUT_VOLUME_ADOBERGB = 1209986.014983 # rel. col.
GAMUT_VOLUME_SMPTE431_P3 = 1176953.485921 # rel. col.
# http://msdn.microsoft.com/en-us/library/dd371953%28v=vs.85%29.aspx
COLORPROFILESUBTYPE = {"NONE": 0x0000,
"RGB_WORKING_SPACE": 0x0001,
"PERCEPTUAL": 0x0002,
"ABSOLUTE_COLORIMETRIC": 0x0004,
"RELATIVE_COLORIMETRIC": 0x0008,
"SATURATION": 0x0010,
"CUSTOM_WORKING_SPACE": 0x0020}
# http://msdn.microsoft.com/en-us/library/dd371955%28v=vs.85%29.aspx (wrong)
# http://msdn.microsoft.com/en-us/library/windows/hardware/ff546018%28v=vs.85%29.aspx (ok)
COLORPROFILETYPE = {"ICC": 0,
"DMP": 1,
"CAMP": 2,
"GMMP": 3}
WCS_PROFILE_MANAGEMENT_SCOPE = {"SYSTEM_WIDE": 0,
"CURRENT_USER": 1}
ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE = 2015
debug = False
enc, fs_enc = get_encodings()
cmms = {"argl": "ArgyllCMS",
"ADBE": "Adobe",
"ACMS": "Agfa",
"Agfa": "Agfa",
"APPL": "Apple",
"appl": "Apple",
"CCMS": "ColorGear",
"UCCM": "ColorGear Lite",
"DL&C": "Digital Light & Color",
"EFI ": "EFI",
"FF ": "Fuji Film",
"HCMM": "Harlequin RIP",
"LgoS": "LogoSync",
"HDM ": "Heidelberg",
"Lino": "Linotype",
"lino": "Linotype",
"lcms": "Little CMS",
"KCMS": "Kodak",
"MCML": "Konica Minolta",
"MSFT": "Microsoft",
"SIGN": "Mutoh",
"RGMS": "DeviceLink",
"SICC": "SampleICC",
"32BT": "the imaging factory",
"WTG ": "Ware to Go",
"zc00": "Zoran"}
encodings = {
"mac": {
141: "africaans",
36: "albanian",
85: "amharic",
12: "arabic",
51: "armenian",
68: "assamese",
134: "aymara",
49: "azerbaijani-cyrllic",
50: "azerbaijani-arabic",
129: "basque",
67: "bengali",
137: "dzongkha",
142: "breton",
44: "bulgarian",
77: "burmese",
46: "byelorussian",
78: "khmer",
130: "catalan",
92: "chewa",
33: "simpchinese",
19: "tradchinese",
18: "croatian",
38: "czech",
7: "danish",
4: "dutch",
0: "roman",
94: "esperanto",
27: "estonian",
30: "faeroese",
31: "farsi",
13: "finnish",
34: "flemish",
1: "french",
140: "galician",
144: "scottishgaelic",
145: "manxgaelic",
52: "georgian",
2: "german",
14: "greek-monotonic",
148: "greek-polytonic",
133: "guarani",
69: "gujarati",
10: "hebrew",
21: "hindi",
26: "hungarian",
15: "icelandic",
81: "indonesian",
143: "inuktitut",
35: "irishgaelic",
146: "irishgaelic-dotsabove",
3: "italian",
11: "japanese",
138: "javaneserom",
73: "kannada",
61: "kashmiri",
48: "kazakh",
90: "kiryarwanda",
54: "kirghiz",
91: "rundi",
23: "korean",
60: "kurdish",
79: "lao",
131: "latin",
28: "latvian",
24: "lithuanian",
43: "macedonian",
93: "malagasy",
83: "malayroman-latin",
84: "malayroman-arabic",
72: "malayalam",
16: "maltese",
66: "marathi",
53: "moldavian",
57: "mongolian",
58: "mongolian-cyrillic",
64: "nepali",
9: "norwegian",
71: "oriya",
87: "oromo",
59: "pashto",
25: "polish",
8: "portuguese",
70: "punjabi",
132: "quechua",
37: "romanian",
32: "russian",
29: "sami",
65: "sanskrit",
42: "serbian",
62: "sindhi",
76: "sinhalese",
39: "slovak",
40: "slovenian",
88: "somali",
6: "spanish",
139: "sundaneserom",
89: "swahili",
5: "swedish",
82: "tagalog",
55: "tajiki",
74: "tamil",
135: "tatar",
75: "telugu",
22: "thai",
63: "tibetan",
86: "tigrinya",
147: "tongan",
17: "turkish",
56: "turkmen",
136: "uighur",
45: "ukrainian",
20: "urdu",
47: "uzbek",
80: "vietnamese",
128: "welsh",
41: "yiddish"
}
}
colorants = {
0: {
"description": "unknown",
"channels": ()
},
1: {
"description": "ITU-R BT.709",
"channels": ((0.64, 0.33), (0.3, 0.6), (0.15, 0.06))
},
2: {
"description": "SMPTE RP145-1994",
"channels": ((0.63, 0.34), (0.31, 0.595), (0.155, 0.07))
},
3: {
"description": "EBU Tech.3213-E",
"channels": ((0.64, 0.33), (0.29, 0.6), (0.15, 0.06))
},
4: {
"description": "P22",
"channels": ((0.625, 0.34), (0.28, 0.605), (0.155, 0.07))
}
}
geometry = {
0: "unknown",
1: "0/45 or 45/0",
2: "0/d or d/0"
}
illuminants = {
0: "unknown",
1: "D50",
2: "D65",
3: "D93",
4: "F2",
5: "D55",
6: "A",
7: "E",
8: "F8"
}
observers = {
0: "unknown",
1: "CIE 1931",
2: "CIE 1964"
}
manufacturers = {"ADBE": "Adobe Systems Incorporated",
"APPL": "Apple Computer, Inc.",
"agfa": "Agfa Graphics N.V.",
"argl": "ArgyllCMS", # Not registered
"DCAL": "DisplayCAL", # Not registered
"bICC": "basICColor GmbH",
"DL&C": "Digital Light & Color",
"EPSO": "Seiko Epson Corporation",
"HDM ": "Heidelberger Druckmaschinen AG",
"HP ": "Hewlett-Packard",
"KODA": "Kodak",
"lcms": "Little CMS",
"MONS": "Monaco Systems Inc.",
"MSFT": "Microsoft Corporation",
"qato": "QUATOGRAPHIC Technology GmbH",
"XRIT": "X-Rite"}
platform = {"APPL": "Apple",
"MSFT": "Microsoft",
"SGI ": "Silicon Graphics",
"SUNW": "Sun Microsystems"}
profileclass = {"scnr": "Input device profile",
"mntr": "Display device profile",
"prtr": "Output device profile",
"link": "DeviceLink profile",
"spac": "Color space Conversion profile",
"abst": "Abstract profile",
"nmcl": "Named color profile"}
tags = {"A2B0": "Device to PCS: Intent 0",
"A2B1": "Device to PCS: Intent 1",
"A2B2": "Device to PCS: Intent 2",
"B2A0": "PCS to device: Intent 0",
"B2A1": "PCS to device: Intent 1",
"B2A2": "PCS to device: Intent 2",
"CIED": "Characterization measurement values", # Non-standard
"DevD": "Characterization device values", # Non-standard
"arts": "Absolute to media relative transform", # Non-standard (Argyll)
"bkpt": "Media black point",
"bTRC": "Blue tone response curve",
"bXYZ": "Blue matrix column",
"chad": "Chromatic adaptation transform",
"ciis": "Colorimetric intent image state",
"clro": "Colorant order",
"cprt": "Copyright",
"desc": "Description",
"dmnd": "Device manufacturer name",
"dmdd": "Device model name",
"gamt": "Out of gamut tag",
"gTRC": "Green tone response curve",
"gXYZ": "Green matrix column",
"kTRC": "Gray tone response curve",
"lumi": "Luminance",
"meas": "Measurement type",
"mmod": "Make and model",
"ncl2": "Named colors",
"pseq": "Profile sequence description",
"rTRC": "Red tone response curve",
"rXYZ": "Red matrix column",
"targ": "Characterization target",
"tech": "Technology",
"vcgt": "Video card gamma table",
"view": "Viewing conditions",
"vued": "Viewing conditions description",
"wtpt": "Media white point"}
tech = {"fscn": "Film scanner",
"dcam": "Digital camera",
"rscn": "Reflective scanner",
"ijet": "Ink jet printer",
"twax": "Thermal wax printer",
"epho": "Electrophotographic printer",
"esta": "Electrostatic printer",
"dsub": "Dye sublimation printer",
"rpho": "Photographic paper printer",
"fprn": "Film writer",
"vidm": "Video monitor",
"vidc": "Video camera",
"pjtv": "Projection television",
"CRT ": "Cathode ray tube display",
"PMD ": "Passive matrix display",
"AMD ": "Active matrix display",
"KPCD": "Photo CD",
"imgs": "Photographic image setter",
"grav": "Gravure",
"offs": "Offset lithography",
"silk": "Silkscreen",
"flex": "Flexography",
"mpfs": "Motion picture film scanner",
"mpfr": "Motion picture film recorder",
"dmpc": "Digital motion picture camera",
"dcpj": "Digital cinema projector"}
ciis = {"scoe": "Scene colorimetry estimates",
"sape": "Scene appearance estimates",
"fpce": "Focal plane colorimetry estimates",
"rhoc": "Reflection hardcopy original colorimetry",
"rpoc": "Reflection print output colorimetry"}
def legacy_PCSLab_dec_to_uInt16(L, a, b):
# ICCv2 (legacy) PCS L*a*b* encoding
# Only used by LUT16Type and namedColor2Type in ICCv4
return [v * (652.80, 256, 256)[i] + (0, 32768, 32768)[i]
for i, v in enumerate((L, a, b))]
def legacy_PCSLab_uInt16_to_dec(L_uInt16, a_uInt16, b_uInt16):
# ICCv2 (legacy) PCS L*a*b* encoding
# Only used by LUT16Type and namedColor2Type in ICCv4
return [(v - (0, 32768, 32768)[i]) / (65280.0, 32768.0, 32768.0)[i] *
(100, 128, 128)[i]
for i, v in enumerate((L_uInt16, a_uInt16, b_uInt16))]
def Property(func):
return property(**func())
def create_RGB_A2B_XYZ(input_curves, clut, logfn=safe_print):
"""
Create RGB device A2B from input curve XYZ values and cLUT
Note that input curves and cLUT should already be adapted to D50.
"""
if len(input_curves) != 3:
raise ValueError("Wrong number of input curves: %i" % len(input_curves))
white_XYZ = clut[-1][-1]
clutres = len(clut[0])
itable = LUT16Type(None, "A2B0")
itable.matrix = colormath.Matrix3x3([(1, 0, 0), (0, 1, 0), (0, 0, 1)])
# Input curve interpolation
# Normlly the input curves would either be linear (= 1:1 mapping to
# cLUT) or the respective tone response curve.
# We use a overall linear curve that is 'bent' in <clutres> intervals
# to accomodate the non-linear TRC. Thus, we can get away with much
# fewer cLUT grid points.
# Use higher interpolation size than actual number of curve entries
steps = 2 ** 15 + 1
maxv = steps - 1.0
fwd = []
bwd = []
for i, input_curve in enumerate(input_curves):
if isinstance(input_curve, (tuple, list)):
linear = [v / (len(input_curve) - 1.0)
for v in xrange(len(input_curve))]
fwd.append(colormath.Interp(linear, input_curve, use_numpy=True))
bwd.append(colormath.Interp(input_curve, linear, use_numpy=True))
else:
# Gamma
fwd.append(lambda v, p=input_curve: colormath.specialpow(v, p))
bwd.append(lambda v, p=input_curve: colormath.specialpow(v, 1.0 / p))
itable.input.append([])
itable.output.append([0, 65535])
logfn("cLUT input curve segments:", clutres)
for i in xrange(3):
maxi = bwd[i](white_XYZ[1])
segment = 1.0 / (clutres - 1.0) * maxi
iv = 0.0
prevpow = fwd[i](0.0)
nextpow = fwd[i](segment)
prevv = 0
pprevpow = 0
clipped = nextpow <= prevpow
xp = []
for j in xrange(steps):
v = (j / maxv) * maxi
if v > iv + segment:
iv += segment
prevpow = nextpow
nextpow = fwd[i](iv + segment)
clipped = nextpow <= prevpow
logfn("#%i %s" % (iv * (clutres - 1), "XYZ"[i]),
"prev %.6f" % prevpow, "next %.6f" % nextpow,
"clip", clipped)
if not clipped:
prevs = 1.0 - (v - iv) / segment
nexts = (v - iv) / segment
vv = (prevs * prevpow + nexts * nextpow)
prevv = v
pprevpow = prevpow
else:
# Linearly interpolate
vv = colormath.convert_range(v, prevv, 1, prevpow, 1)
out = bwd[i](vv)
xp.append(out)
# Fill input curves from interpolated values
interp = colormath.Interp(xp, range(steps), use_numpy=True)
entries = 2049
threshold = bwd[i](pprevpow)
k = None
for j in xrange(entries):
n = j / (entries - 1.0)
v = interp(n) / maxv
if clipped and n + (1 / (entries - 1.0)) > threshold:
# Linear interpolate shaper for last n cLUT steps to prevent
# clipping in shaper
if k is None:
k = j
ov = v
v = min(ov + (1.0 - ov) * ((j - k) / (entries - k - 1.0)), 1.0)
# Slope limit for 16-bit encoding
itable.input[i].append(max(v, j / 65535.0) * 65535)
# Fill cLUT
clut = list(clut)
itable.clut = []
step = 1.0 / (clutres - 1.0)
for R in xrange(clutres):
for G in xrange(clutres):
row = list(clut.pop(0))
itable.clut.append([])
for B in xrange(clutres):
X, Y, Z = row.pop(0)
itable.clut[-1].append([max(v / white_XYZ[1] * 32768, 0)
for v in (X, Y, Z)])
return itable
def create_synthetic_clut_profile(rgb_space, description, XYZbp=None,
white_Y=1.0, clutres=9, entries=2049,
cat="Bradford"):
"""
Create a synthetic cLUT profile from a colorspace definition
"""
profile = ICCProfile()
profile.version = 2.2 # Match ArgyllCMS
profile.tags.desc = TextDescriptionType("", "desc")
profile.tags.desc.ASCII = description
profile.tags.cprt = TextType("text\0\0\0\0Public domain\0", "cprt")
profile.tags.wtpt = XYZType(profile=profile)
(profile.tags.wtpt.X,
profile.tags.wtpt.Y,
profile.tags.wtpt.Z) = colormath.get_whitepoint(rgb_space[1])
profile.tags.arts = chromaticAdaptionTag()
profile.tags.arts.update(colormath.get_cat_matrix(cat))
itable = profile.tags.A2B0 = LUT16Type(None, "A2B0", profile)
itable.matrix = colormath.Matrix3x3([(1, 0, 0), (0, 1, 0), (0, 0, 1)])
otable = profile.tags.B2A0 = LUT16Type(None, "B2A0", profile)
Xr, Yr, Zr = colormath.adapt(*colormath.RGB2XYZ(1, 0, 0, rgb_space=rgb_space),
whitepoint_source=rgb_space[1], cat=cat)
Xg, Yg, Zg = colormath.adapt(*colormath.RGB2XYZ(0, 1, 0, rgb_space=rgb_space),
whitepoint_source=rgb_space[1], cat=cat)
Xb, Yb, Zb = colormath.adapt(*colormath.RGB2XYZ(0, 0, 1, rgb_space=rgb_space),
whitepoint_source=rgb_space[1], cat=cat)
m1 = colormath.Matrix3x3(((Xr, Xg, Xb),
(Yr, Yg, Yb),
(Zr, Zg, Zb))).inverted()
scale = 1 + (32767 / 32768.0)
m3 = colormath.Matrix3x3(((scale, 0, 0),
(0, scale, 0),
(0, 0, scale)))
otable.matrix = m1 * m3
# Input curve interpolation
# Normlly the input curves would either be linear (= 1:1 mapping to
# cLUT) or the respective tone response curve.
# We use a overall linear curve that is 'bent' in <clutres> intervals
# to accomodate the non-linear TRC. Thus, we can get away with much
# fewer cLUT grid points.
# Use higher interpolation size than actual number of curve entries
steps = 2 ** 15 + 1
maxv = steps - 1.0
gammas = rgb_space[0]
if not isinstance(gammas, (list, tuple)):
gammas = [gammas]
for i, gamma in enumerate(gammas):
maxi = colormath.specialpow(white_Y, 1.0 / gamma)
segment = 1.0 / (clutres - 1.0) * maxi
iv = 0.0
prevpow = 0.0
nextpow = colormath.specialpow(segment, gamma)
xp = []
for j in xrange(steps):
v = (j / maxv) * maxi
if v > iv + segment:
iv += segment
prevpow = nextpow
nextpow = colormath.specialpow(iv + segment, gamma)
prevs = 1.0 - (v - iv) / segment
nexts = (v - iv) / segment
vv = (prevs * prevpow + nexts * nextpow)
out = colormath.specialpow(vv, 1.0 / gamma)
xp.append(out)
interp = colormath.Interp(xp, range(steps), use_numpy=True)
# Create input curves
itable.input.append([])
otable.input.append([])
for j in xrange(4096):
otable.input[i].append(colormath.specialpow(j / 4095.0 * white_Y,
1.0 / gamma) * 65535)
# Fill input curves from interpolated values
for j in xrange(entries):
v = j / (entries - 1.0)
itable.input[i].append(interp(v) / maxv * 65535)
# Fill remaining input curves from first input curve and create output curves
for i in xrange(3):
if len(itable.input) < 3:
itable.input.append(itable.input[0])
otable.input.append(otable.input[0])
itable.output.append([0, 65535])
otable.output.append([0, 65535])
# Create and fill cLUT
itable.clut = []
step = 1.0 / (clutres - 1.0)
for R in xrange(clutres):
for G in xrange(clutres):
itable.clut.append([])
for B in xrange(clutres):
X, Y, Z = colormath.adapt(*colormath.RGB2XYZ(*[v * step * maxi
for v in (R, G, B)],
rgb_space=rgb_space),
whitepoint_source=rgb_space[1],
cat=cat)
X, Y, Z = colormath.blend_blackpoint(X, Y, Z, None, XYZbp)
itable.clut[-1].append([max(v / white_Y * 32768, 0)
for v in (X, Y, Z)])
otable.clut = []
for R in xrange(2):
for G in xrange(2):
otable.clut.append([])
for B in xrange(2):
otable.clut[-1].append([v * 65535 for v in (R , G, B)])
return profile
def create_synthetic_smpte2084_clut_profile(rgb_space, description,
black_cdm2=0, white_cdm2=400,
master_black_cdm2=0,
master_white_cdm2=10000,
use_alternate_master_white_clip=True,
content_rgb_space="DCI P3",
rolloff=True,
clutres=33, mode="HSV_ICtCp",
sat=1.0,
hue=0.5,
forward_xicclu=None,
backward_xicclu=None,
generate_B2A=False,
worker=None,
logfile=None,
cat="Bradford"):
"""
Create a synthetic cLUT profile with the SMPTE 2084 TRC from a colorspace
definition
mode: The gamut mapping mode when rolling off. Valid values:
"HSV_ICtCp" (default, recommended)
"ICtCp"
"XYZ" (not recommended, unpleasing hue shift)
"HSV" (not recommended, saturation loss)
"RGB" (not recommended, saturation loss, pleasing hue shift)
The roll-off saturation and hue preservation can be controlled.
sat: Saturation preservation factor [0.0, 1.0]
0.0 = Favor luminance preservation over saturation
1.0 = Favor saturation preservation over luminance
hue: Selective hue preservation factor [0.0, 1.0]
0.0 = Allow hue shift for redorange/orange/yellowgreen towards
yellow to preserve more saturation and detail
1.0 = Preserve hue
"""
if not rolloff:
raise NotImplementedError("rolloff needs to be True")
return create_synthetic_hdr_clut_profile("PQ", rgb_space, description,
black_cdm2, white_cdm2,
master_black_cdm2,
master_white_cdm2,
use_alternate_master_white_clip,
1.2, # Not used for PQ
5.0, # Not used for PQ
1.0, # Not used for PQ
content_rgb_space,
clutres, mode, sat, hue,
forward_xicclu,
backward_xicclu,
generate_B2A,
worker,
logfile,
cat)
def create_synthetic_hdr_clut_profile(hdr_format, rgb_space, description,
black_cdm2=0, white_cdm2=400,
master_black_cdm2=0, # Not used for HLG
master_white_cdm2=10000, # Not used for HLG
use_alternate_master_white_clip=True, # Not used for HLG
system_gamma=1.2, # Not used for PQ
ambient_cdm2=5, # Not used for PQ
maxsignal=1.0, # Not used for PQ
content_rgb_space="DCI P3",
clutres=33,
mode="HSV_ICtCp", # Not used for HLG
sat=1.0, # Not used for HLG
hue=0.5, # Not used for HLG
forward_xicclu=None,
backward_xicclu=None,
generate_B2A=False,
worker=None,
logfile=None,
cat="Bradford"):
"""
Create a synthetic HDR cLUT profile from a colorspace definition
"""
rgb_space = colormath.get_rgb_space(rgb_space)
content_rgb_space = colormath.get_rgb_space(content_rgb_space)
if hdr_format == "PQ":
bt2390 = colormath.BT2390(black_cdm2, white_cdm2, master_black_cdm2,
master_white_cdm2,
use_alternate_master_white_clip)
# Preserve detail in saturated colors if mastering display peak < 10K cd/m2
# XXX: Effect is detrimental to contrast at low target peak, and looks
# artificial for BT.2390-4. Don't use for now.
preserve_saturated_detail = False # master_white_cdm2 < 10000
if preserve_saturated_detail:
bt2390s = colormath.BT2390(black_cdm2, white_cdm2, master_black_cdm2,
10000)
maxv = white_cdm2 / 10000.0
eotf = lambda v: colormath.specialpow(v, -2084)
oetf = eotf_inverse = lambda v: colormath.specialpow(v, 1.0 / -2084)
eetf = bt2390.apply
# Apply a slight power to the segments to optimize encoding
encpow = min(max(bt2390.omaxi * (5 / 3.0), 1.0), 1.5)
def encf(v):
if v < bt2390.mmaxi:
v = colormath.convert_range(v, 0, bt2390.mmaxi, 0, 1)
v = colormath.specialpow(v, 1.0 / encpow, 2)
return colormath.convert_range(v, 0, 1, 0, bt2390.mmaxi)
else:
return v
def encf_inverse(v):
if v < bt2390.mmaxi:
v = colormath.convert_range(v, 0, bt2390.mmaxi, 0, 1)
v = colormath.specialpow(v, encpow, 2)
return colormath.convert_range(v, 0, 1, 0, bt2390.mmaxi)
else:
return v
elif hdr_format == "HLG":
# Note: Unlike the PQ black level lift, we apply HLG black offset as
# separate final step, not as part of the HLG EOTF
hlg = colormath.HLG(0, white_cdm2, system_gamma, ambient_cdm2, rgb_space)
if maxsignal < 1:
# Adjust EOTF so that EOTF[maxsignal] gives (approx) white_cdm2
while hlg.eotf(maxsignal) * hlg.white_cdm2 < white_cdm2:
hlg.white_cdm2 += 1
lscale = 1.0 / hlg.oetf(1.0, True)
hlg.white_cdm2 *= lscale
if lscale < 1 and logfile:
logfile.write("Nominal peak luminance after scaling = %.2f\n" %
hlg.white_cdm2)
Ymax = hlg.eotf(maxsignal)
maxv = 1.0
eotf = hlg.eotf
eotf_inverse = lambda v: hlg.eotf(v, True)
oetf = hlg.oetf
eetf = lambda v: v
encf = lambda v: v
else:
raise NotImplementedError("Unknown HDR format %r" % hdr_format)
tonemap = eetf(1) != 1
profile = ICCProfile()
profile.version = 2.2 # Match ArgyllCMS
profile.tags.desc = TextDescriptionType("", "desc")
profile.tags.desc.ASCII = description
profile.tags.cprt = TextType("text\0\0\0\0Public domain\0", "cprt")
profile.tags.wtpt = XYZType(profile=profile)
(profile.tags.wtpt.X,
profile.tags.wtpt.Y,
profile.tags.wtpt.Z) = colormath.get_whitepoint(rgb_space[1])
profile.tags.arts = chromaticAdaptionTag()
profile.tags.arts.update(colormath.get_cat_matrix(cat))
itable = profile.tags.A2B0 = LUT16Type(None, "A2B0", profile)
itable.matrix = colormath.Matrix3x3([(1, 0, 0), (0, 1, 0), (0, 0, 1)])
# HDR RGB
debugtable0 = profile.tags.DBG0 = LUT16Type(None, "DBG0", profile)
debugtable0.matrix = colormath.Matrix3x3([(1, 0, 0), (0, 1, 0), (0, 0, 1)])
# Display RGB
debugtable1 = profile.tags.DBG1 = LUT16Type(None, "DBG1", profile)
debugtable1.matrix = colormath.Matrix3x3([(1, 0, 0), (0, 1, 0), (0, 0, 1)])
# Display XYZ
debugtable2 = profile.tags.DBG2 = LUT16Type(None, "DBG2", profile)
debugtable2.matrix = colormath.Matrix3x3([(1, 0, 0), (0, 1, 0), (0, 0, 1)])
if generate_B2A:
otable = profile.tags.B2A0 = LUT16Type(None, "B2A0", profile)
Xr, Yr, Zr = colormath.adapt(*colormath.RGB2XYZ(1, 0, 0, rgb_space=rgb_space),
whitepoint_source=rgb_space[1], cat=cat)
Xg, Yg, Zg = colormath.adapt(*colormath.RGB2XYZ(0, 1, 0, rgb_space=rgb_space),
whitepoint_source=rgb_space[1], cat=cat)
Xb, Yb, Zb = colormath.adapt(*colormath.RGB2XYZ(0, 0, 1, rgb_space=rgb_space),
whitepoint_source=rgb_space[1], cat=cat)
m1 = colormath.Matrix3x3(((Xr, Xg, Xb),
(Yr, Yg, Yb),
(Zr, Zg, Zb)))
m2 = m1.inverted()
scale = 1 + (32767 / 32768.0)
m3 = colormath.Matrix3x3(((scale, 0, 0),
(0, scale, 0),
(0, 0, scale)))
otable.matrix = m2 * m3
# Input curve interpolation
# Normlly the input curves would either be linear (= 1:1 mapping to
# cLUT) or the respective tone response curve.
# We use a overall linear curve that is 'bent' in <clutres> intervals
# to accomodate the non-linear TRC. Thus, we can get away with much
# fewer cLUT grid points.
# Use higher interpolation size than actual number of curve entries
steps = 2 ** 15 + 1
maxstep = steps - 1.0
segment = 1.0 / (clutres - 1.0)
iv = 0.0
prevpow = eotf(eetf(0))
# Apply a slight power to segments to optimize encoding
nextpow = eotf(eetf(encf(segment)))
prevv = 0
pprevpow = [0]
clipped = False
xp = []
if generate_B2A:
oxp = []
for j in xrange(steps):
v = (j / maxstep)
if v > iv + segment:
iv += segment
prevpow = nextpow
# Apply a slight power to segments to optimize encoding
nextpow = eotf(eetf(encf(iv + segment)))
if nextpow > prevpow or test_input_curve_clipping:
prevs = 1.0 - (v - iv) / segment
nexts = (v - iv) / segment
vv = (prevs * prevpow + nexts * nextpow)
prevv = v
if prevpow > pprevpow[-1]:
pprevpow.append(prevpow)
else:
clipped = True
# Linearly interpolate
vv = colormath.convert_range(v, prevv, 1, prevpow, 1)
out = eotf_inverse(vv)
xp.append(out)
if generate_B2A:
oxp.append(eotf(eetf(v)) / maxv)
interp = colormath.Interp(xp, range(steps), use_numpy=True)
if generate_B2A:
ointerp = colormath.Interp(oxp, range(steps), use_numpy=True)
# Save interpolation input values for diagnostic purposes
profile.tags.kTRC = CurveType()
interp_inverse = colormath.Interp(range(steps), xp, use_numpy=True)
profile.tags.kTRC[:] = [interp_inverse(colormath.convert_range(v, 0, 2048,
0, maxstep)) *
65535
for v in xrange(2049)]
# Create input and output curves
for i in xrange(3):
itable.input.append([])
itable.output.append([0, 65535])
debugtable0.input.append([0, 65535])
debugtable0.output.append([0, 65535])
debugtable1.input.append([0, 65535])
debugtable1.output.append([0, 65535])
debugtable2.input.append([0, 65535])
debugtable2.output.append([0, 65535])
if generate_B2A:
otable.input.append([])
otable.output.append([0, 65535])
# Generate device-to-PCS shaper curves from interpolated values
if logfile:
logfile.write("Generating device-to-PCS shaper curves...\n")
entries = 1025
prevperc = 0
if generate_B2A:
endperc = 1
else:
endperc = 2
threshold = eotf_inverse(pprevpow[-2])
k = None
end = eotf_inverse(pprevpow[-1])
l = entries - 1
if end > threshold:
for j in xrange(entries):
n = j / (entries - 1.0)
if eetf(n) > end:
l = j - 1
break
for j in xrange(entries):
if worker and worker.thread_abort:
if forward_xicclu:
forward_xicclu.exit()
if backward_xicclu:
backward_xicclu.exit()
raise Exception("aborted")
n = j / (entries - 1.0)
v = interp(eetf(n)) / maxstep
if hdr_format == "PQ":
##threshold = 1.0 - segment * math.ceil((1.0 - bt2390.mmaxi) *
##(clutres - 1.0) + 1)
##check = n >= threshold
check = tonemap and eetf(n + (1 / (entries - 1.0))) > threshold
elif hdr_format == "HLG":
check = maxsignal < 1 and n >= maxsignal
if check and not test_input_curve_clipping:
# Linear interpolate shaper for last n cLUT steps to prevent
# clipping in shaper
if k is None:
k = j
ov = v
ev = interp(eetf(l / (entries - 1.0))) / maxstep
##v = min(ov + (1.0 - ov) * ((j - k) / (entries - k - 1.0)), 1.0)
v = min(colormath.convert_range(j, k, l, ov, ev), n)
for i in xrange(3):
itable.input[i].append(v * 65535)
perc = math.floor(n * endperc)
if logfile and perc > prevperc:
logfile.write("\r%i%%" % perc)
prevperc = perc
startperc = perc
if generate_B2A:
# Generate PCS-to-device shaper curves from interpolated values
if logfile:
logfile.write("\rGenerating PCS-to-device shaper curves...\n")
logfile.write("\r%i%%" % perc)
for j in xrange(4096):
if worker and worker.thread_abort:
if forward_xicclu:
forward_xicclu.exit()
if backward_xicclu:
backward_xicclu.exit()
raise Exception("aborted")
n = j / 4095.0
v = ointerp(n) / maxstep * 65535
for i in xrange(3):
otable.input[i].append(v)
perc = startperc + math.floor(n)
if logfile and perc > prevperc:
logfile.write("\r%i%%" % perc)