-
Notifications
You must be signed in to change notification settings - Fork 17
/
image.py
1165 lines (955 loc) · 41.8 KB
/
image.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2017
# Author(s):
# Martin Raspaud <martin.raspaud@smhi.se>
# Adam Dybbroe <adam.dybbroe@smhi.se>
# Esben S. Nielsen <esn@dmi.dk>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""This module defines the image class. It overlaps largely the PIL library,
but has the advantage of using masked arrays as pixel arrays, so that data
arrays containing invalid values may be properly handled.
"""
import logging
import os
import re
from copy import deepcopy
import numpy as np
from PIL import Image as Pil
try:
import numexpr as ne
except ImportError:
ne = None
logger = logging.getLogger(__name__)
PIL_IMAGE_FORMATS = Pil.registered_extensions()
def _pprint_pil_formats():
res = ''
row = []
for i in PIL_IMAGE_FORMATS:
if len(row) > 12:
res = res + ", ".join(row) + ",\n"
row = []
row.append(i)
return res + ", ".join(row)
PIL_IMAGE_FORMATS_STR = _pprint_pil_formats()
def ensure_dir(filename):
"""Checks if the dir of f exists, otherwise create it.
"""
directory = os.path.dirname(filename)
if len(directory) and not os.path.isdir(directory):
os.makedirs(directory)
class UnknownImageFormat(Exception):
"""Exception to be raised when image format is unknown to pytroll-image"""
pass
def check_image_format(fformat):
"""Check that *fformat* is valid.
Valid formats are listed in https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
"""
fformat = fformat.lower()
try:
fformat = PIL_IMAGE_FORMATS["." + fformat]
except KeyError:
raise UnknownImageFormat(
"Unknown image format '%s'. Supported formats for 'simple_image' writer are:\n%s" %
(fformat, PIL_IMAGE_FORMATS_STR))
return fformat
class Image(object):
"""This class defines images. As such, it contains data of the different
*channels* of the image (red, green, and blue for example). The *mode*
tells if the channels define a black and white image ("L"), an rgb image
("RGB"), an YCbCr image ("YCbCr"), or an indexed image ("P"), in which case
a *palette* is needed. Each mode has also a corresponding alpha mode, which
is the mode with an "A" in the end: for example "RGBA" is rgb with an alpha
channel. *fill_value* sets how the image is filled where data is missing,
since channels are numpy masked arrays. Setting it to (0,0,0) in RGB mode
for example will produce black where data is missing."None" (default) will
produce transparency (thus adding an alpha channel) if the file format
allows it, black otherwise.
The channels are considered to contain floating point values in the range
[0.0,1.0]. In order to normalize the input data, the *color_range*
parameter defines the original range of the data. The conversion to the
classical [0,255] range and byte type is done automagically when saving the
image to file.
"""
modes = ["L", "LA", "RGB", "RGBA", "YCbCr", "YCbCrA", "P", "PA"]
def __init__(self, channels=None, mode="L", color_range=None,
fill_value=None, palette=None, copy=True):
self.channels = None
self.mode = None
self.width = 0
self.height = 0
self.fill_value = None
self.palette = None
self.shape = None
self.info = {}
self._secondary_mode = "RGB"
if(channels is not None and
not isinstance(channels, (tuple, set, list,
np.ndarray, np.ma.core.MaskedArray))):
raise TypeError("Image channels should a tuple, set, list, numpy "
"array, or masked array.")
if(isinstance(channels, (tuple, list)) and
len(channels) != len(re.findall("[A-Z]", mode))):
errmsg = ("Number of channels (" +
"{n}) does not match mode {mode}.".format(
n=len(channels), mode=mode))
raise ValueError(errmsg)
if copy and channels is not None:
channels = deepcopy(channels)
if mode not in self.modes:
raise ValueError("Unknown mode.")
if(color_range is not None and
not _is_pair(color_range) and
not _is_list_of_pairs(color_range)):
raise ValueError("Color_range should be a pair"
" or a list/tuple/set of pairs.")
if(color_range is not None and
_is_list_of_pairs(color_range) and
(channels is None or
len(color_range) != len(channels))):
raise ValueError("Color_range length does not match number of "
"channels.")
if(color_range is not None and
(((mode == "L" or mode == "P") and not _is_pair(color_range)) and
(len(color_range) != len(re.findall("[A-Z]", mode))))):
raise ValueError("Color_range does not match mode")
self.mode = mode
if isinstance(fill_value, (tuple, list, set)):
self.fill_value = list(fill_value)
elif fill_value is not None:
self.fill_value = [fill_value]
else:
self.fill_value = None
self.channels = []
self.palette = palette
if isinstance(channels, (tuple, list)):
if _areinstances(channels, (np.ma.core.MaskedArray, np.ndarray,
list, tuple)):
for i, chn in enumerate(channels):
if color_range is not None:
color_min = color_range[i][0]
color_max = color_range[i][1]
# Add data to image object as a channel
# self._add_channel(chn, color_min, color_max)
else:
color_min = 0.0
color_max = 1.0
# self.channels.append(np.ma.array(chn))
# Add data to image object as a channel
self._add_channel(chn, color_min, color_max)
self.shape = self.channels[-1].shape
if self.shape != self.channels[0].shape:
raise ValueError("Image channels must have the same"
" shape.")
self.height = self.shape[0]
try:
self.width = self.shape[1]
except IndexError:
self.width = 0
else:
raise ValueError("Image channels must all be arrays tuples.")
elif channels is not None:
self.height = channels.shape[0]
self.width = channels.shape[1]
self.shape = channels.shape
if color_range is not None:
color_min = color_range[0]
color_max = color_range[1]
else:
color_min = 0.0
color_max = 1.0
# Add data to image object as a channel
self._add_channel(channels, color_min, color_max)
else:
self.shape = (0, 0)
self.width = 0
self.height = 0
def _add_channel(self, chn, color_min, color_max):
"""Adds a channel to the image object
"""
if isinstance(chn, np.ma.core.MaskedArray):
chn_data = chn.data
chn_mask = chn.mask
else:
chn_data = np.array(chn)
chn_mask = False
scaled = ((chn_data - color_min) *
1.0 / (color_max - color_min))
self.channels.append(np.ma.array(scaled, mask=chn_mask))
def _finalize(self, dtype=np.uint8):
"""Finalize the image, that is put it in RGB mode, and set the channels
in unsigned 8bit format ([0,255] range) (if the *dtype* doesn't say
otherwise).
"""
channels = []
if self.mode == "P":
self.convert("RGB")
if self.mode == "PA":
self.convert("RGBA")
for chn in self.channels:
if isinstance(chn, np.ma.core.MaskedArray):
final_data = chn.data.clip(0, 1) * np.iinfo(dtype).max
else:
final_data = chn.clip(0, 1) * np.iinfo(dtype).max
if np.issubdtype(dtype, np.integer):
final_data = np.round(final_data)
channels.append(np.ma.array(final_data,
dtype,
mask=np.ma.getmaskarray(chn)))
if self.fill_value is not None:
fill_value = [int(col * np.iinfo(dtype).max)
for col in self.fill_value]
else:
fill_value = None
return channels, fill_value
def is_empty(self):
"""Checks for an empty image.
"""
if(((self.channels == []) and (not self.shape == (0, 0))) or
((not self.channels == []) and (self.shape == (0, 0)))):
raise RuntimeError("Channels-shape mismatch.")
return self.channels == [] and self.shape == (0, 0)
def show(self):
"""Display the image on screen.
"""
self.pil_image().show()
def pil_image(self):
"""Return a PIL image from the current image.
"""
channels, fill_value = self._finalize()
if self.is_empty():
return Pil.new(self.mode, (0, 0))
if self.mode == "L":
if fill_value is not None:
img = Pil.fromarray(channels[0].filled(fill_value))
else:
img = Pil.fromarray(channels[0].filled(0))
alpha = np.zeros(channels[0].shape, np.uint8)
mask = np.ma.getmaskarray(channels[0])
alpha = np.where(mask, alpha, 255)
pil_alpha = Pil.fromarray(alpha)
img = Pil.merge("LA", (img, pil_alpha))
elif self.mode == "LA":
if fill_value is not None:
img = Pil.fromarray(channels[0].filled(fill_value))
pil_alpha = Pil.fromarray(channels[1])
else:
img = Pil.fromarray(channels[0].filled(0))
alpha = np.zeros(channels[0].shape, np.uint8)
mask = np.ma.getmaskarray(channels[0])
alpha = np.where(mask, alpha, channels[1])
pil_alpha = Pil.fromarray(alpha)
img = Pil.merge("LA", (img, pil_alpha))
elif self.mode == "RGB":
# Mask where all channels have missing data (incomplete data will
# be shown).
mask = (np.ma.getmaskarray(channels[0]) &
np.ma.getmaskarray(channels[1]) &
np.ma.getmaskarray(channels[2]))
if fill_value is not None:
pil_r = Pil.fromarray(channels[0].filled(fill_value[0]))
pil_g = Pil.fromarray(channels[1].filled(fill_value[1]))
pil_b = Pil.fromarray(channels[2].filled(fill_value[2]))
img = Pil.merge("RGB", (pil_r, pil_g, pil_b))
else:
pil_r = Pil.fromarray(channels[0].filled(0))
pil_g = Pil.fromarray(channels[1].filled(0))
pil_b = Pil.fromarray(channels[2].filled(0))
alpha = np.zeros(channels[0].shape, np.uint8)
alpha = np.where(mask, alpha, 255)
pil_a = Pil.fromarray(alpha)
img = Pil.merge("RGBA", (pil_r, pil_g, pil_b, pil_a))
elif self.mode == "RGBA":
# Mask where all channels have missing data (incomplete data will
# be shown).
mask = (np.ma.getmaskarray(channels[0]) &
np.ma.getmaskarray(channels[1]) &
np.ma.getmaskarray(channels[2]) &
np.ma.getmaskarray(channels[3]))
if fill_value is not None:
pil_r = Pil.fromarray(channels[0].filled(fill_value[0]))
pil_g = Pil.fromarray(channels[1].filled(fill_value[1]))
pil_b = Pil.fromarray(channels[2].filled(fill_value[2]))
pil_a = Pil.fromarray(channels[3].filled(fill_value[3]))
img = Pil.merge("RGBA", (pil_r, pil_g, pil_b, pil_a))
else:
pil_r = Pil.fromarray(channels[0].filled(0))
pil_g = Pil.fromarray(channels[1].filled(0))
pil_b = Pil.fromarray(channels[2].filled(0))
alpha = np.where(mask, 0, channels[3])
pil_a = Pil.fromarray(alpha)
img = Pil.merge("RGBA", (pil_r, pil_g, pil_b, pil_a))
else:
raise TypeError("Does not know how to use mode %s." % (self.mode))
return img
def save(self, filename, compression=6, fformat=None,
thumbnail_name=None, thumbnail_size=None):
"""Save the image to the given *filename*. For some formats like jpg
and png, the work is delegated to :meth:`pil_save`, which doesn't
support the *compression* option.
"""
self.pil_save(filename, compression, fformat,
thumbnail_name, thumbnail_size)
def pil_save(self, filename, compression=6, fformat=None,
thumbnail_name=None, thumbnail_size=None):
"""Save the image to the given *filename* using PIL.
For now, the compression level [0-9] is ignored, due to PIL's lack of support.
See also :meth:`save`.
Supported image formats are listed in https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html
"""
# PIL does not support compression option.
del compression
if self.is_empty():
raise IOError("Cannot save an empty image")
if isinstance(filename, str):
ensure_dir(filename)
fformat = fformat or os.path.splitext(filename)[1][1:4]
fformat = check_image_format(fformat)
params = {}
if fformat == 'PNG':
# Take care of GeoImage.tags (if any).
params['pnginfo'] = self._pngmeta()
# JPEG images does not support transparency
if fformat == 'JPEG' and not self.fill_value:
self.fill_value = [0, 0, 0, 0]
logger.debug("No fill_value provided, setting it to 0.")
img = self.pil_image()
img.save(filename, fformat, **params)
if thumbnail_name is not None and thumbnail_size is not None:
img.thumbnail(thumbnail_size, Pil.ANTIALIAS)
img.save(thumbnail_name, fformat, **params)
def _pngmeta(self):
"""It will return GeoImage.tags as a PNG metadata object.
Inspired by:
public domain, Nick Galbreath
http://blog.modp.com/2007/08/python-pil-and-png-metadata-take-2.html
"""
reserved = ('interlace', 'gamma', 'dpi', 'transparency', 'aspect')
try:
tags = self.tags
except AttributeError:
tags = {}
# Undocumented class
from PIL import PngImagePlugin
meta = PngImagePlugin.PngInfo()
# Copy from tags to new dict
for k__, v__ in tags.items():
if k__ not in reserved:
meta.add_text(k__, v__, 0)
return meta
def putalpha(self, alpha):
"""Adds an *alpha* channel to the current image, or replaces it with
*alpha* if it already exists.
"""
alpha = np.ma.array(alpha)
if(not (alpha.shape[0] == 0 and
self.shape[0] == 0) and
alpha.shape != self.shape):
raise ValueError("Alpha channel shape should match image shape")
if not self.mode.endswith("A"):
self.convert(self.mode + "A")
if not self.is_empty():
self.channels[-1] = alpha
def _rgb2ycbcr(self, mode):
"""Convert the image from RGB mode to YCbCr."""
self._check_modes(("RGB", "RGBA"))
(self.channels[0], self.channels[1], self.channels[2]) = \
rgb2ycbcr(self.channels[0],
self.channels[1],
self.channels[2])
if self.fill_value is not None:
self.fill_value[0:3] = rgb2ycbcr(self.fill_value[0],
self.fill_value[1],
self.fill_value[2])
self.mode = mode
def _ycbcr2rgb(self, mode):
"""Convert the image from YCbCr mode to RGB.
"""
self._check_modes(("YCbCr", "YCbCrA"))
(self.channels[0], self.channels[1], self.channels[2]) = \
ycbcr2rgb(self.channels[0],
self.channels[1],
self.channels[2])
if self.fill_value is not None:
self.fill_value[0:3] = ycbcr2rgb(self.fill_value[0],
self.fill_value[1],
self.fill_value[2])
self.mode = mode
def _to_p(self, mode):
"""Convert the image to P or PA mode.
"""
if self.mode.endswith("A"):
chans = self.channels[:-1]
alpha = self.channels[-1]
self._secondary_mode = self.mode[:-1]
else:
chans = self.channels
alpha = None
self._secondary_mode = self.mode
palette = []
selfmask = chans[0].mask
for chn in chans[1:]:
selfmask = np.ma.mask_or(selfmask, chn.mask)
new_chn = np.ma.zeros(self.shape, dtype=int)
color_nb = 0
for i in range(self.height):
for j in range(self.width):
current_col = tuple([chn[i, j] for chn in chans])
try:
next(idx
for idx in range(len(palette))
if palette[idx] == current_col)
except StopIteration:
idx = color_nb
palette.append(current_col)
color_nb = color_nb + 1
new_chn[i, j] = idx
if self.fill_value is not None:
if self.mode.endswith("A"):
current_col = tuple(self.fill_value[:-1])
fill_alpha = [self.fill_value[-1]]
else:
current_col = tuple(self.fill_value)
fill_alpha = []
try:
next(idx
for idx in range(len(palette))
if palette[idx] == current_col)
except StopIteration:
idx = color_nb
palette.append(current_col)
color_nb = color_nb + 1
self.fill_value = [idx] + fill_alpha
new_chn.mask = selfmask
self.palette = palette
if alpha is None:
self.channels = [new_chn]
else:
self.channels = [new_chn, alpha]
self.mode = mode
def _from_p(self, mode):
"""Convert the image from P or PA mode.
"""
self._check_modes(("P", "PA"))
if self.mode.endswith("A"):
alpha = self.channels[-1]
else:
alpha = None
chans = []
cdfs = []
color_chan = self.channels[0]
for i in range(len(self.palette[0])):
cdfs.append(np.zeros(len(self.palette)))
for j in range(len(self.palette)):
cdfs[i][j] = self.palette[j][i]
new_chn = np.ma.array(np.interp(color_chan,
np.arange(len(self.palette)),
cdfs[i]),
mask=color_chan.mask)
chans.append(new_chn)
if self.fill_value is not None:
if alpha is not None:
fill_alpha = self.fill_value[-1]
self.fill_value = list(self.palette[int(self.fill_value[0])])
self.fill_value += [fill_alpha]
else:
self.fill_value = list(self.palette[int(self.fill_value[0])])
self.mode = self._secondary_mode
self.channels = chans
if alpha is not None:
self.channels.append(alpha)
self.mode = self.mode + "A"
self.convert(mode)
def _check_modes(self, modes):
"""Check that the image is in on of the given *modes*, raise an
exception otherwise.
"""
if not isinstance(modes, (tuple, list, set)):
modes = [modes]
if self.mode not in modes:
raise ValueError("Image not in suitable mode: %s" % modes)
def _l2rgb(self, mode):
"""Convert from L (black and white) to RGB.
"""
self._check_modes(("L", "LA"))
self.channels.append(self.channels[0].copy())
self.channels.append(self.channels[0].copy())
if self.fill_value is not None:
self.fill_value = self.fill_value[:1] * 3 + self.fill_value[1:]
if self.mode == "LA":
self.channels[1], self.channels[3] = \
self.channels[3], self.channels[1]
self.mode = mode
def _rgb2l(self, mode):
"""Convert from RGB to monochrome L.
"""
self._check_modes(("RGB", "RGBA"))
kb_ = 0.114
kr_ = 0.299
r__ = self.channels[0]
g__ = self.channels[1]
b__ = self.channels[2]
y__ = kr_ * r__ + (1 - kr_ - kb_) * g__ + kb_ * b__
if self.fill_value is not None:
self.fill_value = ([rgb2ycbcr(self.fill_value[0],
self.fill_value[1],
self.fill_value[2])[0]] +
self.fill_value[3:])
self.channels = [y__] + self.channels[3:]
self.mode = mode
def _ycbcr2l(self, mode):
"""Convert from YCbCr to L.
"""
self._check_modes(("YCbCr", "YCbCrA"))
self.channels = [self.channels[0]] + self.channels[3:]
if self.fill_value is not None:
self.fill_value = [self.fill_value[0]] + self.fill_value[3:]
self.mode = mode
def _l2ycbcr(self, mode):
"""Convert from L to YCbCr.
"""
self._check_modes(("L", "LA"))
luma = self.channels[0]
zeros = np.ma.zeros(luma.shape)
zeros.mask = luma.mask
self.channels = [luma, zeros, zeros] + self.channels[1:]
if self.fill_value is not None:
self.fill_value = [self.fill_value[0], 0, 0] + self.fill_value[1:]
self.mode = mode
def convert(self, mode):
"""Convert the current image to the given *mode*. See :class:`Image`
for a list of available modes.
"""
if mode == self.mode:
return
if mode not in ["L", "LA", "RGB", "RGBA",
"YCbCr", "YCbCrA", "P", "PA"]:
raise ValueError("Mode %s not recognized." % (mode))
if self.is_empty():
self.mode = mode
return
if mode == self.mode + "A":
self.channels.append(np.ma.ones(self.channels[0].shape))
if self.fill_value is not None:
self.fill_value += [1]
self.mode = mode
elif mode + "A" == self.mode:
self.channels = self.channels[:-1]
if self.fill_value is not None:
self.fill_value = self.fill_value[:-1]
self.mode = mode
elif mode.endswith("A") and not self.mode.endswith("A"):
self.convert(self.mode + "A")
self.convert(mode)
elif self.mode.endswith("A") and not mode.endswith("A"):
self.convert(self.mode[:-1])
self.convert(mode)
else:
cases = {
"RGB": {"YCbCr": self._rgb2ycbcr,
"L": self._rgb2l,
"P": self._to_p},
"RGBA": {"YCbCrA": self._rgb2ycbcr,
"LA": self._rgb2l,
"PA": self._to_p},
"YCbCr": {"RGB": self._ycbcr2rgb,
"L": self._ycbcr2l,
"P": self._to_p},
"YCbCrA": {"RGBA": self._ycbcr2rgb,
"LA": self._ycbcr2l,
"PA": self._to_p},
"L": {"RGB": self._l2rgb,
"YCbCr": self._l2ycbcr,
"P": self._to_p},
"LA": {"RGBA": self._l2rgb,
"YCbCrA": self._l2ycbcr,
"PA": self._to_p},
"P": {"RGB": self._from_p,
"YCbCr": self._from_p,
"L": self._from_p},
"PA": {"RGBA": self._from_p,
"YCbCrA": self._from_p,
"LA": self._from_p}}
try:
cases[self.mode][mode](mode)
except KeyError:
raise ValueError("Conversion from %s to %s not implemented !"
% (self.mode, mode))
def clip(self, channels=True):
"""Limit the values of the array to the default [0,1] range. *channels*
says which channels should be clipped."""
if not isinstance(channels, (tuple, list)):
channels = [channels] * len(self.channels)
for i in range(len(self.channels)):
if channels[i]:
self.channels[i] = np.ma.clip(self.channels[i], 0.0, 1.0)
def resize(self, shape):
"""Resize the image to the given *shape* tuple, in place. For zooming,
nearest neighbour method is used, while for shrinking, decimation is
used. Therefore, *shape* must be a multiple or a divisor of the image
shape.
"""
if self.is_empty():
raise ValueError("Cannot resize an empty image")
factor = [1, 1]
zoom = [True, True]
zoom[0] = shape[0] >= self.height
zoom[1] = shape[1] >= self.width
if zoom[0]:
factor[0] = shape[0] * 1.0 / self.height
else:
factor[0] = self.height * 1.0 / shape[0]
if zoom[1]:
factor[1] = shape[1] * 1.0 / self.width
else:
factor[1] = self.width * 1.0 / shape[1]
if(int(factor[0]) != factor[0] or
int(factor[1]) != factor[1]):
raise ValueError("Resize not of integer factor!")
factor[0] = int(factor[0])
factor[1] = int(factor[1])
i = 0
for chn in self.channels:
if zoom[0]:
chn = chn.repeat([factor[0]] * chn.shape[0], axis=0)
else:
chn = chn[[idx * factor[0]
for idx in range(int(self.height / factor[0]))],
:]
if zoom[1]:
self.channels[i] = chn.repeat([factor[1]] * chn.shape[1],
axis=1)
else:
self.channels[i] = chn[:,
[idx * factor[1]
for idx in range(int(self.width /
factor[1]))]]
i = i + 1
self.height = self.channels[0].shape[0]
self.width = self.channels[0].shape[1]
self.shape = self.channels[0].shape
def replace_luminance(self, luminance):
"""Replace the Y channel of the image by the array *luminance*. If the
image is not in YCbCr mode, it is converted automatically to and
from that mode.
"""
if self.is_empty():
return
if luminance.shape != self.channels[0].shape:
if ((luminance.shape[0] * 1.0 / luminance.shape[1]) ==
(self.channels[0].shape[0] * 1.0 / self.channels[0].shape[1])):
if luminance.shape[0] > self.channels[0].shape[0]:
self.resize(luminance.shape)
else:
raise NameError("Luminance smaller than the image !")
else:
raise NameError("Not the good shape !")
mode = self.mode
if mode.endswith("A"):
self.convert("YCbCrA")
self.channels[0] = luminance
self.convert(mode)
else:
self.convert("YCbCr")
self.channels[0] = luminance
self.convert(mode)
def enhance(self, inverse=False, gamma=1.0, stretch="no",
stretch_parameters=None, **kwargs):
"""Image enhancement function. It applies **in this order** inversion,
gamma correction, and stretching to the current image, with parameters
*inverse* (see :meth:`Image.invert`), *gamma* (see
:meth:`Image.gamma`), and *stretch* (see :meth:`Image.stretch`).
"""
self.invert(inverse)
if stretch_parameters is None:
stretch_parameters = {}
stretch_parameters.update(kwargs)
self.stretch(stretch, **stretch_parameters)
self.gamma(gamma)
def gamma(self, gamma=1.0):
"""Apply gamma correction to the channels of the image. If *gamma* is a
tuple, then it should have as many elements as the channels of the
image, and the gamma correction is applied elementwise. If *gamma* is a
number, the same gamma correction is applied on every channel, if there
are several channels in the image. The behaviour of :func:`gamma` is
undefined outside the normal [0,1] range of the channels.
"""
if(isinstance(gamma, (list, tuple, set)) and
len(gamma) != len(self.channels)):
raise ValueError("Number of channels and gamma components differ.")
if isinstance(gamma, (tuple, list)):
gamma_list = list(gamma)
else:
gamma_list = [gamma] * len(self.channels)
for i in range(len(self.channels)):
gamma = float(gamma_list[i])
if gamma < 0:
raise ValueError("Gamma correction must be a positive number.")
logger.debug("Applying gamma %f", gamma)
if gamma == 1.0:
continue
if isinstance(self.channels[i], np.ma.core.MaskedArray):
if ne:
self.channels[i] = np.ma.array(
ne.evaluate("data ** (1.0 / gamma)",
local_dict={"data": self.channels[i].data,
'gamma': gamma}),
mask=self.channels[i].mask,
copy=False)
else:
self.channels[i] = np.ma.array(self.channels[i].data **
(1.0 / gamma),
mask=self.channels[i].mask,
copy=False)
else:
self.channels[i] = np.where(self.channels[i] >= 0,
self.channels[i] **
(1.0 / gamma),
self.channels[i])
def stretch(self, stretch="crude", **kwargs):
"""Apply stretching to the current image. The value of *stretch* sets
the type of stretching applied. The values "histogram", "linear",
"crude" (or "crude-stretch") perform respectively histogram
equalization, contrast stretching (with 5% cutoff on both sides), and
contrast stretching without cutoff. The value "logarithmic" or "log"
will do a logarithmic enhancement towards white. If a tuple or a list
of two values is given as input, then a contrast stretching is performed
with the values as cutoff. These values should be normalized in the
range [0.0,1.0].
"""
logger.debug("Applying stretch %s with parameters %s",
stretch, str(kwargs))
ch_len = len(self.channels)
if self.mode.endswith("A"):
ch_len -= 1
if((isinstance(stretch, tuple) or
isinstance(stretch, list))):
if len(stretch) == 2:
for i in range(ch_len):
self.stretch_linear(i, cutoffs=stretch, **kwargs)
else:
raise ValueError(
"Stretch tuple must have exactly two elements")
elif stretch == "linear":
for i in range(ch_len):
self.stretch_linear(i, **kwargs)
elif stretch == "histogram":
for i in range(ch_len):
self.stretch_hist_equalize(i, **kwargs)
elif stretch in ["crude", "crude-stretch"]:
for i in range(ch_len):
self.crude_stretch(i, **kwargs)
elif stretch in ["log", "logarithmic"]:
for i in range(ch_len):
self.stretch_logarithmic(i, **kwargs)
elif stretch == "no":
return
elif isinstance(stretch, str):
raise ValueError("Stretching method %s not recognized." % stretch)
else:
raise TypeError("Stretch parameter must be a string or a tuple.")
def invert(self, invert=True):
"""Inverts all the channels of a image according to *invert*. If invert is a tuple or a list, elementwise
invertion is performed, otherwise all channels are inverted if *invert* is true (default).
Note: 'Inverting' means that black becomes white, and vice-versa, not that the values are negated !
"""
if(isinstance(invert, (tuple, list)) and
len(self.channels) != len(invert)):
raise ValueError(
"Number of channels and invert components differ.")
logger.debug("Applying invert with parameters %s", str(invert))
if isinstance(invert, (tuple, list)):
for i, chn in enumerate(self.channels):
if invert[i]:
self.channels[i] = 1 - chn
elif invert:
for i, chn in enumerate(self.channels):
self.channels[i] = 1 - chn
def stretch_hist_equalize(self, ch_nb):
"""Stretch the current image's colors by performing histogram
equalization on channel *ch_nb*.
"""
logger.info("Perform a histogram equalized contrast stretch.")
if(self.channels[ch_nb].size ==
np.ma.count_masked(self.channels[ch_nb])):
logger.warning("Nothing to stretch !")
return
arr = self.channels[ch_nb]
nwidth = 2048.0
carr = arr.compressed()
cdf = np.arange(0.0, 1.0, 1 / nwidth)
logger.debug("Make histogram bins having equal amount of data, " +
"using numpy percentile function:")
bins = np.percentile(carr, list(cdf * 100))
res = np.ma.empty_like(arr)
res.mask = np.ma.getmaskarray(arr)
res[~res.mask] = np.interp(carr, bins, cdf)
self.channels[ch_nb] = res
def stretch_logarithmic(self, ch_nb, factor=100.):
"""Move data into range [1:factor] and do a normalized logarithmic
enhancement.
"""
logger.debug("Perform a logarithmic contrast stretch.")
if ((self.channels[ch_nb].size ==
np.ma.count_masked(self.channels[ch_nb])) or
(self.channels[ch_nb].min() == self.channels[ch_nb].max())):
logger.warning("Nothing to stretch !")
return
crange = (0., 1.0)
arr = self.channels[ch_nb]
b__ = float(crange[1] - crange[0]) / np.log(factor)
c__ = float(crange[0])
slope = (factor - 1.) / float(arr.max() - arr.min())
arr = 1. + (arr - arr.min()) * slope
arr = c__ + b__ * np.log(arr)
self.channels[ch_nb] = arr
def stretch_linear(self, ch_nb, cutoffs=(0.005, 0.005)):
"""Stretch linearly the contrast of the current image on channel
*ch_nb*, using *cutoffs* for left and right trimming.
"""
logger.debug("Perform a linear contrast stretch.")
if((self.channels[ch_nb].size ==
np.ma.count_masked(self.channels[ch_nb])) or
self.channels[ch_nb].min() == self.channels[ch_nb].max()):
logger.warning("Nothing to stretch !")
return