-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathnumpngw.py
1541 lines (1289 loc) · 58.9 KB
/
numpngw.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
"""
The numpngw module defines two functions and a class:
* write_png(...) writes a numpy array to a PNG file.
* write_apng(...) writes a sequence of arrays to an animated PNG file.
* AnimatedPNGWriter is a class that can be used with Matplotlib animations.
-----
Copyright (c) 2015-2024, Warren Weckesser
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
import sys as _sys
import contextlib as _contextlib
from io import BytesIO as _BytesIO
import time as _time
import struct as _struct
import zlib as _zlib
from fractions import Fraction as _Fraction
import operator
import numpy as _np
__all__ = ['write_png', 'write_apng', 'AnimatedPNGWriter']
__version__ = "0.1.5dev0"
_PY3 = _sys.version_info > (3,)
if _PY3:
def _bord(c):
return c
else:
_bord = ord
def _software_text():
software = ("numpngw (version %s), "
"https://github.com/WarrenWeckesser/numpngw" % __version__)
return software
def _filter0(row, prev_row):
return row
def _filter0inv(frow, prev_row):
return frow
def _filter1(row, prev_row):
d = _np.zeros_like(row)
d[1:] = _np.diff(row, axis=0)
d[0] = row[0]
return d
def _filter1inv(frow, prev_row):
return frow.cumsum(axis=0, dtype=_np.uint64).astype(_np.uint8)
def _filter2(row, prev_row):
d = row - prev_row
return d
def _filter2inv(frow, prev_row):
return frow + prev_row
def _filter3(row, prev_row):
a = _np.zeros_like(row, dtype=_np.int64)
a[1:] = row[:-1]
c = ((a + prev_row) // 2).astype(row.dtype)
d = row - c
return d
def _filter3inv(frow, prev_row):
# Slow python loop, but currently this is only used for testing.
row = _np.empty_like(frow)
for k in range(len(frow)):
if k == 0:
row[k] = frow[k] + (prev_row[k] // 2)
else:
row[k] = frow[k] + (row[k-1].astype(int) +
prev_row[k].astype(int)) // 2
return row
def _filter4(row, prev_row):
"""Paeth filter."""
# Create a, b and c.
a = _np.zeros_like(row, dtype=_np.int64)
a[1:] = row[:-1]
b = prev_row.astype(_np.int64)
c = _np.zeros_like(b)
c[1:] = b[:-1]
p = a + b - c
pa = _np.abs(p - a)
pb = _np.abs(p - b)
pc = _np.abs(p - c)
y = _np.where((pa <= pb) & (pa <= pc), a, _np.where(pb <= pc, b, c))
pr = y.astype(_np.uint8)
d = row - pr
return d
def _filter4inv(frow, prev_row):
# Slow python loop, but currently this is only used for testing.
row = _np.empty_like(frow)
for k in range(len(frow)):
if k == 0:
ra = _np.zeros_like(frow[k])
rc = _np.zeros_like(frow[k])
else:
ra = row[k-1].astype(int)
rc = prev_row[k-1].astype(int)
rb = prev_row[k].astype(int)
p = ra + rb - rc
pa = _np.abs(p - ra)
pb = _np.abs(p - rb)
pc = _np.abs(p - rc)
y = _np.where((pa <= pb) & (pa <= pc), ra, _np.where(pb <= pc, rb, rc))
row[k] = frow[k] + y
return row
def _interlace_passes(img):
"""
Return the subimages of img that make up the seven Adam7 interlace passes.
"""
pass1 = img[::8, ::8]
pass2 = img[::8, 4::8]
pass3 = img[4::8, ::4]
pass4 = img[::4, 2::4]
pass5 = img[2::4, ::2]
pass6 = img[::2, 1::2]
pass7 = img[1::2, :]
return (pass1, pass2, pass3, pass4, pass5, pass6, pass7)
def _create_stream(a, filter_type=None):
"""
Convert the data in `a` into a python string.
`a` is must to be a 2D or 3D array of unsigned 8- or 16-bit
integers.
The string is formatted as the "scan lines" of the array.
"""
filters = [_filter0, _filter1, _filter2, _filter3, _filter4]
if filter_type is None:
filter_type = "heuristic"
allowed_filter_types = [0, 1, 2, 3, 4, "heuristic"]
if filter_type not in allowed_filter_types:
raise ValueError('filter_type must be one of %r' %
(allowed_filter_types,))
if a.ndim == 2:
# Gray scale. Add a trivial third dimension.
a = a[:, :, _np.newaxis]
lines = []
prev_row = _np.zeros_like(a[0]).view(_np.uint8)
for row in a:
# Convert the row to big-endian (i.e. network byte order).
row_be = row.astype('>' + row.dtype.str[1:]).view(_np.uint8)
if filter_type == "heuristic":
filtered_rows = [filt(row_be, prev_row) for filt in filters]
lst = [_np.abs(fr.view(_np.int8).astype(_np.int_)).sum()
for fr in filtered_rows]
values = _np.array(lst)
ftype = values.argmin()
# Create the string, with the filter type prepended.
lines.append(chr(ftype).encode('ascii') +
filtered_rows[ftype].tobytes())
else:
filtered_row = filters[filter_type](row_be, prev_row)
lines.append(chr(filter_type).encode('ascii') +
filtered_row.tobytes())
prev_row = row_be
stream = b''.join(lines)
return stream
def _write_chunk(f, chunk_type, chunk_data):
"""
Write a chunk to the file `f`. This function wraps the chunk_type and
chunk_data with the length and CRC field, and writes the result to `f`.
"""
content = chunk_type + chunk_data
length = _struct.pack("!I", len(chunk_data))
crc = _struct.pack("!I", _zlib.crc32(content) & 0xFFFFFFFF)
f.write(length + content + crc)
def _write_ihdr(f, width, height, nbits, color_type, interlace):
"""Write an IHDR chunk to `f`."""
fmt = "!IIBBBBB"
chunk_data = _struct.pack(fmt, width, height, nbits, color_type, 0, 0,
interlace)
_write_chunk(f, b"IHDR", chunk_data)
def _write_text(f, keyword, text_string):
"""Write a tEXt chunk to `f`.
keyword and test_string are expected to be bytes (not unicode).
They must already be validated.
"""
data = keyword + b'\0' + text_string
_write_chunk(f, b'tEXt', data)
def _write_time(f, timestamp):
"""Write a tIME chunk to `f`."""
chunk_data = _struct.pack('!HBBBBB', *timestamp)
_write_chunk(f, b'tIME', chunk_data)
def _write_sbit(f, sbit):
"""Write an sBIT chunk to `f`."""
chunk_data = _struct.pack('BBBB'[:len(sbit)], *sbit)
_write_chunk(f, b'sBIT', chunk_data)
def _write_gama(f, gamma):
"""Write a gAMA chunk to `f`."""
gama = int(gamma*100000 + 0.5)
chunk_data = _struct.pack('!I', gama)
_write_chunk(f, b'gAMA', chunk_data)
def _write_plte(f, palette):
_write_chunk(f, b"PLTE", palette.tobytes())
def _write_trns(f, trans):
trans_be = trans.astype('>' + trans.dtype.str[1:])
_write_chunk(f, b"tRNS", trans_be.tobytes())
def _write_bkgd(f, color, color_type):
"""
Write bKGD chunk to `f`.
* If `color_type` is 0 or 4, `color` must be an integer.
* If `color_type` is 2 or 6, `color` must be a sequence of three
integers (RGB values).
* If `color_type` is 3, `color` must be an integer that is less than
the number of colors in the palette.
"""
if color_type == 0 or color_type == 4:
chunk_data = _struct.pack("!H", color)
elif color_type == 2 or color_type == 6:
chunk_data = _struct.pack("!HHH", *color)
elif color_type == 3:
chunk_data = _struct.pack("B", color)
else:
raise ValueError("invalid chunk_type %r" % (color_type,))
_write_chunk(f, b"bKGD", chunk_data)
def _write_phys(f, phys):
"""Write a pHYs chunk to `f`."""
chunk_data = _struct.pack("!IIB", *phys)
_write_chunk(f, b"pHYs", chunk_data)
def _write_iccp(f, iccp):
"""Write a iCCP chunk to `f`."""
_validate_iccp(iccp)
profile_name = _encode_latin1(iccp[0])
compressed_profile = _zlib.compress(iccp[1])
chunk_data = profile_name + b'\0\0' + compressed_profile
_write_chunk(f, b"iCCP", chunk_data)
def _write_chrm(f, chromaticity):
"""Write a cHRM chunk to `f`."""
data = (100000 * _np.array(chromaticity) + 0.5).astype(_np.uint32)
chunk_data = _struct.pack('!IIIIIIII', *data.ravel())
_write_chunk(f, b'cHRM', chunk_data)
def _write_idat(f, data):
"""Write an IDAT chunk to `f`."""
_write_chunk(f, b"IDAT", data)
def _write_iend(f):
"""Write an IEND chunk to `f`."""
_write_chunk(f, b"IEND", b"")
def _write_actl(f, num_frames, num_plays):
"""Write an acTL chunk to `f`."""
if num_frames < 1:
raise ValueError("Attempt to create acTL chunk with num_frames (%i) "
"less than 1." % (num_frames,))
chunk_data = _struct.pack("!II", num_frames, num_plays)
_write_chunk(f, b"acTL", chunk_data)
def _write_fctl(f, sequence_number, width, height, x_offset, y_offset,
delay_num, delay_den, dispose_op=0, blend_op=0):
"""Write an fcTL chunk to `f`."""
if width < 1:
raise ValueError("width must be greater than 0")
if height < 1:
raise ValueError("heigt must be greater than 0")
if x_offset < 0:
raise ValueError("x_offset must be nonnegative")
if y_offset < 0:
raise ValueError("y_offset must be nonnegative")
fmt = "!IIIIIHHBB"
chunk_data = _struct.pack(fmt, sequence_number, width, height,
x_offset, y_offset, delay_num, delay_den,
dispose_op, blend_op)
_write_chunk(f, b"fcTL", chunk_data)
def _write_fdat(f, sequence_number, data):
"""Write an fdAT chunk to `f`."""
seq = _struct.pack("!I", sequence_number)
_write_chunk(f, b"fdAT", seq + data)
def _write_data(f, a, bitdepth, max_chunk_len=None, sequence_number=None,
filter_type=None, interlace=0):
"""
Write the image data in the array `a` to the file, using IDAT chunks
if sequence_number is None and fdAT chunks otherwise.
`f` must be a writable file object.
`a` must be a numpy array to be written to the file `f`.
If `sequence_number` is None, 'IDAT' chunks are written.
If `sequence_number` is not None, `fdAT` chunks are written.
`interlace` must be 0 or 1. It determines the interlace method.
0 mean no interlacing; 1 means Adam7 interlacing.
Returns the number of chunks written to the file.
`filter_type` is passed on to _create_stream().
"""
if interlace == 1:
passes = _interlace_passes(a)
else:
passes = [a]
if bitdepth is not None and bitdepth < 8:
passes = [_pack(aa, bitdepth) for aa in passes]
if filter_type == "auto":
filter_types = [0, 1, 2, 3, 4, "heuristic"]
else:
filter_types = [filter_type]
zstream = None
for filter_type in filter_types:
stream = b''
for a in passes:
if a.size > 0:
stream += _create_stream(a, filter_type=filter_type)
z = _zlib.compress(stream)
if zstream is None or len(z) < len(zstream):
zstream = z
# zstream is a string containing the packed, compressed version of the
# data from the array `a`. This will be written to the file in one or
# more IDAT or fdAT chunks.
if max_chunk_len is None:
# Put the whole thing in one chunk.
max_chunk_len = len(zstream)
elif max_chunk_len < 1:
raise ValueError("max_chunk_len must be at least 1.")
num_data_chunks = (len(zstream) + max_chunk_len - 1) // max_chunk_len
for k in range(num_data_chunks):
start = k * max_chunk_len
end = min(start + max_chunk_len, len(zstream))
data = zstream[start:end]
if sequence_number is None:
_write_idat(f, data)
else:
_write_fdat(f, sequence_number, data)
sequence_number += 1
return num_data_chunks
def _encode_latin1(s):
if _PY3:
unicode_type = str
else:
unicode_type = eval('unicode')
if isinstance(s, unicode_type):
s = s.encode('latin-1')
return s
def _validate_keyword(keyword, keyname='keyword'):
"""
From http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html:
The keyword must be at least one character and less than 80 characters
long. Keywords are always interpreted according to the ISO/IEC 8859-1
(Latin-1) character set [ISO/IEC-8859-1]. They must contain only
printable Latin-1 characters and spaces; that is, only character
codes 32-126 and 161-255 decimal are allowed. To reduce the chances
for human misreading of a keyword, leading and trailing spaces are
forbidden, as are consecutive spaces. Note also that the non-breaking
space (code 160) is not permitted in keywords, since it is visually
indistinguishable from an ordinary space.
"""
if not (0 < len(keyword) < 80):
raise ValueError("length of %s must greater than 0 and less "
"than 80." % (keyname,))
kw_check = all([(31 < _bord(c) < 127) or (160 < _bord(c) < 256)
for c in keyword])
if not kw_check:
raise ValueError("%s %r contains non-printable characters or "
"a non-breaking space (code 160)." %
(keyname, keyword,))
if keyword.startswith(b' '):
raise ValueError("%s %r begins with a space." % (keyname, keyword,))
if keyword.endswith(b' '):
raise ValueError("%s %r ends with a space." % (keyname, keyword,))
if b' ' in keyword:
raise ValueError("%s %r contains consecutive spaces." %
(keyname, keyword,))
def _validate_text(text_list):
if text_list is None:
text_list = []
creation_time = _encode_latin1(_time.strftime("%Y-%m-%dT%H:%M:%SZ",
_time.gmtime()))
software = _encode_latin1(_software_text())
text_list = [(_encode_latin1(keyword), _encode_latin1(text))
for keyword, text in text_list]
keywords = [keyword for keyword, text in text_list]
if b"Creation Time" not in keywords:
text_list.append((b"Creation Time", creation_time))
if b"Software" not in keywords:
text_list.append((b"Software", software))
validated_text_list = []
for keyword, text_string in text_list:
if text_string is None:
# Drop elements where the text string is None.
continue
_validate_keyword(keyword)
# Validate the text string.
if b'\0' in text_string:
raise ValueError("text_string contains a null character.")
validated_text_list.append((keyword, text_string))
return validated_text_list
def _palettize(a):
# `a` must be a numpy array with dtype `np.uint8` and shape (m, n, 3) or
# (m, n, 4).
a = _np.ascontiguousarray(a)
depth = a.shape[-1]
dt = ','.join(['u1'] * depth)
b = a.view(dt).reshape(a.shape[:-1])
colors, inv = _np.unique(b, return_inverse=True)
index = inv.astype(_np.uint8).reshape(a.shape[:-1])
# palette is the RGB values of the unique RGBA colors.
palette = colors.view(_np.uint8).reshape(-1, depth)[:, :3]
if depth == 3:
trans = None
else:
# trans is the 1-d array of alpha values of the unique RGBA colors.
# trans is the same length as `palette`.
trans = colors['f3']
return index, palette, trans
def _palettize_seq(seq):
""""
seq must be a sequence of 3-d numpy arrays with dtype np.uint8,
all with the same depth (i.e. the same length of the third dimension).
"""
# Call np.unique for each array in seq. Each array is viewed as a
# 2-d structured array of colors.
depth = seq[0].shape[-1]
dt = ','.join(['u1'] * depth)
result = [_np.unique(a.view(dt).reshape(a.shape[:-1]), return_inverse=True)
for a in seq]
# `sizes` is the number of unique colors found in each array.
sizes = [len(r[0]) for r in result]
# Combine all the colors found in each array to get the overall
# set of unique colors.
combined = _np.concatenate([r[0] for r in result])
colors, inv = _np.unique(combined, return_inverse=True)
offsets = _np.cumsum(_np.r_[0, sizes[:-1]])
invs = [r[1].reshape(a.shape[:2]) for r, a in zip(result, seq)]
# The sequence index_seq holds the converted arrays. The values
# in these arrays are indices into `palette`. Note that if
# len(palette) > 256, the conversion to np.uint8 will cause
# some values in the arrays in `index_seq` to wrap around.
# The caller must check the len(palette) to determine if this
# has happened.
index_seq = [inv[o:o+s][i].astype(_np.uint8)
for i, o, s in zip(invs, offsets, sizes)]
palette = colors.view(_np.uint8).reshape(-1, depth)[:, :3]
if depth == 3:
trans = None
else:
# trans is the 1-d array of alpha values of the unique RGBA colors.
# trans is the same length as `palette`.
trans = colors['f3']
return index_seq, palette, trans
def _pack(a, bitdepth):
"""
Pack the values in `a` into bitfields of a smaller array.
`a` must be a 2-d numpy array with dtype `np.uint8`
bitdepth must be either 1, 2, 4 or 8.
(bitdepth=8 is a trivial case, for which the return value is simply `a`.)
"""
if a.dtype != _np.uint8:
raise ValueError('Input array must have dtype uint8')
if a.ndim != 2:
raise ValueError('Input array must be two dimensional')
if bitdepth == 8:
return a
ncols, rembits = divmod(a.shape[1]*bitdepth, 8)
if rembits > 0:
ncols += 1
b = _np.zeros((a.shape[0], ncols), dtype=_np.uint8)
for row in range(a.shape[0]):
bcol = 0
pos = 8
for col in range(a.shape[1]):
val = (2**bitdepth - 1) & a[row, col]
pos -= bitdepth
if pos < 0:
bcol += 1
pos = 8 - bitdepth
b[row, bcol] |= (val << pos)
return b
def _unpack(p, bitdepth, width):
powers = _np.arange(bitdepth-1, -1, -1)
up = _np.unpackbits(p).reshape(p.shape[0], -1, bitdepth).dot(2**powers)
a = up[:, :width]
return a
def _validate_array(a):
if a.ndim != 2:
if a.ndim != 3 or a.shape[2] > 4 or a.shape[2] == 0:
raise ValueError("array must be 2D, or 3D with shape "
"(m, n, d) with 1 <= d <= 4.")
itemsize = a.dtype.itemsize
if not _np.issubdtype(a.dtype, _np.unsignedinteger) or itemsize > 2:
raise ValueError("array must be an array of 8- or 16-bit "
"unsigned integers")
# Notes on color_type:
#
# color_type meaning tRNS chunk contents (optional)
# ---------- ------------------------ --------------------------------
# 0 grayscale Single gray level value, 2 bytes
# 2 RGB Single RGB, 2 bytes per channel
# 3 8 bit indexed RGB or RGBA Series of 1 byte alpha values
# 4 Grayscale and alpha
# 6 RGBA
#
#
# from http://www.w3.org/TR/PNG/:
# Table 11.1 - Allowed combinations of colour type and bit depth
#
# Color Allowed
# PNG image type type bit depths Interpretation
# Greyscale 0 1, 2, 4, 8, 16 Each pixel is a greyscale
# sample
# Truecolour 2 8, 16 Each pixel is an RGB triple
# Indexed-colour 3 1, 2, 4, 8 Each pixel is a palette index;
# a PLTE chunk shall appear.
# Greyscale with alpha 4 8, 16 Each pixel is a greyscale
# sample followed by an alpha
# sample.
# Truecolour with alpha 6 8, 16 Each pixel is an RGB triple
# followed by an alpha sample.
def _get_color_type(a, use_palette):
if a.ndim == 2:
color_type = 0
else:
depth = a.shape[2]
if depth == 1:
# Grayscale
color_type = 0
elif depth == 2:
# Grayscale and alpha
color_type = 4
elif depth == 3:
# RGB
if a.dtype == _np.uint8 and use_palette:
# Indexed color (create a palette)
color_type = 3
else:
# RGB colors
color_type = 2
elif depth == 4:
# RGB and alpha
if a.dtype == _np.uint8 and use_palette:
color_type = 3
else:
color_type = 6
return color_type
def _validate_bitdepth(bitdepth, a, color_type):
if bitdepth not in [None, 1, 2, 4, 8, 16]:
raise ValueError('bitdepth %i is not valid. Valid values are '
'1, 2, 4, 8 or 16' % (bitdepth,))
if bitdepth is not None:
if color_type in [2, 4, 6]:
if 8*a.dtype.itemsize != bitdepth:
raise ValueError("For the given input, the bit depth must "
"match the data type of the array.")
elif color_type == 3:
if bitdepth == 16:
raise ValueError("Bit depth 16 not allowed when use_palette "
"is True.")
else:
# Given bitdepth is None
if color_type == 3:
bitdepth = 8
else:
bitdepth = 8*a.dtype.itemsize
return bitdepth
def _validate_timestamp(timestamp):
if timestamp is None:
return None
if len(timestamp) != 6:
raise ValueError("timestamp must have length 6")
return timestamp
def _validate_phys(phys):
if phys is not None:
if len(phys) == 2:
phys = tuple(phys) + (0,)
elif phys[2] not in [0, 1]:
raise ValueError('Third element of `phys` must be 0 or 1.')
phys = [int(x) for x in phys]
if phys[0] <= 0 or phys[1] <= 0:
raise ValueError('The pixels per unit in `phys` must be positive.')
return phys
def _validate_iccp(iccp):
if iccp is not None:
if len(iccp) != 2:
raise ValueError('`iccp` must have two elements.')
if not isinstance(iccp[0], str):
raise ValueError('First element of `iccp` must be str.')
try:
profile_name = _encode_latin1(iccp[0])
except UnicodeEncodeError:
raise ValueError('The profile name (the first element of `iccp`) '
'must be encodable as Latin-1.')
_validate_keyword(profile_name, 'profile name')
if not isinstance(iccp[1], bytes):
raise ValueError('Second element of `iccp` must be bytes.')
return iccp
def _validate_chromaticity(chromaticity):
if chromaticity is not None:
if len(chromaticity) != 4:
raise ValueError('chromaticity must be a sequence with length 4.')
for pair in chromaticity:
if len(pair) != 2:
raise ValueError('each item in chromaticity must be a '
'sequence of length 2.')
if not ((0 <= pair[0] <= 1) and (0 <= pair[1] <= 1)):
raise ValueError('each value in chromaticity must be between '
'0 and 1.')
return chromaticity
def _validate_sbit(sbit, color_type, bitdepth):
try:
len_sbit = len(sbit)
except TypeError:
sbit = (sbit,)
len_sbit = 1
try:
[operator.index(n) for n in sbit]
except Exception:
raise ValueError('Each value in sbit must be an integer.')
# Mapping from color_type to required length of sbit:
required_length = {0: 1, 2: 3, 3: 3, 4: 2, 6: 4}
if len_sbit != required_length[color_type]:
raise ValueError('For color type %d, len(sbit) must be %d' %
(color_type, required_length[color_type]))
for n in sbit:
if n < 1 or n > bitdepth:
raise ValueError('Each value in sbit must be greater than 0 '
'and less than or equal to the bit depth %s'
% bitdepth)
return sbit
def _common_validation(interlace, filter_type, phys, text_list, timestamp,
chromaticity):
if interlace not in [0, 1]:
raise ValueError('interlace must be 0 or 1.')
if filter_type is None:
filter_type = "auto"
phys = _validate_phys(phys)
text_list = _validate_text(text_list)
timestamp = _validate_timestamp(timestamp)
chromaticity = _validate_chromaticity(chromaticity)
return filter_type, phys, text_list, timestamp, chromaticity
def _add_background_color(background, palette, trans, bitdepth):
if len(background) != 3:
raise ValueError("background must have length 3 when "
"use_palette is True.")
index = _np.where((palette == background).all(axis=-1))[0]
if index.size > 0:
# The given background color is in the palette.
background = index[0]
else:
# The given background color is *not* in the palette. Is there
# room for one more color?
if bitdepth is None:
bitdepth = 8
if len(palette) == 2**bitdepth:
msg = ("The array already has the maximum of %i colors, and a "
"background color that is not in the array has been given. "
"With a bitdepth of %i, no more than %i colors are allowed "
"when using a palette." % (2**bitdepth, bitdepth,
2**bitdepth))
raise ValueError(msg)
else:
index = len(palette)
palette = _np.append(palette,
_np.array([background],
dtype=_np.uint8),
axis=0)
if trans is not None:
trans = _np.append(trans, [_np.uint8(255)])
background = index
return background, palette, trans
def _write_header_and_meta(f, dtype, shape, color_type, bitdepth, palette,
interlace, text_list, timestamp, sbit, gamma, iccp,
chromaticity, trans, background, phys):
# Write the PNG header.
f.write(b"\x89PNG\x0D\x0A\x1A\x0A")
# Write the chunks...
# IHDR chunk
if bitdepth is not None:
nbits = bitdepth
else:
nbits = dtype.itemsize*8
_write_ihdr(f, shape[1], shape[0], nbits, color_type, interlace)
# tEXt chunks, if any.
if text_list is not None:
for keyword, text_string in text_list:
_write_text(f, keyword, text_string)
if timestamp is not None:
_write_time(f, timestamp)
# sBIT must preceed PLTE (if present) and first IDAT chunk.
if sbit is not None:
_write_sbit(f, sbit)
if gamma is not None:
_write_gama(f, gamma)
# iCCP chunk, if `iccp` was given.
if iccp is not None:
_write_iccp(f, iccp)
# cHRM chunk, if `chromaticity` was given.
if chromaticity is not None:
_write_chrm(f, chromaticity)
# PLTE chunk, if requested.
if color_type == 3:
_write_plte(f, palette)
# tRNS chunk, if there is one.
if trans is not None:
_write_trns(f, trans)
# bKGD chunk, if there is one.
if background is not None:
_write_bkgd(f, background, color_type)
# pHYs chunk, if `phys` was given.
if phys is not None:
_write_phys(f, phys)
def write_png(fileobj, a, text_list=None, use_palette=False,
transparent=None, bitdepth=None, max_chunk_len=None,
timestamp=None, gamma=None, background=None,
filter_type=None, interlace=0, phys=None, iccp=None,
chromaticity=None, sbit=None):
"""
Write a numpy array to a PNG file.
Parameters
----------
fileobj : string or file object
If fileobj is a string, it is the name of the PNG file to be created.
Otherwise fileobj must be a file opened for writing.
a : numpy array
Must be an array of 8- or 16-bit unsigned integers. The shape of `a`
must be (m, n) or (m, n, d) with 1 <= d <= 4.
text_list : list of (keyword, text) tuples, optional
Each tuple is written to the file as a 'tEXt' chunk. See the Notes
for more information about text in PNG files.
use_palette : bool, optional
If True, *and* the data type of `a` is `numpy.uint8`, *and* the size
of `a` is (m, n, 3), then a PLTE chunk is created and an indexed color
image is created. (If the conditions on `a` are not true, this
argument is ignored and a palette is not created.) There must not be
more than 2**bitdepth distinct colors in `a`. If the conditions on `a`
are true but the array has more than 256 colors, a ValueError exception
is raised.
transparent : integer or 3-tuple of integers (r, g, b), optional
If the colors in `a` do not include an alpha channel (i.e. the shape
of `a` is (m, n), (m, n, 1) or (m, n, 3)), the `transparent` argument
can be used to specify a single color that is to be considered the
transparent color. This argument is ignored if `a` includes an
alpha channel, or if `use_palette` is True and the `transparent`
color is not in `a`. Otherwise, a 'tRNS' chunk is included in the
PNG file.
bitdepth : integer, optional
Bit depth of the output image. Valid values are 1, 2, 4 and 8.
Only valid for grayscale images with no alpha channel with an input
array having dtype numpy.uint8. If not given, the bit depth is
inferred from the data type of the input array `a`.
max_chunk_len : integer, optional
The data in a PNG file is stored in records called IDAT chunks.
`max_chunk_len` sets the maximum number of data bytes to stored in
each IDAT chunk. The default is None, which means that all the data
is written to a single IDAT chunk.
timestamp : tuple with length 6, optional
If this argument is not None, a 'tIME' chunk is included in the
PNG file. The value must be a tuple of six integers: (year, month,
day, hour, minute, second).
gamma : float, optional
If this argument is not None, a 'gAMA' chunk is included in the
PNG file. The argument is expected to be a floating point value.
The value written in the 'gAMA' chunk is int(gamma*100000 + 0.5).
background : int (for grayscale) or sequence of three ints (for RGB)
Set the default background color. When this option is used, a
'bKGD' chunk is included in the PNG file. When `use_palette`
is True, and `background` is not one of the colors in `a`, the
`background` color is included in the palette, and so it counts
towards the maximum number of 256 colors allowed in a palette.
filter_type : one of 0, 1, 2, 3, 4, "heuristic" or "auto", optional
Controls the filter type that is used per scanline in the IDAT
chunks. The default is "auto", which means the output data is
generated six time, once for each of the other possible filter
types, and the filter that generates the smallest output is used.
interlace : either 0 or 1
Interlace method to use. 0 means no interlace; 1 means Adam7.
phys : tuple with length 2 or 3, optional
If given, a `pHYs` chunk is written to the PNG file.
If `phys` is given, it must be a tuple of integers with length 2
or 3. The first two integers are the pixels per unit of the X
and Y axes, respectively. The third value, if given, must be 0
or 1. If the value is 1, the units of the first two values are
pixels per *meter*. If the third value is 0 (or not given),
the units of the first two values are undefined. In that case,
the values define the pixel aspect ratio only.
iccp : tuple with length 2, optional
ICCP color profile. If given, the argument must be a tuple of length 2.
The first element must be a string containing the profile name. The
profile name is subject to the same restrictions as the keywords in the
text_list argument; see the Notes for more information about these
restrictions. The second element is the profile data, and it must be a
bytes object. This data is not validated. It is written "as is" to
the PNG file.
chromaticity : array-like, optional
The four chromaticity values: white point, red, green and blue.
If given, the value must be a sequence of length four containing pairs
(x, y) of chromaticity values. The values must be floating point
in the interval [0, 1].
sbit : sequence of 1, 2, 3, or 4 integers, optional
If given, the value(s) are written in an `sBIT` chunk in the PNG
file. The values indicate the original number of significant bits
in each color (and alpha, if applicable) channel. The values must be
compatible with the color type and bit depth of the image data.
Notes
-----
If `a` is three dimensional (i.e. `a.ndim == 3`), the size of the last
dimension determines how the values in the last dimension are interpreted,
as follows:
a.shape[2] Interpretation
---------- --------------------
1 grayscale
2 grayscale and alpha
3 RGB
4 RGB and alpha
The `text_list` argument accepts a list of tuples of two strings argument.
The first item in each tuple is the *keyword*, and the second is the text
string. This argument allows `'tEXt'` chunks to be created. The
following is from the PNG specification::
The keyword indicates the type of information represented by the
text string. The following keywords are predefined and should be
used where appropriate:
Title Short (one line) title or caption for image
Author Name of image's creator
Description Description of image (possibly long)
Copyright Copyright notice
Creation Time Time of original image creation
Software Software used to create the image
Disclaimer Legal disclaimer
Warning Warning of nature of content
Source Device used to create the image
Comment Miscellaneous comment; conversion from GIF comment