/
colorconv.py
2314 lines (1886 loc) · 65.9 KB
/
colorconv.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
"""Functions for converting between color spaces.
The "central" color space in this module is RGB, more specifically the linear
sRGB color space using D65 as a white-point [1]_. This represents a
standard monitor (w/o gamma correction). For a good FAQ on color spaces see
[2]_.
The API consists of functions to convert to and from RGB as defined above, as
well as a generic function to convert to and from any supported color space
(which is done through RGB in most cases).
Supported color spaces
----------------------
* RGB : Red Green Blue.
Here the sRGB standard [1]_.
* HSV : Hue, Saturation, Value.
Uniquely defined when related to sRGB [3]_.
* RGB CIE : Red Green Blue.
The original RGB CIE standard from 1931 [4]_. Primary colors are 700 nm
(red), 546.1 nm (blue) and 435.8 nm (green).
* XYZ CIE : XYZ
Derived from the RGB CIE color space. Chosen such that
``x == y == z == 1/3`` at the whitepoint, and all color matching
functions are greater than zero everywhere.
* LAB CIE : Lightness, a, b
Colorspace derived from XYZ CIE that is intended to be more
perceptually uniform
* LUV CIE : Lightness, u, v
Colorspace derived from XYZ CIE that is intended to be more
perceptually uniform
* LCH CIE : Lightness, Chroma, Hue
Defined in terms of LAB CIE. C and H are the polar representation of
a and b. The polar angle C is defined to be on ``(0, 2*pi)``
:author: Nicolas Pinto (rgb2hsv)
:author: Ralf Gommers (hsv2rgb)
:author: Travis Oliphant (XYZ and RGB CIE functions)
:author: Matt Terry (lab2lch)
:author: Alex Izvorski (yuv2rgb, rgb2yuv and related)
:license: modified BSD
References
----------
.. [1] Official specification of sRGB, IEC 61966-2-1:1999.
.. [2] http://www.poynton.com/ColorFAQ.html
.. [3] https://en.wikipedia.org/wiki/HSL_and_HSV
.. [4] https://en.wikipedia.org/wiki/CIE_1931_color_space
"""
from warnings import warn
import numpy as np
from scipy import linalg
from .._shared.utils import (
_supported_float_type,
channel_as_last_axis,
identity,
reshape_nd,
slice_at_axis,
)
from ..util import dtype, dtype_limits
# TODO: when minimum numpy dependency is 1.25 use:
# np..exceptions.AxisError instead of AxisError
# and remove this try-except
try:
from numpy import AxisError
except ImportError:
from numpy.exceptions import AxisError
def convert_colorspace(arr, fromspace, tospace, *, channel_axis=-1):
"""Convert an image array to a new color space.
Valid color spaces are:
'RGB', 'HSV', 'RGB CIE', 'XYZ', 'YUV', 'YIQ', 'YPbPr', 'YCbCr', 'YDbDr'
Parameters
----------
arr : (..., C=3, ...) array_like
The image to convert. By default, the final dimension denotes
channels.
fromspace : str
The color space to convert from. Can be specified in lower case.
tospace : str
The color space to convert to. Can be specified in lower case.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The converted image. Same dimensions as input.
Raises
------
ValueError
If fromspace is not a valid color space
ValueError
If tospace is not a valid color space
Notes
-----
Conversion is performed through the "central" RGB color space,
i.e. conversion from XYZ to HSV is implemented as ``XYZ -> RGB -> HSV``
instead of directly.
Examples
--------
>>> from skimage import data
>>> img = data.astronaut()
>>> img_hsv = convert_colorspace(img, 'RGB', 'HSV')
"""
fromdict = {
'rgb': identity,
'hsv': hsv2rgb,
'rgb cie': rgbcie2rgb,
'xyz': xyz2rgb,
'yuv': yuv2rgb,
'yiq': yiq2rgb,
'ypbpr': ypbpr2rgb,
'ycbcr': ycbcr2rgb,
'ydbdr': ydbdr2rgb,
}
todict = {
'rgb': identity,
'hsv': rgb2hsv,
'rgb cie': rgb2rgbcie,
'xyz': rgb2xyz,
'yuv': rgb2yuv,
'yiq': rgb2yiq,
'ypbpr': rgb2ypbpr,
'ycbcr': rgb2ycbcr,
'ydbdr': rgb2ydbdr,
}
fromspace = fromspace.lower()
tospace = tospace.lower()
if fromspace not in fromdict:
msg = f'`fromspace` has to be one of {fromdict.keys()}'
raise ValueError(msg)
if tospace not in todict:
msg = f'`tospace` has to be one of {todict.keys()}'
raise ValueError(msg)
return todict[tospace](
fromdict[fromspace](arr, channel_axis=channel_axis), channel_axis=channel_axis
)
def _prepare_colorarray(arr, force_copy=False, *, channel_axis=-1):
"""Check the shape of the array and convert it to
floating point representation.
"""
arr = np.asanyarray(arr)
if arr.shape[channel_axis] != 3:
msg = (
f'the input array must have size 3 along `channel_axis`, '
f'got {arr.shape}'
)
raise ValueError(msg)
float_dtype = _supported_float_type(arr.dtype)
if float_dtype == np.float32:
_func = dtype.img_as_float32
else:
_func = dtype.img_as_float64
return _func(arr, force_copy=force_copy)
def _validate_channel_axis(channel_axis, ndim):
if not isinstance(channel_axis, int):
raise TypeError("channel_axis must be an integer")
if channel_axis < -ndim or channel_axis >= ndim:
raise AxisError("channel_axis exceeds array dimensions")
def rgba2rgb(rgba, background=(1, 1, 1), *, channel_axis=-1):
"""RGBA to RGB conversion using alpha blending [1]_.
Parameters
----------
rgba : (..., C=4, ...) array_like
The image in RGBA format. By default, the final dimension denotes
channels.
background : array_like
The color of the background to blend the image with (3 floats
between 0 to 1 - the RGB value of the background).
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `rgba` is not at least 2D with shape (..., 4, ...).
References
----------
.. [1] https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending
Examples
--------
>>> from skimage import color
>>> from skimage import data
>>> img_rgba = data.logo()
>>> img_rgb = color.rgba2rgb(img_rgba)
"""
arr = np.asanyarray(rgba)
_validate_channel_axis(channel_axis, arr.ndim)
channel_axis = channel_axis % arr.ndim
if arr.shape[channel_axis] != 4:
msg = (
f'the input array must have size 4 along `channel_axis`, '
f'got {arr.shape}'
)
raise ValueError(msg)
float_dtype = _supported_float_type(arr.dtype)
if float_dtype == np.float32:
arr = dtype.img_as_float32(arr)
else:
arr = dtype.img_as_float64(arr)
background = np.ravel(background).astype(arr.dtype)
if len(background) != 3:
raise ValueError(
'background must be an array-like containing 3 RGB '
f'values. Got {len(background)} items'
)
if np.any(background < 0) or np.any(background > 1):
raise ValueError('background RGB values must be floats between ' '0 and 1.')
# reshape background for broadcasting along non-channel axes
background = reshape_nd(background, arr.ndim, channel_axis)
alpha = arr[slice_at_axis(slice(3, 4), axis=channel_axis)]
channels = arr[slice_at_axis(slice(3), axis=channel_axis)]
out = np.clip((1 - alpha) * background + alpha * channels, a_min=0, a_max=1)
return out
@channel_as_last_axis()
def rgb2hsv(rgb, *, channel_axis=-1):
"""RGB to HSV color space conversion.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in HSV format. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
Conversion between RGB and HSV color spaces results in some loss of
precision, due to integer arithmetic and rounding [1]_.
References
----------
.. [1] https://en.wikipedia.org/wiki/HSL_and_HSV
Examples
--------
>>> from skimage import color
>>> from skimage import data
>>> img = data.astronaut()
>>> img_hsv = color.rgb2hsv(img)
"""
input_is_one_pixel = rgb.ndim == 1
if input_is_one_pixel:
rgb = rgb[np.newaxis, ...]
arr = _prepare_colorarray(rgb, channel_axis=-1)
out = np.empty_like(arr)
# -- V channel
out_v = arr.max(-1)
# -- S channel
delta = np.ptp(arr, axis=-1)
# Ignore warning for zero divided by zero
old_settings = np.seterr(invalid='ignore')
out_s = delta / out_v
out_s[delta == 0.0] = 0.0
# -- H channel
# red is max
idx = arr[..., 0] == out_v
out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]
# green is max
idx = arr[..., 1] == out_v
out[idx, 0] = 2.0 + (arr[idx, 2] - arr[idx, 0]) / delta[idx]
# blue is max
idx = arr[..., 2] == out_v
out[idx, 0] = 4.0 + (arr[idx, 0] - arr[idx, 1]) / delta[idx]
out_h = (out[..., 0] / 6.0) % 1.0
out_h[delta == 0.0] = 0.0
np.seterr(**old_settings)
# -- output
out[..., 0] = out_h
out[..., 1] = out_s
out[..., 2] = out_v
# # remove NaN
out[np.isnan(out)] = 0
if input_is_one_pixel:
out = np.squeeze(out, axis=0)
return out
@channel_as_last_axis()
def hsv2rgb(hsv, *, channel_axis=-1):
"""HSV to RGB color space conversion.
Parameters
----------
hsv : (..., C=3, ...) array_like
The image in HSV format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `hsv` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
Conversion between RGB and HSV color spaces results in some loss of
precision, due to integer arithmetic and rounding [1]_.
References
----------
.. [1] https://en.wikipedia.org/wiki/HSL_and_HSV
Examples
--------
>>> from skimage import data
>>> img = data.astronaut()
>>> img_hsv = rgb2hsv(img)
>>> img_rgb = hsv2rgb(img_hsv)
"""
arr = _prepare_colorarray(hsv, channel_axis=-1)
hi = np.floor(arr[..., 0] * 6)
f = arr[..., 0] * 6 - hi
p = arr[..., 2] * (1 - arr[..., 1])
q = arr[..., 2] * (1 - f * arr[..., 1])
t = arr[..., 2] * (1 - (1 - f) * arr[..., 1])
v = arr[..., 2]
hi = np.stack([hi, hi, hi], axis=-1).astype(np.uint8) % 6
out = np.choose(
hi,
np.stack(
[
np.stack((v, t, p), axis=-1),
np.stack((q, v, p), axis=-1),
np.stack((p, v, t), axis=-1),
np.stack((p, q, v), axis=-1),
np.stack((t, p, v), axis=-1),
np.stack((v, p, q), axis=-1),
]
),
)
return out
# ---------------------------------------------------------------
# Primaries for the coordinate systems
# ---------------------------------------------------------------
cie_primaries = np.array([700, 546.1, 435.8])
sb_primaries = np.array([1.0 / 155, 1.0 / 190, 1.0 / 225]) * 1e5
# ---------------------------------------------------------------
# Matrices that define conversion between different color spaces
# ---------------------------------------------------------------
# From sRGB specification
xyz_from_rgb = np.array(
[
[0.412453, 0.357580, 0.180423],
[0.212671, 0.715160, 0.072169],
[0.019334, 0.119193, 0.950227],
]
)
rgb_from_xyz = linalg.inv(xyz_from_rgb)
# From https://en.wikipedia.org/wiki/CIE_1931_color_space
# Note: Travis's code did not have the divide by 0.17697
xyz_from_rgbcie = (
np.array([[0.49, 0.31, 0.20], [0.17697, 0.81240, 0.01063], [0.00, 0.01, 0.99]])
/ 0.17697
)
rgbcie_from_xyz = linalg.inv(xyz_from_rgbcie)
# construct matrices to and from rgb:
rgbcie_from_rgb = rgbcie_from_xyz @ xyz_from_rgb
rgb_from_rgbcie = rgb_from_xyz @ xyz_from_rgbcie
gray_from_rgb = np.array([[0.2125, 0.7154, 0.0721], [0, 0, 0], [0, 0, 0]])
yuv_from_rgb = np.array(
[
[0.299, 0.587, 0.114],
[-0.14714119, -0.28886916, 0.43601035],
[0.61497538, -0.51496512, -0.10001026],
]
)
rgb_from_yuv = linalg.inv(yuv_from_rgb)
yiq_from_rgb = np.array(
[
[0.299, 0.587, 0.114],
[0.59590059, -0.27455667, -0.32134392],
[0.21153661, -0.52273617, 0.31119955],
]
)
rgb_from_yiq = linalg.inv(yiq_from_rgb)
ypbpr_from_rgb = np.array(
[[0.299, 0.587, 0.114], [-0.168736, -0.331264, 0.5], [0.5, -0.418688, -0.081312]]
)
rgb_from_ypbpr = linalg.inv(ypbpr_from_rgb)
ycbcr_from_rgb = np.array(
[[65.481, 128.553, 24.966], [-37.797, -74.203, 112.0], [112.0, -93.786, -18.214]]
)
rgb_from_ycbcr = linalg.inv(ycbcr_from_rgb)
ydbdr_from_rgb = np.array(
[[0.299, 0.587, 0.114], [-0.45, -0.883, 1.333], [-1.333, 1.116, 0.217]]
)
rgb_from_ydbdr = linalg.inv(ydbdr_from_rgb)
# CIE LAB constants for Observer=2A, Illuminant=D65
# NOTE: this is actually the XYZ values for the illuminant above.
lab_ref_white = np.array([0.95047, 1.0, 1.08883])
# CIE XYZ tristimulus values of the illuminants, scaled to [0, 1]. For each illuminant I
# we have:
#
# illuminant[I]['2'] corresponds to the CIE XYZ tristimulus values for the 2 degree
# field of view.
#
# illuminant[I]['10'] corresponds to the CIE XYZ tristimulus values for the 10 degree
# field of view.
#
# illuminant[I]['R'] corresponds to the CIE XYZ tristimulus values for R illuminants
# in grDevices::convertColor
#
# The CIE XYZ tristimulus values are calculated from [1], using the formula:
#
# X = x * ( Y / y )
# Y = Y
# Z = ( 1 - x - y ) * ( Y / y )
#
# where Y = 1. The only exception is the illuminant "D65" with aperture angle
# 2, whose coordinates are copied from 'lab_ref_white' for
# backward-compatibility reasons.
#
# References
# ----------
# .. [1] https://en.wikipedia.org/wiki/Standard_illuminant
_illuminants = {
"A": {
'2': (1.098466069456375, 1, 0.3558228003436005),
'10': (1.111420406956693, 1, 0.3519978321919493),
'R': (1.098466069456375, 1, 0.3558228003436005),
},
"B": {
'2': (0.9909274480248003, 1, 0.8531327322886154),
'10': (0.9917777147717607, 1, 0.8434930535866175),
'R': (0.9909274480248003, 1, 0.8531327322886154),
},
"C": {
'2': (0.980705971659919, 1, 1.1822494939271255),
'10': (0.9728569189782166, 1, 1.1614480488951577),
'R': (0.980705971659919, 1, 1.1822494939271255),
},
"D50": {
'2': (0.9642119944211994, 1, 0.8251882845188288),
'10': (0.9672062750333777, 1, 0.8142801513128616),
'R': (0.9639501491621826, 1, 0.8241280285499208),
},
"D55": {
'2': (0.956797052643698, 1, 0.9214805860173273),
'10': (0.9579665682254781, 1, 0.9092525159847462),
'R': (0.9565317453467969, 1, 0.9202554587037198),
},
"D65": {
'2': (0.95047, 1.0, 1.08883), # This was: `lab_ref_white`
'10': (0.94809667673716, 1, 1.0730513595166162),
'R': (0.9532057125493769, 1, 1.0853843816469158),
},
"D75": {
'2': (0.9497220898840717, 1, 1.226393520724154),
'10': (0.9441713925645873, 1, 1.2064272211720228),
'R': (0.9497220898840717, 1, 1.226393520724154),
},
"E": {'2': (1.0, 1.0, 1.0), '10': (1.0, 1.0, 1.0), 'R': (1.0, 1.0, 1.0)},
}
def xyz_tristimulus_values(*, illuminant, observer, dtype=float):
"""Get the CIE XYZ tristimulus values.
Given an illuminant and observer, this function returns the CIE XYZ tristimulus
values [2]_ scaled such that :math:`Y = 1`.
Parameters
----------
illuminant : {"A", "B", "C", "D50", "D55", "D65", "D75", "E"}
The name of the illuminant (the function is NOT case sensitive).
observer : {"2", "10", "R"}
One of: 2-degree observer, 10-degree observer, or 'R' observer as in
R function ``grDevices::convertColor`` [3]_.
dtype: dtype, optional
Output data type.
Returns
-------
values : array
Array with 3 elements :math:`X, Y, Z` containing the CIE XYZ tristimulus values
of the given illuminant.
Raises
------
ValueError
If either the illuminant or the observer angle are not supported or
unknown.
References
----------
.. [1] https://en.wikipedia.org/wiki/Standard_illuminant#White_points_of_standard_illuminants
.. [2] https://en.wikipedia.org/wiki/CIE_1931_color_space#Meaning_of_X,_Y_and_Z
.. [3] https://www.rdocumentation.org/packages/grDevices/versions/3.6.2/topics/convertColor
Notes
-----
The CIE XYZ tristimulus values are calculated from :math:`x, y` [1]_, using the
formula
.. math:: X = x / y
.. math:: Y = 1
.. math:: Z = (1 - x - y) / y
The only exception is the illuminant "D65" with aperture angle 2° for
backward-compatibility reasons.
Examples
--------
Get the CIE XYZ tristimulus values for a "D65" illuminant for a 10 degree field of
view
>>> xyz_tristimulus_values(illuminant="D65", observer="10")
array([0.94809668, 1. , 1.07305136])
"""
illuminant = illuminant.upper()
observer = observer.upper()
try:
return np.asarray(_illuminants[illuminant][observer], dtype=dtype)
except KeyError:
raise ValueError(
f'Unknown illuminant/observer combination '
f'(`{illuminant}`, `{observer}`)'
)
# Haematoxylin-Eosin-DAB colorspace
# From original Ruifrok's paper: A. C. Ruifrok and D. A. Johnston,
# "Quantification of histochemical staining by color deconvolution,"
# Analytical and quantitative cytology and histology / the International
# Academy of Cytology [and] American Society of Cytology, vol. 23, no. 4,
# pp. 291-9, Aug. 2001.
rgb_from_hed = np.array([[0.65, 0.70, 0.29], [0.07, 0.99, 0.11], [0.27, 0.57, 0.78]])
hed_from_rgb = linalg.inv(rgb_from_hed)
# Following matrices are adapted form the Java code written by G.Landini.
# The original code is available at:
# https://web.archive.org/web/20160624145052/http://www.mecourse.com/landinig/software/cdeconv/cdeconv.html
# Hematoxylin + DAB
rgb_from_hdx = np.array([[0.650, 0.704, 0.286], [0.268, 0.570, 0.776], [0.0, 0.0, 0.0]])
rgb_from_hdx[2, :] = np.cross(rgb_from_hdx[0, :], rgb_from_hdx[1, :])
hdx_from_rgb = linalg.inv(rgb_from_hdx)
# Feulgen + Light Green
rgb_from_fgx = np.array(
[
[0.46420921, 0.83008335, 0.30827187],
[0.94705542, 0.25373821, 0.19650764],
[0.0, 0.0, 0.0],
]
)
rgb_from_fgx[2, :] = np.cross(rgb_from_fgx[0, :], rgb_from_fgx[1, :])
fgx_from_rgb = linalg.inv(rgb_from_fgx)
# Giemsa: Methyl Blue + Eosin
rgb_from_bex = np.array(
[
[0.834750233, 0.513556283, 0.196330403],
[0.092789, 0.954111, 0.283111],
[0.0, 0.0, 0.0],
]
)
rgb_from_bex[2, :] = np.cross(rgb_from_bex[0, :], rgb_from_bex[1, :])
bex_from_rgb = linalg.inv(rgb_from_bex)
# FastRed + FastBlue + DAB
rgb_from_rbd = np.array(
[
[0.21393921, 0.85112669, 0.47794022],
[0.74890292, 0.60624161, 0.26731082],
[0.268, 0.570, 0.776],
]
)
rbd_from_rgb = linalg.inv(rgb_from_rbd)
# Methyl Green + DAB
rgb_from_gdx = np.array(
[[0.98003, 0.144316, 0.133146], [0.268, 0.570, 0.776], [0.0, 0.0, 0.0]]
)
rgb_from_gdx[2, :] = np.cross(rgb_from_gdx[0, :], rgb_from_gdx[1, :])
gdx_from_rgb = linalg.inv(rgb_from_gdx)
# Hematoxylin + AEC
rgb_from_hax = np.array(
[[0.650, 0.704, 0.286], [0.2743, 0.6796, 0.6803], [0.0, 0.0, 0.0]]
)
rgb_from_hax[2, :] = np.cross(rgb_from_hax[0, :], rgb_from_hax[1, :])
hax_from_rgb = linalg.inv(rgb_from_hax)
# Blue matrix Anilline Blue + Red matrix Azocarmine + Orange matrix Orange-G
rgb_from_bro = np.array(
[
[0.853033, 0.508733, 0.112656],
[0.09289875, 0.8662008, 0.49098468],
[0.10732849, 0.36765403, 0.9237484],
]
)
bro_from_rgb = linalg.inv(rgb_from_bro)
# Methyl Blue + Ponceau Fuchsin
rgb_from_bpx = np.array(
[
[0.7995107, 0.5913521, 0.10528667],
[0.09997159, 0.73738605, 0.6680326],
[0.0, 0.0, 0.0],
]
)
rgb_from_bpx[2, :] = np.cross(rgb_from_bpx[0, :], rgb_from_bpx[1, :])
bpx_from_rgb = linalg.inv(rgb_from_bpx)
# Alcian Blue + Hematoxylin
rgb_from_ahx = np.array(
[[0.874622, 0.457711, 0.158256], [0.552556, 0.7544, 0.353744], [0.0, 0.0, 0.0]]
)
rgb_from_ahx[2, :] = np.cross(rgb_from_ahx[0, :], rgb_from_ahx[1, :])
ahx_from_rgb = linalg.inv(rgb_from_ahx)
# Hematoxylin + PAS
rgb_from_hpx = np.array(
[[0.644211, 0.716556, 0.266844], [0.175411, 0.972178, 0.154589], [0.0, 0.0, 0.0]]
)
rgb_from_hpx[2, :] = np.cross(rgb_from_hpx[0, :], rgb_from_hpx[1, :])
hpx_from_rgb = linalg.inv(rgb_from_hpx)
# -------------------------------------------------------------
# The conversion functions that make use of the matrices above
# -------------------------------------------------------------
def _convert(matrix, arr):
"""Do the color space conversion.
Parameters
----------
matrix : array_like
The 3x3 matrix to use.
arr : (..., C=3, ...) array_like
The input array. By default, the final dimension denotes
channels.
Returns
-------
out : (..., C=3, ...) ndarray
The converted array. Same dimensions as input.
"""
arr = _prepare_colorarray(arr)
return arr @ matrix.T.astype(arr.dtype)
@channel_as_last_axis()
def xyz2rgb(xyz, *, channel_axis=-1):
"""XYZ to RGB color space conversion.
Parameters
----------
xyz : (..., C=3, ...) array_like
The image in XYZ format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `xyz` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
The CIE XYZ color space is derived from the CIE RGB color space. Note
however that this function converts to sRGB.
References
----------
.. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space
Examples
--------
>>> from skimage import data
>>> from skimage.color import rgb2xyz, xyz2rgb
>>> img = data.astronaut()
>>> img_xyz = rgb2xyz(img)
>>> img_rgb = xyz2rgb(img_xyz)
"""
# Follow the algorithm from http://www.easyrgb.com/index.php
# except we don't multiply/divide by 100 in the conversion
arr = _convert(rgb_from_xyz, xyz)
mask = arr > 0.0031308
arr[mask] = 1.055 * np.power(arr[mask], 1 / 2.4) - 0.055
arr[~mask] *= 12.92
np.clip(arr, 0, 1, out=arr)
return arr
@channel_as_last_axis()
def rgb2xyz(rgb, *, channel_axis=-1):
"""RGB to XYZ color space conversion.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in XYZ format. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
The CIE XYZ color space is derived from the CIE RGB color space. Note
however that this function converts from sRGB.
References
----------
.. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space
Examples
--------
>>> from skimage import data
>>> img = data.astronaut()
>>> img_xyz = rgb2xyz(img)
"""
# Follow the algorithm from http://www.easyrgb.com/index.php
# except we don't multiply/divide by 100 in the conversion
arr = _prepare_colorarray(rgb, channel_axis=-1).copy()
mask = arr > 0.04045
arr[mask] = np.power((arr[mask] + 0.055) / 1.055, 2.4)
arr[~mask] /= 12.92
return arr @ xyz_from_rgb.T.astype(arr.dtype)
@channel_as_last_axis()
def rgb2rgbcie(rgb, *, channel_axis=-1):
"""RGB to RGB CIE color space conversion.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB CIE format. Same dimensions as input.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
References
----------
.. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space
Examples
--------
>>> from skimage import data
>>> from skimage.color import rgb2rgbcie
>>> img = data.astronaut()
>>> img_rgbcie = rgb2rgbcie(img)
"""
return _convert(rgbcie_from_rgb, rgb)
@channel_as_last_axis()
def rgbcie2rgb(rgbcie, *, channel_axis=-1):
"""RGB CIE to RGB color space conversion.
Parameters
----------
rgbcie : (..., C=3, ...) array_like
The image in RGB CIE format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which axis of the array corresponds to
channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
Returns
-------
out : (..., C=3, ...) ndarray
The image in RGB format. Same dimensions as input.
Raises
------
ValueError
If `rgbcie` is not at least 2-D with shape (..., C=3, ...).
References
----------
.. [1] https://en.wikipedia.org/wiki/CIE_1931_color_space
Examples
--------
>>> from skimage import data
>>> from skimage.color import rgb2rgbcie, rgbcie2rgb
>>> img = data.astronaut()
>>> img_rgbcie = rgb2rgbcie(img)
>>> img_rgb = rgbcie2rgb(img_rgbcie)
"""
return _convert(rgb_from_rgbcie, rgbcie)
@channel_as_last_axis(multichannel_output=False)
def rgb2gray(rgb, *, channel_axis=-1):
"""Compute luminance of an RGB image.
Parameters
----------
rgb : (..., C=3, ...) array_like
The image in RGB format. By default, the final dimension denotes
channels.
Returns
-------
out : ndarray
The luminance image - an array which is the same size as the input
array, but with the channel dimension removed.
Raises
------
ValueError
If `rgb` is not at least 2-D with shape (..., C=3, ...).
Notes
-----
The weights used in this conversion are calibrated for contemporary
CRT phosphors::
Y = 0.2125 R + 0.7154 G + 0.0721 B
If there is an alpha channel present, it is ignored.
References
----------
.. [1] http://poynton.ca/PDFs/ColorFAQ.pdf
Examples
--------
>>> from skimage.color import rgb2gray
>>> from skimage import data
>>> img = data.astronaut()
>>> img_gray = rgb2gray(img)
"""
rgb = _prepare_colorarray(rgb)
coeffs = np.array([0.2125, 0.7154, 0.0721], dtype=rgb.dtype)
return rgb @ coeffs
def gray2rgba(image, alpha=None, *, channel_axis=-1):
"""Create a RGBA representation of a gray-level image.
Parameters
----------
image : array_like
Input image.
alpha : array_like, optional
Alpha channel of the output image. It may be a scalar or an
array that can be broadcast to ``image``. If not specified it is
set to the maximum limit corresponding to the ``image`` dtype.
channel_axis : int, optional
This parameter indicates which axis of the output array will correspond
to channels.