-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy path_writer.py
More file actions
1849 lines (1629 loc) · 75.7 KB
/
_writer.py
File metadata and controls
1849 lines (1629 loc) · 75.7 KB
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
"""GeoTIFF/COG writer."""
from __future__ import annotations
import math
import struct
import warnings
import numpy as np
from ._compression import (
COMPRESSION_DEFLATE,
COMPRESSION_JPEG,
COMPRESSION_JPEG2000,
COMPRESSION_LERC,
COMPRESSION_LZ4,
COMPRESSION_LZW,
COMPRESSION_NONE,
COMPRESSION_PACKBITS,
COMPRESSION_ZSTD,
compress,
fp_predictor_encode,
jpeg_compress,
predictor_encode,
)
from ._dtypes import (
DOUBLE,
RATIONAL,
SHORT,
LONG,
LONG8,
ASCII,
numpy_to_tiff_dtype,
TIFF_TYPE_SIZES,
)
from ._geotags import (
GeoTransform,
build_geo_tags,
TAG_GEO_ASCII_PARAMS,
TAG_GEO_KEY_DIRECTORY,
TAG_GDAL_NODATA,
TAG_MODEL_PIXEL_SCALE,
TAG_MODEL_TIEPOINT,
TAG_MODEL_TRANSFORMATION,
)
from ._header import (
TAG_NEW_SUBFILE_TYPE,
TAG_IMAGE_WIDTH,
TAG_IMAGE_LENGTH,
TAG_BITS_PER_SAMPLE,
TAG_COMPRESSION,
TAG_PHOTOMETRIC,
TAG_SAMPLES_PER_PIXEL,
TAG_SAMPLE_FORMAT,
TAG_STRIP_OFFSETS,
TAG_ROWS_PER_STRIP,
TAG_STRIP_BYTE_COUNTS,
TAG_SUB_IFDS,
TAG_X_RESOLUTION,
TAG_Y_RESOLUTION,
TAG_RESOLUTION_UNIT,
TAG_TILE_WIDTH,
TAG_TILE_LENGTH,
TAG_TILE_OFFSETS,
TAG_TILE_BYTE_COUNTS,
TAG_EXTRA_SAMPLES,
TAG_PREDICTOR,
TAG_GDAL_METADATA,
)
# Tag IDs the writer must never accept from ``extra_tags``. NewSubfileType
# (254) is a per-IFD status flag the writer emits on its own for overview
# IFDs; copying a level-1 source value onto a level-0 destination would
# mis-mark the primary IFD as a reduced-resolution overview. SubIFDs
# (330) carries absolute byte offsets, which become garbage after a
# rewrite. The read side now filters both via ``_MANAGED_TAGS``; this
# constant is the writer-side belt-and-braces guard. See issue #1657.
_DANGEROUS_EXTRA_TAG_IDS = frozenset({TAG_NEW_SUBFILE_TYPE, TAG_SUB_IFDS})
# Byte order: always write little-endian
BO = '<'
def normalize_predictor(predictor, dtype, compression: int) -> int:
"""Normalize a user-supplied predictor value to a TIFF predictor int.
Accepts ``False``/``True`` (legacy) and integers ``1``/``2``/``3``.
Returns ``1`` (no predictor), ``2`` (horizontal differencing), or ``3``
(floating-point predictor).
"""
if predictor is False or predictor == 0:
return 1
if predictor is True or predictor == 2:
return 2
if predictor == 1:
return 1
if predictor == 3:
if np.dtype(dtype).kind != 'f':
raise ValueError(
"predictor=3 (floating-point) requires float data, "
f"got dtype={np.dtype(dtype)}")
return 3
raise ValueError(
f"predictor must be False/True or 1/2/3, got {predictor!r}")
def _apply_predictor_encode(buf: np.ndarray, predictor: int,
width: int, height: int,
bytes_per_sample: int, samples: int) -> np.ndarray:
"""Apply the chosen predictor to a flat uint8 buffer.
Files always go to disk in little-endian order (see ``BO``), so
``predictor_encode`` is invoked with ``byte_order='<'``.
"""
if predictor == 2:
return predictor_encode(buf, width, height,
bytes_per_sample, samples=samples,
byte_order=BO)
if predictor == 3:
return fp_predictor_encode(buf, width * samples, height,
bytes_per_sample)
return buf
def _compression_tag(compression_name: str) -> int:
"""Convert compression name to TIFF tag value."""
_map = {
'none': COMPRESSION_NONE,
'deflate': COMPRESSION_DEFLATE,
'lzw': COMPRESSION_LZW,
'jpeg': COMPRESSION_JPEG,
'packbits': COMPRESSION_PACKBITS,
'zstd': COMPRESSION_ZSTD,
'lz4': COMPRESSION_LZ4,
'jpeg2000': COMPRESSION_JPEG2000,
'j2k': COMPRESSION_JPEG2000,
'lerc': COMPRESSION_LERC,
}
name = compression_name.lower()
if name not in _map:
raise ValueError(f"Unsupported compression: {compression_name!r}. "
f"Use one of: {list(_map.keys())}")
return _map[name]
OVERVIEW_METHODS = ('mean', 'nearest', 'min', 'max', 'median', 'mode', 'cubic')
#: Maximum number of overview levels generated by auto-overview mode in COG
#: writes. 8 halvings = 1/256 of the original resolution, which is enough
#: for any practical raster. Pass ``overview_levels=[...]`` explicitly to
#: override.
_MAX_OVERVIEW_LEVELS = 8
def _block_reduce_2d(arr2d, method, nodata=None):
"""2x block-reduce a single 2D plane using *method*.
When ``nodata`` is supplied, cells that equal the sentinel are
treated as NaN during the reduction so the ``nan*`` aggregation
routines correctly skip them. The float branch keeps any all-
sentinel block as NaN so the caller's post-overview loop can
rewrite it back to the sentinel; the integer branch rewrites NaN
back to the sentinel before the dtype cast so the cast is
well-defined (the caller's post-overview loop only handles the
float case). The ``nearest`` and ``mode`` methods do NOT mask the
sentinel: ``nearest`` returns the top-left pixel of each 2x2 block
and ``mode`` returns the most-frequent value, so the sentinel can
be selected as the overview pixel if it occupies that position
(``nearest``) or is the most frequent value in the block
(``mode``). Mean / median / min / max / cubic all mask the
sentinel before reduction. The ``cubic`` branch honours ``nodata``
by masking the sentinel to NaN, running cubic with
``prefilter=False`` to keep the kernel local, and rewriting any
NaN in the output back to the sentinel before returning (issue
#1623).
"""
h, w = arr2d.shape
h2 = (h // 2) * 2
w2 = (w // 2) * 2
cropped = arr2d[:h2, :w2]
oh, ow = h2 // 2, w2 // 2
if method == 'nearest':
# Top-left pixel of each 2x2 block
return cropped[::2, ::2].copy()
if method == 'cubic':
try:
from scipy.ndimage import zoom
except ImportError:
raise ImportError(
"scipy is required for cubic overview resampling. "
"Install it with: pip install scipy")
# When ``nodata`` is supplied on a float array, the writer has
# already rewritten NaN to the sentinel value upstream. Feeding
# that sentinel-poisoned array straight into ``zoom`` blends the
# sentinel into neighbouring cells and produces ringing
# artefacts near nodata borders (issue #1623, same root cause
# as #1613 but for the cubic branch).
#
# Mask the sentinel back to NaN before the spline so the
# interpolation does not treat it as signal, run cubic with
# ``prefilter=False`` so a single NaN does not poison the entire
# row/column (the default B-spline prefilter is global), then
# rewrite any NaN in the result back to the sentinel so the
# on-disk overview keeps the same convention as the
# full-resolution band. The ``prefilter=False`` switch only
# fires when a sentinel was actually found in the input, so the
# default cubic semantics still apply to inputs without nodata.
if (nodata is not None
and arr2d.dtype.kind == 'f'
and not np.isnan(nodata)):
try:
sentinel = arr2d.dtype.type(nodata)
except (OverflowError, ValueError):
sentinel = None
if sentinel is not None:
mask = arr2d == sentinel
if mask.any():
masked = np.where(mask, np.float64('nan'), arr2d)
with warnings.catch_warnings():
warnings.simplefilter('ignore', RuntimeWarning)
result = zoom(masked, 0.5, order=3,
prefilter=False)
nan_mask = np.isnan(result)
if nan_mask.any():
result = result.copy()
result[nan_mask] = float(nodata)
return result.astype(arr2d.dtype)
return zoom(arr2d, 0.5, order=3).astype(arr2d.dtype)
if method == 'mode':
# Most-common value per 2x2 block (useful for classified rasters).
# Vectorized: sort each 4-cell block, then for each position count
# how many cells equal it. argmax picks the leftmost max-count
# position, which (post-sort) is the smallest tied value, matching
# the prior np.unique+argmax tie-break behavior ("lowest wins").
blocks = cropped.reshape(oh, 2, ow, 2).transpose(0, 2, 1, 3).reshape(oh, ow, 4)
srt = np.sort(blocks, axis=-1)
counts = np.empty_like(srt, dtype=np.int8)
for i in range(4):
counts[..., i] = np.sum(srt == srt[..., i:i + 1], axis=-1)
pick = np.argmax(counts, axis=-1)
return np.take_along_axis(srt, pick[..., None], axis=-1).squeeze(-1)
# Block reshape for mean/min/max/median
if arr2d.dtype.kind == 'f':
blocks = cropped.reshape(oh, 2, ow, 2)
# When a sentinel was used in place of NaN by an upstream
# NaN-to-sentinel rewrite, mask it back to NaN here so nanmean /
# nanmin / nanmax / nanmedian honour the missing-data semantic.
# Without this the sentinel value participates in the reduction
# and poisons the overview (issue #1613). Match the upstream
# NaN->sentinel rewrite gate (``not np.isnan(nodata)``) so that
# ``nodata=+/-inf`` is masked here too.
if nodata is not None and not np.isnan(nodata):
try:
sentinel = arr2d.dtype.type(nodata)
except (OverflowError, ValueError):
sentinel = None
if sentinel is not None:
mask = blocks == sentinel
if mask.any():
# ``np.where(mask, nan, blocks)`` produces a fresh
# array so the caller's input is not mutated.
blocks = np.where(mask, np.float64('nan'), blocks)
else:
blocks = cropped.astype(np.float64).reshape(oh, 2, ow, 2)
# Integer rasters with a sentinel need the same NaN-mask the float
# branch above applies: without it, nanmean / nanmin / nanmax /
# nanmedian average the sentinel value into surrounding valid
# cells and produce overview pixels that are neither the sentinel
# nor any real measurement. The read-side int-to-NaN mask in
# ``open_geotiff`` only catches exact sentinel hits, so the
# poisoned values survive as silent garbage at every zoom level
# above 0. Gate on the sentinel being representable in the
# source integer dtype (mirrors ``_int_nodata_in_range`` in
# ``_reader.py``) so an out-of-range sentinel pair like
# ``uint16`` + ``GDAL_NODATA="-9999"`` stays a no-op rather than
# tripping ``OverflowError`` on the dtype cast.
if (nodata is not None
and np.isfinite(nodata)
and float(nodata).is_integer()):
nodata_int = int(nodata)
info = np.iinfo(arr2d.dtype)
if info.min <= nodata_int <= info.max:
sentinel = arr2d.dtype.type(nodata_int)
# Compare against the original integer block view so
# the equality runs at the integer's native width
# (avoids any float-cast rounding on adjacent values).
# The boolean mask broadcasts into the float64 block
# layout below.
int_blocks = cropped.reshape(oh, 2, ow, 2)
mask = int_blocks == sentinel
if mask.any():
blocks = np.where(mask, np.float64('nan'), blocks)
# nanmean / nanmin / nanmax / nanmedian emit RuntimeWarning when a
# 2x2 block is all-NaN (typical at nodata borders). The all-NaN
# output is the desired signal that the caller rewrites to the
# sentinel, so suppress the warning locally to keep COG writes quiet.
with warnings.catch_warnings():
warnings.simplefilter('ignore', RuntimeWarning)
if method == 'mean':
result = np.nanmean(blocks, axis=(1, 3))
elif method == 'min':
result = np.nanmin(blocks, axis=(1, 3))
elif method == 'max':
result = np.nanmax(blocks, axis=(1, 3))
elif method == 'median':
flat = blocks.transpose(0, 2, 1, 3).reshape(oh, ow, 4)
result = np.nanmedian(flat, axis=2)
else:
raise ValueError(
f"Unknown overview resampling method: {method!r}. "
f"Use one of: {OVERVIEW_METHODS}")
if arr2d.dtype.kind != 'f':
# All-sentinel 2x2 blocks come back as NaN from the nan-aware
# reduction; cast NaN to an integer dtype is undefined (varies
# between platforms / produces zero or INT_MIN). Rewrite those
# back to the sentinel before the cast so the integer overview
# pyramid carries the same masking convention as the
# full-resolution band. The float branch relies on the caller's
# post-overview rewrite in ``write()``; integer dtypes skip that
# branch because ``current.dtype.kind == 'f'`` is False, so we
# close the loop here.
if nodata is not None and np.isfinite(nodata):
nan_mask = np.isnan(result)
if nan_mask.any():
info = np.iinfo(arr2d.dtype)
nodata_int = int(nodata) if float(nodata).is_integer() else None
if (nodata_int is not None
and info.min <= nodata_int <= info.max):
result = np.where(nan_mask, float(nodata_int), result)
return np.round(result).astype(arr2d.dtype)
return result.astype(arr2d.dtype)
def _make_overview(arr: np.ndarray, method: str = 'mean',
nodata=None) -> np.ndarray:
"""Generate a 2x decimated overview.
Parameters
----------
arr : np.ndarray
2D or 3D (height, width, bands) array.
method : str
Resampling method: 'mean' (default), 'nearest', 'min', 'max',
'median', 'mode', or 'cubic'.
nodata : scalar or None
When supplied, cells equal to the sentinel are masked back to
NaN before the reduction so the sentinel does not bias the
result. Applies to both float dtypes (issue #1613, extended to
``cubic`` in #1623) and integer dtypes (the mean / min / max /
median reductions used to average the sentinel into surrounding
valid pixels and produce overview values that the reader could
not mask). Ignored for ``nearest`` / ``mode`` methods (no
averaging occurs).
Returns
-------
np.ndarray
Half-resolution array.
"""
if arr.ndim == 3:
bands = [_block_reduce_2d(arr[:, :, b], method, nodata=nodata)
for b in range(arr.shape[2])]
return np.stack(bands, axis=2)
return _block_reduce_2d(arr, method, nodata=nodata)
# ---------------------------------------------------------------------------
# Tag serialization
# ---------------------------------------------------------------------------
def _float_to_rational(val):
"""Convert a float to a TIFF RATIONAL (numerator, denominator) pair."""
if val == int(val):
return (int(val), 1)
# Use a denominator of 10000 for reasonable precision
den = 10000
num = int(round(val * den))
return (num, den)
def _serialize_tag_value(type_id, count, values):
"""Serialize tag values to bytes."""
if type_id == ASCII:
if isinstance(values, str):
return values.encode('ascii') + b'\x00'
return values + b'\x00'
elif type_id == SHORT:
if isinstance(values, (list, tuple)):
return struct.pack(f'{BO}{count}H', *values)
return struct.pack(f'{BO}H', values)
elif type_id == LONG:
if isinstance(values, (list, tuple)):
return struct.pack(f'{BO}{count}I', *values)
return struct.pack(f'{BO}I', values)
elif type_id == LONG8:
# BigTIFF 64-bit unsigned. Used for StripOffsets / TileOffsets
# (and their byte-count siblings) in files larger than 4 GB.
if isinstance(values, (list, tuple)):
return struct.pack(f'{BO}{count}Q', *values)
return struct.pack(f'{BO}Q', values)
elif type_id == RATIONAL:
# RATIONAL = two LONGs (numerator, denominator) per value
if isinstance(values, (list, tuple)) and isinstance(values[0], (list, tuple)):
parts = []
for num, den in values:
parts.extend([int(num), int(den)])
return struct.pack(f'{BO}{count * 2}I', *parts)
else:
num, den = _float_to_rational(float(values))
return struct.pack(f'{BO}II', num, den)
elif type_id == DOUBLE:
if isinstance(values, (list, tuple)):
return struct.pack(f'{BO}{count}d', *values)
return struct.pack(f'{BO}d', values)
else:
if isinstance(values, bytes):
return values
return struct.pack(f'{BO}I', values)
def _pack_tag_value(tag_id: int, type_id: int, count: int,
values, overflow_buf: bytearray,
overflow_base: int, bigtiff: bool = False) -> bytes:
"""Pack a single IFD entry.
Standard TIFF: 12 bytes (tag:2, type:2, count:4, value:4).
BigTIFF: 20 bytes (tag:2, type:2, count:8, value:8).
"""
val_bytes = _serialize_tag_value(type_id, count, values)
# For ASCII, count is the actual byte length
if type_id == ASCII:
count = len(val_bytes)
inline_max = 8 if bigtiff else 4
if bigtiff:
entry = struct.pack(f'{BO}HHQ', tag_id, type_id, count)
else:
entry = struct.pack(f'{BO}HHI', tag_id, type_id, count)
if len(val_bytes) <= inline_max:
value_field = val_bytes.ljust(inline_max, b'\x00')
else:
offset = overflow_base + len(overflow_buf)
if bigtiff:
value_field = struct.pack(f'{BO}Q', offset)
else:
value_field = struct.pack(f'{BO}I', offset)
overflow_buf.extend(val_bytes)
if len(overflow_buf) % 2:
overflow_buf.append(0)
return entry + value_field
def _build_ifd(tags: list[tuple], overflow_base: int,
bigtiff: bool = False) -> tuple[bytes, bytes]:
"""Build a complete IFD block.
Parameters
----------
tags : list of (tag_id, type_id, count, values)
Tags sorted by tag_id.
overflow_base : int
Where overflow data starts in the file.
Returns
-------
(ifd_bytes, overflow_bytes)
"""
# Sort by tag ID (TIFF spec requires this)
tags = sorted(tags, key=lambda t: t[0])
num_entries = len(tags)
overflow_buf = bytearray()
if bigtiff:
ifd_parts = [struct.pack(f'{BO}Q', num_entries)]
else:
ifd_parts = [struct.pack(f'{BO}H', num_entries)]
for tag_id, type_id, count, values in tags:
entry = _pack_tag_value(tag_id, type_id, count, values,
overflow_buf, overflow_base, bigtiff=bigtiff)
ifd_parts.append(entry)
# Next IFD offset (0 = no more IFDs, will be patched for COG)
if bigtiff:
ifd_parts.append(struct.pack(f'{BO}Q', 0))
else:
ifd_parts.append(struct.pack(f'{BO}I', 0))
return b''.join(ifd_parts), bytes(overflow_buf)
# ---------------------------------------------------------------------------
# Strip writer
# ---------------------------------------------------------------------------
def _write_stripped(data: np.ndarray, compression: int, predictor: int,
rows_per_strip: int = 256,
compression_level: int | None = None,
max_z_error: float = 0.0) -> tuple[list, list, list]:
"""Compress data as strips.
Returns
-------
(offsets_placeholder, byte_counts, compressed_chunks)
offsets are relative to the start of the compressed data block.
compressed_chunks is a list of bytes objects (one per strip).
"""
height, width = data.shape[:2]
samples = data.shape[2] if data.ndim == 3 else 1
dtype = data.dtype
bytes_per_sample = dtype.itemsize
strips = []
rel_offsets = []
byte_counts = []
current_offset = 0
num_strips = math.ceil(height / rows_per_strip)
for i in range(num_strips):
r0 = i * rows_per_strip
r1 = min(r0 + rows_per_strip, height)
strip_rows = r1 - r0
if compression == COMPRESSION_JPEG:
strip_data = np.ascontiguousarray(data[r0:r1]).tobytes()
compressed = jpeg_compress(strip_data, width, strip_rows, samples)
elif predictor != 1 and compression != COMPRESSION_NONE:
strip_arr = np.ascontiguousarray(data[r0:r1])
buf = strip_arr.view(np.uint8).ravel().copy()
buf = _apply_predictor_encode(
buf, predictor, width, strip_rows, bytes_per_sample, samples)
strip_data = buf.tobytes()
if compression_level is None:
compressed = compress(strip_data, compression)
else:
compressed = compress(strip_data, compression, level=compression_level)
else:
strip_data = np.ascontiguousarray(data[r0:r1]).tobytes()
if compression == COMPRESSION_JPEG2000:
from ._compression import jpeg2000_compress
compressed = jpeg2000_compress(
strip_data, width, strip_rows, samples=samples, dtype=dtype)
elif compression == COMPRESSION_LERC:
from ._compression import lerc_compress
compressed = lerc_compress(
strip_data, width, strip_rows, samples=samples, dtype=dtype,
max_z_error=max_z_error)
elif compression_level is None:
compressed = compress(strip_data, compression)
else:
compressed = compress(strip_data, compression, level=compression_level)
rel_offsets.append(current_offset)
byte_counts.append(len(compressed))
strips.append(compressed)
current_offset += len(compressed)
return rel_offsets, byte_counts, strips
# ---------------------------------------------------------------------------
# Tile writer
# ---------------------------------------------------------------------------
def _prepare_tile(data, tr, tc, th, tw, height, width, samples, dtype,
bytes_per_sample, predictor: int, compression,
compression_level=None, max_z_error: float = 0.0):
"""Extract, pad, and compress a single tile. Thread-safe."""
r0 = tr * th
c0 = tc * tw
r1 = min(r0 + th, height)
c1 = min(c0 + tw, width)
actual_h = r1 - r0
actual_w = c1 - c0
tile_slice = data[r0:r1, c0:c1]
if actual_h < th or actual_w < tw:
if data.ndim == 3:
padded = np.empty((th, tw, samples), dtype=dtype)
else:
padded = np.empty((th, tw), dtype=dtype)
padded[:actual_h, :actual_w] = tile_slice
if actual_h < th:
padded[actual_h:, :] = 0
if actual_w < tw:
padded[:actual_h, actual_w:] = 0
tile_arr = padded
else:
tile_arr = np.ascontiguousarray(tile_slice)
if compression == COMPRESSION_JPEG:
tile_data = tile_arr.tobytes()
return jpeg_compress(tile_data, tw, th, samples)
elif predictor != 1 and compression != COMPRESSION_NONE:
buf = tile_arr.view(np.uint8).ravel().copy()
buf = _apply_predictor_encode(
buf, predictor, tw, th, bytes_per_sample, samples)
tile_data = buf.tobytes()
else:
tile_data = tile_arr.tobytes()
if compression == COMPRESSION_JPEG2000:
from ._compression import jpeg2000_compress
return jpeg2000_compress(
tile_data, tw, th, samples=samples, dtype=dtype)
if compression == COMPRESSION_LERC:
from ._compression import lerc_compress
return lerc_compress(
tile_data, tw, th, samples=samples, dtype=dtype,
max_z_error=max_z_error)
if compression_level is None:
return compress(tile_data, compression)
return compress(tile_data, compression, level=compression_level)
def _write_tiled(data: np.ndarray, compression: int, predictor: int,
tile_size: int = 256,
compression_level: int | None = None,
max_z_error: float = 0.0) -> tuple[list, list, list]:
"""Compress data as tiles, using parallel compression.
For compressed formats (deflate, lzw, zstd), tiles are compressed
in parallel using a thread pool. zlib, zstandard, and our Numba
LZW all release the GIL.
Returns
-------
(relative_offsets, byte_counts, compressed_chunks)
compressed_chunks is a list of bytes objects (one per tile).
"""
height, width = data.shape[:2]
samples = data.shape[2] if data.ndim == 3 else 1
dtype = data.dtype
bytes_per_sample = dtype.itemsize
tw = tile_size
th = tile_size
tiles_across = math.ceil(width / tw)
tiles_down = math.ceil(height / th)
n_tiles = tiles_across * tiles_down
if compression == COMPRESSION_NONE:
# Uncompressed: pre-allocate a contiguous buffer for all tiles
# and copy tile data directly, avoiding per-tile Python overhead.
tile_bytes = tw * th * bytes_per_sample * samples
total_buf = bytearray(n_tiles * tile_bytes)
mv = memoryview(total_buf)
tiles = []
rel_offsets = []
byte_counts = []
current_offset = 0
for tr in range(tiles_down):
for tc in range(tiles_across):
r0 = tr * th
c0 = tc * tw
r1 = min(r0 + th, height)
c1 = min(c0 + tw, width)
actual_h = r1 - r0
actual_w = c1 - c0
tile_slice = data[r0:r1, c0:c1]
if actual_h < th or actual_w < tw:
if data.ndim == 3:
padded = np.zeros((th, tw, samples), dtype=dtype)
else:
padded = np.zeros((th, tw), dtype=dtype)
padded[:actual_h, :actual_w] = tile_slice
tile_arr = padded
else:
tile_arr = np.ascontiguousarray(tile_slice)
chunk = tile_arr.tobytes()
rel_offsets.append(current_offset)
byte_counts.append(len(chunk))
tiles.append(chunk)
current_offset += len(chunk)
return rel_offsets, byte_counts, tiles
if n_tiles <= 4:
# Very few tiles: sequential (thread pool overhead not worth it)
tiles = []
rel_offsets = []
byte_counts = []
current_offset = 0
for tr in range(tiles_down):
for tc in range(tiles_across):
compressed = _prepare_tile(
data, tr, tc, th, tw, height, width,
samples, dtype, bytes_per_sample, predictor, compression,
compression_level, max_z_error,
)
rel_offsets.append(current_offset)
byte_counts.append(len(compressed))
tiles.append(compressed)
current_offset += len(compressed)
return rel_offsets, byte_counts, tiles
# Parallel tile compression -- zlib/zstd/LZW all release the GIL
from concurrent.futures import ThreadPoolExecutor
import os
n_workers = min(n_tiles, os.cpu_count() or 4)
tile_indices = [(tr, tc) for tr in range(tiles_down)
for tc in range(tiles_across)]
with ThreadPoolExecutor(max_workers=n_workers) as pool:
futures = [
pool.submit(
_prepare_tile, data, tr, tc, th, tw, height, width,
samples, dtype, bytes_per_sample, predictor, compression,
compression_level, max_z_error,
)
for tr, tc in tile_indices
]
compressed_tiles = [f.result() for f in futures]
rel_offsets = []
byte_counts = []
current_offset = 0
for ct in compressed_tiles:
rel_offsets.append(current_offset)
byte_counts.append(len(ct))
current_offset += len(ct)
return rel_offsets, byte_counts, compressed_tiles
# ---------------------------------------------------------------------------
# File assembly
# ---------------------------------------------------------------------------
def _assemble_tiff(width: int, height: int, dtype: np.dtype,
compression: int, predictor: int,
tiled: bool, tile_size: int,
pixel_data_parts: list[tuple],
geo_transform: GeoTransform | None,
crs_epsg: int | None,
nodata,
is_cog: bool = False,
raster_type: int = 1,
crs_wkt: str | None = None,
gdal_metadata_xml: str | None = None,
extra_tags: list | None = None,
x_resolution: float | None = None,
y_resolution: float | None = None,
resolution_unit: int | None = None,
force_bigtiff: bool | None = None) -> bytes:
"""Assemble a complete TIFF file.
Parameters
----------
pixel_data_parts : list of (array, width, height, relative_offsets, byte_counts, compressed_data)
One entry per resolution level (full res first, then overviews).
is_cog : bool
If True, layout IFDs contiguously at file start (COG layout).
raster_type : int
1 = PixelIsArea, 2 = PixelIsPoint.
Returns
-------
bytes
Complete TIFF file.
"""
bits_per_sample, sample_format = numpy_to_tiff_dtype(dtype)
# Determine samples per pixel from the pixel data
first_arr = pixel_data_parts[0][0]
samples_per_pixel = first_arr.shape[2] if first_arr.ndim == 3 else 1
# Build geo tags
geo_tags_dict = {}
if geo_transform is not None:
geo_tags_dict = build_geo_tags(
geo_transform, crs_epsg, nodata, raster_type=raster_type,
crs_wkt=crs_wkt)
else:
# No spatial reference -- still write CRS and nodata if provided
if crs_epsg is not None or crs_wkt is not None or nodata is not None:
geo_tags_dict = build_geo_tags(
GeoTransform(), crs_epsg, nodata, raster_type=raster_type,
crs_wkt=crs_wkt,
)
# Remove the default pixel scale / tiepoint tags since we
# have no real transform -- keep only GeoKeys and NODATA.
geo_tags_dict.pop(TAG_MODEL_PIXEL_SCALE, None)
geo_tags_dict.pop(TAG_MODEL_TIEPOINT, None)
# Compression tag for predictor
pred_val = predictor if compression != COMPRESSION_NONE else 1
# Build IFDs for each resolution level
ifd_specs = []
for level_idx, (arr, lw, lh, rel_offsets, byte_counts, comp_data) in enumerate(pixel_data_parts):
tags = []
# Mark overview IFDs as reduced-resolution images (TIFF tag 254).
# GDAL/rasterio use this tag to identify overview sub-IFDs.
if level_idx > 0:
tags.append((TAG_NEW_SUBFILE_TYPE, LONG, 1, 1))
tags.append((TAG_IMAGE_WIDTH, LONG, 1, lw))
tags.append((TAG_IMAGE_LENGTH, LONG, 1, lh))
if samples_per_pixel > 1:
tags.append((TAG_BITS_PER_SAMPLE, SHORT, samples_per_pixel,
[bits_per_sample] * samples_per_pixel))
else:
tags.append((TAG_BITS_PER_SAMPLE, SHORT, 1, bits_per_sample))
tags.append((TAG_COMPRESSION, SHORT, 1, compression))
# Photometric: RGB for 3+ bands, BlackIsZero for single-band
photometric = 2 if samples_per_pixel >= 3 else 1
tags.append((TAG_PHOTOMETRIC, SHORT, 1, photometric))
tags.append((TAG_SAMPLES_PER_PIXEL, SHORT, 1, samples_per_pixel))
if samples_per_pixel > 1:
tags.append((TAG_SAMPLE_FORMAT, SHORT, samples_per_pixel,
[sample_format] * samples_per_pixel))
else:
tags.append((TAG_SAMPLE_FORMAT, SHORT, 1, sample_format))
# ExtraSamples: for bands beyond what Photometric accounts for
# Photometric=2 (RGB) accounts for 3 bands; any extra are alpha/other
if photometric == 2 and samples_per_pixel > 3:
n_extra = samples_per_pixel - 3
# 2 = unassociated alpha for the first extra, 0 = unspecified for rest
extra_vals = [2] + [0] * (n_extra - 1)
tags.append((TAG_EXTRA_SAMPLES, SHORT, n_extra, extra_vals))
elif photometric == 1 and samples_per_pixel > 1:
n_extra = samples_per_pixel - 1
extra_vals = [0] * n_extra # unspecified
tags.append((TAG_EXTRA_SAMPLES, SHORT, n_extra, extra_vals))
if pred_val != 1:
tags.append((TAG_PREDICTOR, SHORT, 1, pred_val))
# Resolution / DPI tags
if x_resolution is not None:
tags.append((TAG_X_RESOLUTION, RATIONAL, 1, x_resolution))
if y_resolution is not None:
tags.append((TAG_Y_RESOLUTION, RATIONAL, 1, y_resolution))
if resolution_unit is not None:
tags.append((TAG_RESOLUTION_UNIT, SHORT, 1, resolution_unit))
if tiled:
tags.append((TAG_TILE_WIDTH, SHORT, 1, tile_size))
tags.append((TAG_TILE_LENGTH, SHORT, 1, tile_size))
# Placeholder offsets/counts -- will be patched
tags.append((TAG_TILE_OFFSETS, LONG, len(rel_offsets), rel_offsets))
tags.append((TAG_TILE_BYTE_COUNTS, LONG, len(byte_counts), byte_counts))
else:
rows_per_strip = 256
if lh <= rows_per_strip:
rows_per_strip = lh
tags.append((TAG_ROWS_PER_STRIP, SHORT, 1, rows_per_strip))
tags.append((TAG_STRIP_OFFSETS, LONG, len(rel_offsets), rel_offsets))
tags.append((TAG_STRIP_BYTE_COUNTS, LONG, len(byte_counts), byte_counts))
# Geo tags only on first IFD
if level_idx == 0:
for gtag, gval in geo_tags_dict.items():
if gtag == TAG_MODEL_PIXEL_SCALE:
tags.append((gtag, DOUBLE, 3, list(gval)))
elif gtag == TAG_MODEL_TIEPOINT:
tags.append((gtag, DOUBLE, 6, list(gval)))
elif gtag == TAG_MODEL_TRANSFORMATION:
tags.append((gtag, DOUBLE, 16, list(gval)))
elif gtag == TAG_GEO_KEY_DIRECTORY:
tags.append((gtag, SHORT, len(gval), list(gval)))
elif gtag == TAG_GEO_ASCII_PARAMS:
tags.append((gtag, ASCII, len(str(gval)) + 1, str(gval)))
elif gtag == TAG_GDAL_NODATA:
tags.append((gtag, ASCII, len(str(gval)) + 1, str(gval)))
# GDALMetadata XML (tag 42112)
if gdal_metadata_xml is not None:
tags.append((TAG_GDAL_METADATA, ASCII,
len(gdal_metadata_xml) + 1, gdal_metadata_xml))
# Extra tags (pass-through from source file)
if extra_tags is not None:
# Compute existing tag IDs once; update as we append to keep
# this loop O(len(extra_tags) + len(tags)) instead of O(N*M).
# See issue #1657 for the filter rationale.
existing_ids = {t[0] for t in tags}
for etag_id, etype_id, ecount, evalue in extra_tags:
if (etag_id not in existing_ids
and etag_id not in _DANGEROUS_EXTRA_TAG_IDS):
tags.append((etag_id, etype_id, ecount, evalue))
existing_ids.add(etag_id)
ifd_specs.append(tags)
# --- Determine if BigTIFF is needed ---
# Classic TIFF uses 32-bit offsets (max ~4.29 GB). Estimate total file
# size including headers, IFDs, overflow data, and all pixel data.
# Switch to BigTIFF if any offset could exceed 2^32.
total_pixel_data = sum(sum(len(c) for c in chunks)
for _, _, _, _, _, chunks in pixel_data_parts)
# Conservative overhead estimate: header + IFDs + overflow + geo tags
num_levels = len(ifd_specs)
max_tags_per_ifd = max(len(tags) for tags in ifd_specs) if ifd_specs else 20
ifd_overhead = num_levels * (2 + 12 * max_tags_per_ifd + 4 + 1024) # ~1KB overflow per IFD
estimated_file_size = 8 + ifd_overhead + total_pixel_data
UINT32_MAX = 0xFFFFFFFF # 4,294,967,295
if force_bigtiff is not None:
bigtiff = force_bigtiff
else:
bigtiff = estimated_file_size > UINT32_MAX
header_size = 16 if bigtiff else 8
# In BigTIFF, StripOffsets / TileOffsets and their byte-count
# siblings must use 64-bit offsets. The ifd_specs above were
# built with LONG (uint32) because bigtiff wasn't yet decided;
# promote them to LONG8 here. This is the write-side counterpart
# of the 64-bit offset handling in _header.parse_ifd.
if bigtiff:
ifd_specs = [_promote_offsets_to_long8(tags) for tags in ifd_specs]
if is_cog and len(ifd_specs) > 1:
return _assemble_cog_layout(header_size, ifd_specs, pixel_data_parts,
bigtiff=bigtiff)
else:
return _assemble_standard_layout(header_size, ifd_specs, pixel_data_parts,
bigtiff=bigtiff)
# Tags whose LONG encoding must become LONG8 in BigTIFF output.
_BIGTIFF_OFFSET_TAGS = frozenset({
TAG_STRIP_OFFSETS,
TAG_STRIP_BYTE_COUNTS,
TAG_TILE_OFFSETS,
TAG_TILE_BYTE_COUNTS,
})
def _promote_offsets_to_long8(tags: list) -> list:
"""Retype strip/tile offset and byte-count tags from LONG to LONG8.
Used when switching to BigTIFF output: 32-bit offsets cannot
address past 4 GB, so the offset arrays must be emitted as
LONG8 (uint64). Non-offset tags pass through unchanged.
"""
out = []
for tag_id, type_id, count, values in tags:
if tag_id in _BIGTIFF_OFFSET_TAGS and type_id == LONG:
out.append((tag_id, LONG8, count, values))
else:
out.append((tag_id, type_id, count, values))
return out
def _assemble_standard_layout(header_size: int,
ifd_specs: list,
pixel_data_parts: list,
bigtiff: bool = False) -> bytes:
"""Assemble standard TIFF layout (one IFD at a time)."""
output = bytearray()
entry_size = 20 if bigtiff else 12
# TIFF header
output.extend(b'II') # little-endian
if bigtiff:
output.extend(struct.pack(f'{BO}H', 43)) # BigTIFF magic
output.extend(struct.pack(f'{BO}H', 8)) # offset size
output.extend(struct.pack(f'{BO}H', 0)) # padding
output.extend(struct.pack(f'{BO}Q', 0)) # first IFD offset placeholder
else:
output.extend(struct.pack(f'{BO}H', 42)) # magic
output.extend(struct.pack(f'{BO}I', 0)) # first IFD offset placeholder
for level_idx, (tags, (_arr, _lw, _lh, rel_offsets, byte_counts, comp_chunks)) in enumerate(
zip(ifd_specs, pixel_data_parts)):
ifd_offset = len(output)
if level_idx == 0:
if bigtiff:
struct.pack_into(f'{BO}Q', output, 8, ifd_offset)
else:
struct.pack_into(f'{BO}I', output, 4, ifd_offset)
num_entries = len(tags)
count_size = 8 if bigtiff else 2
next_size = 8 if bigtiff else 4
ifd_block_size = count_size + entry_size * num_entries + next_size
overflow_base = ifd_offset + ifd_block_size