-
Notifications
You must be signed in to change notification settings - Fork 538
/
Copy path_io.pyx
2511 lines (2049 loc) · 88.4 KB
/
_io.pyx
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
# cython: boundscheck=False
"""Rasterio input/output."""
from enum import Enum, IntEnum
from collections import Counter
from contextlib import contextmanager, ExitStack
import logging
import os
import sys
from uuid import uuid4
import warnings
import attr
import numpy as np
from rasterio._base import tastes_like_gdal
from rasterio._base cimport open_dataset
from rasterio._env import catch_errors
from rasterio._err import (
GDALError, CPLE_AppDefinedError, CPLE_OpenFailedError, CPLE_IllegalArgError, CPLE_BaseError,
CPLE_AWSObjectNotFoundError, CPLE_HttpResponseError, stack_errors)
from rasterio.crs import CRS
from rasterio import dtypes
from rasterio.enums import ColorInterp, MaskFlags, Resampling
from rasterio.errors import (
CRSError, DriverRegistrationError, RasterioIOError,
NotGeoreferencedWarning, NodataShadowWarning, WindowError,
UnsupportedOperation, OverviewCreationError, RasterBlockError, InvalidArrayError,
StatisticsError, RasterioDeprecationWarning
)
from rasterio.dtypes import is_ndarray, _is_complex_int, _getnpdtype, _gdal_typename, _get_gdal_dtype
from rasterio.sample import sample_gen
from rasterio.transform import Affine
from rasterio._path import _parse_path, _UnparsedPath
from rasterio.vrt import _boundless_vrt_doc
from rasterio.windows import Window, intersection
from libc.stdio cimport FILE
from rasterio.enums import Resampling
from rasterio.env import GDALVersion
from rasterio.errors import ResamplingAlgorithmError, DatasetIOShapeError
from rasterio._base cimport get_driver_name, DatasetBase
from rasterio._err cimport exc_wrap_int, exc_wrap_pointer, exc_wrap_vsilfile, StackChecker
cimport numpy as np
np.import_array()
log = logging.getLogger(__name__)
def validate_resampling(resampling):
"""Validate that the resampling method is compatible of reads/writes."""
if resampling != Resampling.rms and resampling > 7:
raise ResamplingAlgorithmError("{!r} can be used for warp operations but not for reads and writes".format(Resampling(resampling)))
cdef int io_band(GDALRasterBandH band, int mode, double x0, double y0,
double width, double height, object data, int resampling=0) except -1:
"""Read or write a region of data for the band.
Implicit are
1) data type conversion if the dtype of `data` and `band` differ.
2) decimation if `data` and `band` shapes differ.
The striding of `data` is passed to GDAL so that it can navigate
the layout of ndarray views.
"""
validate_resampling(resampling)
# GDAL handles all the buffering indexing, so a typed memoryview,
# as in previous versions, isn't needed.
cdef void *buf = <void *>np.PyArray_DATA(data)
cdef int bufxsize = data.shape[1]
cdef int bufysize = data.shape[0]
cdef GDALDataType buftype = _get_gdal_dtype(data.dtype.name)
cdef GSpacing bufpixelspace = data.strides[1]
cdef GSpacing buflinespace = data.strides[0]
cdef int xoff = <int>x0
cdef int yoff = <int>y0
cdef int xsize = <int>width
cdef int ysize = <int>height
cdef int retval = 3
cdef StackChecker checker
cdef GDALRasterIOExtraArg extras
extras.nVersion = 1
extras.eResampleAlg = <GDALRIOResampleAlg>resampling
extras.bFloatingPointWindowValidity = 1
extras.dfXOff = x0
extras.dfYOff = y0
extras.dfXSize = width
extras.dfYSize = height
extras.pfnProgress = NULL
extras.pProgressData = NULL
with stack_errors() as checker:
with nogil:
retval = GDALRasterIOEx(
band, <GDALRWFlag>mode, xoff, yoff, xsize, ysize, buf, bufxsize, bufysize,
buftype, bufpixelspace, buflinespace, &extras)
return checker.exc_wrap_int(retval)
cdef int io_multi_band(GDALDatasetH hds, int mode, double x0, double y0,
double width, double height, object data,
Py_ssize_t[:] indexes, int resampling=0) except -1:
"""Read or write a region of data for multiple bands.
Implicit are
1) data type conversion if the dtype of `data` and bands differ.
2) decimation if `data` and band shapes differ.
The striding of `data` is passed to GDAL so that it can navigate
the layout of ndarray views.
"""
validate_resampling(resampling)
cdef StackChecker checker
cdef int i = 0
cdef int retval = 3
cdef int *bandmap = NULL
cdef void *buf = <void *>np.PyArray_DATA(data)
cdef int bufxsize = data.shape[2]
cdef int bufysize = data.shape[1]
cdef GDALDataType buftype = _get_gdal_dtype(data.dtype.name)
cdef GSpacing bufpixelspace = data.strides[2]
cdef GSpacing buflinespace = data.strides[1]
cdef GSpacing bufbandspace = data.strides[0]
cdef int count = len(indexes)
cdef int xoff = <int>x0
cdef int yoff = <int>y0
cdef int xsize = <int>max(1, width)
cdef int ysize = <int>max(1, height)
cdef GDALRasterIOExtraArg extras
extras.nVersion = 1
extras.eResampleAlg = <GDALRIOResampleAlg>resampling
extras.bFloatingPointWindowValidity = 1
extras.dfXOff = x0
extras.dfYOff = y0
extras.dfXSize = width
extras.dfYSize = height
extras.pfnProgress = NULL
extras.pProgressData = NULL
if len(indexes) != data.shape[0]:
raise DatasetIOShapeError("Dataset indexes and destination buffer are mismatched")
bandmap = <int *>CPLMalloc(count*sizeof(int))
for i in range(count):
bandmap[i] = <int>indexes[i]
IF (CTE_GDAL_MAJOR_VERSION, CTE_GDAL_MINOR_VERSION, CTE_GDAL_PATCH_VERSION) >= (3, 6, 0) and (CTE_GDAL_MAJOR_VERSION, CTE_GDAL_MINOR_VERSION, CTE_GDAL_PATCH_VERSION) < (3, 7, 1):
# Workaround for https://github.com/rasterio/rasterio/issues/2847
# (bug when reading TIFF PlanarConfiguration=Separate images with
# multi-threading)
# To be removed when GDAL >= 3.7.1 is required
cdef const char* interleave = NULL
cdef GDALDriverH driver = NULL
cdef const char* driver_name = NULL
cdef GDALRasterBandH band = NULL
if CPLGetConfigOption("GDAL_NUM_THREADS", NULL):
interleave = GDALGetMetadataItem(hds, "INTERLEAVE", "IMAGE_STRUCTURE")
if interleave and interleave == b"BAND":
driver = GDALGetDatasetDriver(hds)
if driver:
driver_name = GDALGetDescription(driver)
if driver_name and driver_name == b"GTiff":
try:
for i in range(count):
band = GDALGetRasterBand(hds, bandmap[i])
if band == NULL:
raise ValueError("Null band")
with stack_errors() as checker:
with nogil:
retval = GDALRasterIOEx(
band,
<GDALRWFlag>mode, xoff, yoff, xsize, ysize,
<void *>(<char *>buf + i * bufbandspace),
bufxsize, bufysize, buftype,
bufpixelspace, buflinespace, &extras)
checker.exc_wrap_int(retval)
return 0
finally:
CPLFree(bandmap)
# Chain errors coming from GDAL.
try:
with stack_errors() as checker:
with nogil:
retval = GDALDatasetRasterIOEx(
hds, <GDALRWFlag>mode, xoff, yoff, xsize, ysize, buf,
bufxsize, bufysize, buftype, count, bandmap,
bufpixelspace, buflinespace, bufbandspace, &extras)
return checker.exc_wrap_int(retval)
finally:
CPLFree(bandmap)
cdef int io_multi_mask(GDALDatasetH hds, int mode, double x0, double y0,
double width, double height, object data,
Py_ssize_t[:] indexes, int resampling=0) except -1:
"""Read or write a region of data for multiple band masks.
Implicit are
1) data type conversion if the dtype of `data` and bands differ.
2) decimation if `data` and band shapes differ.
The striding of `data` is passed to GDAL so that it can navigate
the layout of ndarray views.
"""
validate_resampling(resampling)
cdef int i = 0
cdef int j = 0
cdef int retval = 3
cdef GDALRasterBandH band = NULL
cdef GDALRasterBandH hmask = NULL
cdef void *buf = NULL
cdef int bufxsize = data.shape[2]
cdef int bufysize = data.shape[1]
cdef GDALDataType buftype = _get_gdal_dtype(data.dtype.name)
cdef GSpacing bufpixelspace = data.strides[2]
cdef GSpacing buflinespace = data.strides[1]
cdef int count = len(indexes)
cdef int xoff = <int>x0
cdef int yoff = <int>y0
cdef int xsize = <int>max(1, width)
cdef int ysize = <int>max(1, height)
cdef StackChecker checker
cdef GDALRasterIOExtraArg extras
extras.nVersion = 1
extras.eResampleAlg = <GDALRIOResampleAlg>resampling
extras.bFloatingPointWindowValidity = 1
extras.dfXOff = x0
extras.dfYOff = y0
extras.dfXSize = width
extras.dfYSize = height
extras.pfnProgress = NULL
extras.pProgressData = NULL
if len(indexes) != data.shape[0]:
raise DatasetIOShapeError("Dataset indexes and destination buffer are mismatched")
for i in range(count):
j = <int>indexes[i]
band = GDALGetRasterBand(hds, j)
if band == NULL:
raise ValueError("Null band")
hmask = GDALGetMaskBand(band)
if hmask == NULL:
raise ValueError("Null mask band")
buf = <void *>np.PyArray_DATA(data[i])
if buf == NULL:
raise ValueError("NULL data")
with stack_errors() as checker:
with nogil:
retval = GDALRasterIOEx(
hmask, <GDALRWFlag>mode, xoff, yoff, xsize, ysize, buf, bufxsize,
bufysize, <GDALDataType>1, bufpixelspace, buflinespace, &extras)
retval = checker.exc_wrap_int(retval)
return retval
cdef _delete_dataset_if_exists(path):
"""Delete a dataset if it already exists.
This operates at a lower level than a:
if rasterio.shutil.exists(path):
rasterio.shutil.delete(path)
and can take some shortcuts.
Parameters
----------
path : str
Dataset path.
Returns
-------
None
"""
cdef GDALDatasetH dataset = NULL
cdef GDALDriverH driver = NULL
cdef const char *path_c = NULL
try:
with catch_errors():
dataset = open_dataset(path, 0x40, None, None, None)
except (CPLE_OpenFailedError, CPLE_AWSObjectNotFoundError, CPLE_HttpResponseError) as exc:
log.debug("Skipped delete for overwrite, dataset does not exist: %r", path)
else:
driver = GDALGetDatasetDriver(dataset)
GDALClose(dataset)
dataset = NULL
if driver != NULL:
path_b = path.encode("utf-8")
path_c = path_b
with nogil:
err = GDALDeleteDataset(driver, path_c)
exc_wrap_int(err)
finally:
if dataset != NULL:
GDALClose(dataset)
cdef bint in_dtype_range(value, dtype):
"""Returns True if value is in the range of dtype, else False."""
infos = {
'c': np.finfo,
'f': np.finfo,
'i': np.iinfo,
'u': np.iinfo,
# Cython 0.22 returns dtype.kind as an int and will not cast to a char
99: np.finfo,
102: np.finfo,
105: np.iinfo,
117: np.iinfo}
key = _getnpdtype(dtype).kind
if np.isnan(value):
return key in ('c', 'f', 99, 102)
if key == "f" and np.isinf(value):
return True
rng = infos[key](dtype)
return rng.min <= value <= rng.max
cdef int io_auto(data, GDALRasterBandH band, bint write, int resampling=0) except -1:
"""Convenience function to handle IO with a GDAL band.
:param data: a numpy.ndarray
:param band: an instance of GDALGetRasterBand
:param write: 1 (True) uses write mode (writes data into band),
0 (False) uses read mode (reads band into data)
:return: the return value from the data-type specific IO function
"""
cdef int ndims = len(data.shape)
cdef float height = data.shape[-2]
cdef float width = data.shape[-1]
try:
if ndims == 2:
return io_band(band, write, 0.0, 0.0, width, height, data, resampling=resampling)
elif ndims == 3:
indexes = np.arange(1, data.shape[0] + 1, dtype='intp')
return io_multi_band(band, write, 0.0, 0.0, width, height, data, indexes, resampling=resampling)
else:
raise ValueError("Specified data must have 2 or 3 dimensions")
# TODO: don't handle, it's inconsistent with the other io_* functions.
except CPLE_BaseError as cplerr:
raise RasterioIOError(str(cplerr))
cdef char **convert_options(kwargs):
cdef char **options = NULL
tiled = kwargs.get("tiled", False) or kwargs.get("TILED", False)
if isinstance(tiled, str):
tiled = (tiled.lower() in ("true", "yes"))
for k, v in kwargs.items():
if k.lower() in ['affine']:
continue
elif k in ['BLOCKXSIZE'] and not tiled:
continue
# Special cases for enums and tuples.
elif isinstance(v, (IntEnum, Enum)):
v = v.name.upper()
elif isinstance(v, tuple):
v = ",".join([str(it) for it in v])
k, v = k.upper(), str(v)
key_b = k.encode('utf-8')
val_b = v.encode('utf-8')
key_c = key_b
val_c = val_b
options = CSLSetNameValue(options, key_c, val_c)
return options
@attr.s(slots=True, frozen=True)
class Statistics:
"""Raster band statistics.
Attributes
----------
min, max, mean, std : float
Basic stats of a raster band.
"""
min = attr.ib()
max = attr.ib()
mean = attr.ib()
std = attr.ib()
cdef class DatasetReaderBase(DatasetBase):
"""Provides data and metadata reading methods."""
def read(self, indexes=None, out=None, window=None, masked=False,
out_shape=None, boundless=False, resampling=Resampling.nearest,
fill_value=None, out_dtype=None):
"""Read band data and, optionally, mask as an array.
A smaller (or larger) region of the dataset may be specified and
it may be resampled and/or converted to a different data type.
Parameters
----------
indexes : int or list, optional
If `indexes` is a list, the result is a 3D array, but is
a 2D array if it is a band index number.
out : numpy.ndarray, optional
As with Numpy ufuncs, this is an optional reference to an
output array into which data will be placed. If the height
and width of `out` differ from that of the specified
window (see below), the raster image will be decimated or
replicated using the specified resampling method (also see
below). This parameter cannot be combined with `out_shape`.
*Note*: the method's return value may be a view on this
array. In other words, `out` is likely to be an
incomplete representation of the method's results.
out_dtype : str or numpy.dtype
The desired output data type. For example: 'uint8' or
rasterio.uint16.
out_shape : tuple, optional
A tuple describing the shape of a new output array. See
`out` (above) for notes on image decimation and replication.
This parameter cannot be combined with `out`.
window : Window, optional
The region (slice) of the dataset from which data will be
read. The default is the entire dataset.
masked : bool, optional
If `masked` is `True` the return value will be a masked
array. Otherwise (the default) the return value will be a
regular array. Masks will be exactly the inverse of the
GDAL RFC 15 conforming arrays returned by read_masks().
boundless : bool, optional (default `False`)
If `True`, windows that extend beyond the dataset's extent
are permitted and partially or completely filled arrays will
be returned as appropriate.
resampling : Resampling
By default, pixel values are read raw or interpolated using
a nearest neighbor algorithm from the band cache. Other
resampling algorithms may be specified. Resampled pixels
are not cached.
fill_value : scalar
Fill value applied in the `boundless=True` case only. Like
the fill_value of :class:`numpy.ma.MaskedArray`, should be value
valid for the dataset's data type.
Returns
-------
Numpy ndarray or a view on a Numpy ndarray
Raises
------
RasterioIOError
If the write fails.
Notes
-----
This data is read from the dataset's band cache, which means
that repeated reads of the same windows may avoid I/O.
As with Numpy ufuncs, an object is returned even if you use the
optional `out` argument and the return value shall be
preferentially used by callers.
"""
cdef GDALRasterBandH band = NULL
if self.mode == "w":
raise UnsupportedOperation("not readable")
return2d = False
if indexes is None:
indexes = self.indexes
elif isinstance(indexes, int):
indexes = [indexes]
return2d = True
if out is not None and out.ndim == 2:
out.shape = (1,) + out.shape
if not indexes:
raise ValueError("No indexes to read")
check_dtypes = set()
nodatavals = []
# Check each index before processing 3D array
for bidx in indexes:
if bidx not in self.indexes:
raise IndexError("band index {} out of range (not in {})".format(bidx, self.indexes))
idx = self.indexes.index(bidx)
dtype = self.dtypes[idx]
check_dtypes.add(dtype)
ndv = self._nodatavals[idx]
log.debug("Output nodata value read from file: %r", ndv)
if ndv is not None and not _is_complex_int(dtype):
kind = _getnpdtype(dtype).kind
if kind in "iu":
info = np.iinfo(dtype)
dt_min, dt_max = info.min, info.max
elif kind in "cf":
info = np.finfo(dtype)
dt_min, dt_max = info.min, info.max
else:
dt_min, dt_max = False, True
if ndv < dt_min:
ndv = dt_min
elif ndv > dt_max:
ndv = dt_max
nodatavals.append(ndv)
log.debug("Output nodata values: %r", nodatavals)
# Mixed dtype reads are not supported at this time.
if len(check_dtypes) > 1:
raise ValueError("more than one 'dtype' found")
elif len(check_dtypes) == 0:
dtype = self.dtypes[0]
else:
dtype = check_dtypes.pop()
if out_dtype is not None:
dtype = out_dtype
# Ensure we have a numpy dtype.
dtype = _getnpdtype(dtype)
# Get the natural shape of the read window, boundless or not.
# The window can have float values. In this case, we round up
# when computing the shape.
# Stub the win_shape.
win_shape = (len(indexes),)
if window:
if isinstance(window, tuple):
window = Window.from_slices(
*window, height=self.height, width=self.width,
boundless=boundless)
if not boundless:
window = window.crop(self.height, self.width)
int_window = window.round_lengths()
win_shape += (int(int_window.height), int(int_window.width))
else:
win_shape += self.shape
if out is not None and out_shape is not None:
raise ValueError("out and out_shape are exclusive")
# `out` takes precedence over `out_shape` and `out_dtype`.
elif out is not None:
if out.dtype != dtype:
dtype == out.dtype
if out.shape[0] != win_shape[0]:
raise ValueError("'out' shape {} does not match window shape {}".format(out.shape, win_shape))
else:
if out_shape is not None:
if len(out_shape) == 2:
out_shape = (len(indexes),) + out_shape
else:
out_shape = win_shape
# We're filling in both the bounded and boundless cases.
# TODO: profile and see if we should avoid this in the
# bounded case.
if boundless:
out = np.zeros(out_shape, dtype=dtype)
else:
out = np.empty(out_shape, dtype=dtype)
# Masking
# -------
#
# If masked is True, we check the GDAL mask flags using
# GDALGetMaskFlags. If GMF_ALL_VALID for all bands, we do not
# call read_masks(), but pass `mask=False` to the masked array
# constructor. Else, we read the GDAL mask bands using
# read_masks(), invert them and use them in constructing masked
# arrays.
enums = self.mask_flag_enums
all_valid = all([MaskFlags.all_valid in flags for flags in enums])
log.debug("all_valid: %s", all_valid)
log.debug("mask_flags: %r", enums)
# We can jump straight to _read() in some cases. We can ignore
# the boundless flag if there's no given window.
if not boundless or not window:
log.debug("Jump straight to _read()")
log.debug("Window: %r", window)
out = self._read(indexes, out, window, dtype, resampling=resampling)
if masked or fill_value is not None:
if all_valid:
mask = np.ma.nomask
else:
mask = np.zeros(out.shape, 'uint8')
mask = ~self._read(
indexes, mask, window, 'uint8', masks=True,
resampling=resampling).astype('bool')
kwds = {'mask': mask}
# Set a fill value only if the read bands share a
# single nodata value.
if fill_value is not None:
kwds['fill_value'] = fill_value
elif len(set(nodatavals)) == 1:
if nodatavals[0] is not None:
kwds['fill_value'] = nodatavals[0]
out = np.ma.array(out, **kwds)
if not masked:
out = out.filled(fill_value)
# If this is a boundless read we will create an in-memory VRT
# in order to use GDAL's windowing and compositing logic.
else:
if fill_value is not None:
nodataval = fill_value
else:
nodataval = ndv
vrt_doc = _boundless_vrt_doc(
self, nodata=nodataval, background=nodataval,
width=max(self.width, window.width) + 1,
height=max(self.height, window.height) + 1,
transform=self.window_transform(window),
resampling=resampling
)
vrt_kwds = {'driver': 'VRT'}
with DatasetReaderBase(_UnparsedPath(vrt_doc), **vrt_kwds) as vrt:
out = vrt._read(
indexes, out, Window(0, 0, window.width, window.height), None)
if masked:
# Below we use another VRT to compute the valid data mask
# in this special case where all source pixels are valid.
if all_valid:
log.debug("Boundless read: self.transform=%r, self.window_transform(window)=%r", self.transform, self.window_transform(window))
mask_vrt_doc = _boundless_vrt_doc(
self, nodata=0,
width=max(self.width, window.width) + 1,
height=max(self.height, window.height) + 1,
transform=self.window_transform(window),
masked=True,
resampling=resampling
)
with DatasetReaderBase(_UnparsedPath(mask_vrt_doc), **vrt_kwds) as mask_vrt:
mask = np.zeros(out.shape, 'uint8')
mask = ~mask_vrt._read(
indexes, mask, Window(0, 0, window.width, window.height), None).astype('bool')
else:
mask = np.zeros(out.shape, 'uint8')
window = Window(0, 0, window.width, window.height)
log.debug("Boundless read: window=%r", window)
mask = ~vrt._read(
indexes, mask, window, None, masks=True).astype('bool')
kwds = {'mask': mask}
# Set a fill value only if the read bands share a
# single nodata value.
if fill_value is not None:
kwds['fill_value'] = fill_value
elif len(set(nodatavals)) == 1:
if nodatavals[0] is not None:
kwds['fill_value'] = nodatavals[0]
log.debug("Boundless read: out=%r, mask=%r", out, mask)
out = np.ma.array(out, **kwds)
if return2d:
out.shape = out.shape[1:]
return out
def read_masks(self, indexes=None, out=None, out_shape=None, window=None,
boundless=False, resampling=Resampling.nearest):
"""Read band masks as an array.
A smaller (or larger) region of the dataset may be specified and
it may be resampled and/or converted to a different data type.
Parameters
----------
indexes : int or list, optional
If `indexes` is a list, the result is a 3D array, but is
a 2D array if it is a band index number.
out : numpy.ndarray, optional
As with Numpy ufuncs, this is an optional reference to an
output array into which data will be placed. If the height
and width of `out` differ from that of the specified
window (see below), the raster image will be decimated or
replicated using the specified resampling method (also see
below). This parameter cannot be combined with `out_shape`.
*Note*: the method's return value may be a view on this
array. In other words, `out` is likely to be an
incomplete representation of the method's results.
out_shape : tuple, optional
A tuple describing the shape of a new output array. See
`out` (above) for notes on image decimation and replication.
This parameter cannot be combined with `out`.
window : Window, optional
The region (slice) of the dataset from which data will be
read. The default is the entire dataset.
boundless : bool, optional (default `False`)
If `True`, windows that extend beyond the dataset's extent
are permitted and partially or completely filled arrays will
be returned as appropriate.
resampling : Resampling
By default, pixel values are read raw or interpolated using
a nearest neighbor algorithm from the band cache. Other
resampling algorithms may be specified. Resampled pixels
are not cached.
Returns
-------
Numpy ndarray or a view on a Numpy ndarray
Raises
------
RasterioIOError
If the write fails.
Notes
-----
This data is read from the dataset's band cache, which means
that repeated reads of the same windows may avoid I/O.
As with Numpy ufuncs, an object is returned even if you use the
optional `out` argument and the return value shall be
preferentially used by callers.
"""
if self.mode == "w":
raise UnsupportedOperation("not readable")
return2d = False
if indexes is None:
indexes = self.indexes
elif isinstance(indexes, int):
indexes = [indexes]
return2d = True
if out is not None and out.ndim == 2:
out.shape = (1,) + out.shape
if not indexes:
raise ValueError("No indexes to read")
# Get the natural shape of the read window, boundless or not.
# Stub the win_shape.
win_shape = (len(indexes),)
if window:
if isinstance(window, tuple):
window = Window.from_slices(
*window, height=self.height, width=self.width,
boundless=boundless)
if not boundless:
window = window.crop(self.height, self.width)
int_window = window.round_lengths()
win_shape += (int(int_window.height), int(int_window.width))
else:
win_shape += self.shape
dtype = 'uint8'
if out is not None and out_shape is not None:
raise ValueError("out and out_shape are exclusive")
elif out_shape is not None:
if len(out_shape) == 2:
out_shape = (len(indexes),) + out_shape
out = np.zeros(out_shape, 'uint8')
if out is not None:
if out.dtype != _getnpdtype(dtype):
raise ValueError(
"the out array's dtype '%s' does not match '%s'"
% (out.dtype, dtype))
if out.shape[0] != win_shape[0]:
raise ValueError(
"'out' shape %s does not match window shape %s" %
(out.shape, win_shape))
else:
out = np.zeros(win_shape, 'uint8')
# We can jump straight to _read() in some cases. We can ignore
# the boundless flag if there's no given window.
if not boundless or not window:
out = self._read(indexes, out, window, dtype, masks=True,
resampling=resampling)
# If this is a boundless read we will create an in-memory VRT
# in order to use GDAL's windowing and compositing logic.
else:
enums = self.mask_flag_enums
all_valid = all([MaskFlags.all_valid in flags for flags in enums])
vrt_kwds = {'driver': 'VRT'}
if all_valid:
blank_path = _UnparsedPath('/vsimem/blank-{}.tif'.format(uuid4()))
transform = Affine.translation(self.transform.xoff, self.transform.yoff) * (Affine.scale(self.width / 3, self.height / 3) * (Affine.translation(-self.transform.xoff, -self.transform.yoff) * self.transform))
with DatasetWriterBase(
blank_path, 'w',
driver='GTiff', count=self.count, height=3, width=3,
dtype='uint8', crs=self.crs, transform=transform) as blank_dataset:
blank_dataset.write(
np.full((self.count, 3, 3), 255, dtype='uint8'))
with DatasetReaderBase(blank_path) as blank_dataset:
mask_vrt_doc = _boundless_vrt_doc(
blank_dataset, nodata=0,
width=max(self.width, window.width) + 1,
height=max(self.height, window.height) + 1,
transform=self.window_transform(window),
resampling=resampling
)
with DatasetReaderBase(_UnparsedPath(mask_vrt_doc), **vrt_kwds) as mask_vrt:
out = np.zeros(out.shape, 'uint8')
out = mask_vrt._read(
indexes, out, Window(0, 0, window.width, window.height), None).astype('bool')
else:
vrt_doc = _boundless_vrt_doc(
self, width=max(self.width, window.width) + 1,
height=max(self.height, window.height) + 1,
transform=self.window_transform(window),
resampling=resampling
)
with DatasetReaderBase(_UnparsedPath(vrt_doc), **vrt_kwds) as vrt:
out = vrt._read(
indexes, out, Window(0, 0, window.width, window.height), None, masks=True)
if return2d:
out.shape = out.shape[1:]
return out
def _read(self, indexes, out, window, dtype, masks=False, resampling=Resampling.nearest):
"""Read raster bands as a multidimensional array
If `indexes` is a list, the result is a 3D array, but
is a 2D array if it is a band index number.
Optional `out` argument is a reference to an output array with the
same dimensions and shape.
See `read_band` for usage of the optional `window` argument.
The return type will be either a regular NumPy array, or a masked
NumPy array depending on the `masked` argument. The return type is
forced if either `True` or `False`, but will be chosen if `None`.
For `masked=None` (default), the array will be the same type as
`out` (if used), or will be masked if any of the nodatavals are
not `None`.
"""
cdef int aix, bidx, indexes_count
cdef double height, width, xoff, yoff
cdef int retval = 0
cdef GDALDatasetH dataset = NULL
if out is None:
raise ValueError("An output array is required.")
dataset = self.handle()
if window:
if not isinstance(window, Window):
raise WindowError("window must be an instance of Window")
yoff = window.row_off
xoff = window.col_off
width = window.width
height = window.height
else:
xoff = yoff = <int>0
width = <int>self.width
height = <int>self.height
log.debug(
"IO window xoff=%s yoff=%s width=%s height=%s",
xoff, yoff, width, height)
# Call io_multi* functions with C type args so that they
# can release the GIL.
indexes_arr = np.array(indexes, dtype='intp')
indexes_count = <int>indexes_arr.shape[0]
try:
if masks:
# Warn if nodata attribute is shadowing an alpha band.
if self.count == 4 and self.colorinterp[3] == ColorInterp.alpha:
for flags in self.mask_flag_enums:
if MaskFlags.nodata in flags:
warnings.warn(NodataShadowWarning())
io_multi_mask(self._hds, 0, xoff, yoff, width, height, out, indexes_arr, resampling=resampling.value)
else:
io_multi_band(self._hds, 0, xoff, yoff, width, height, out, indexes_arr, resampling=resampling.value)
except CPLE_BaseError as cplerr:
raise RasterioIOError("Read failed. See previous exception for details.") from cplerr
return out
def dataset_mask(self, out=None, out_shape=None, window=None,
boundless=False, resampling=Resampling.nearest):
"""Get the dataset's 2D valid data mask.
Parameters
----------
out : numpy.ndarray, optional
As with Numpy ufuncs, this is an optional reference to an
output array with the same dimensions and shape into which
data will be placed.
*Note*: the method's return value may be a view on this
array. In other words, `out` is likely to be an
incomplete representation of the method's results.
Cannot be combined with `out_shape`.
out_shape : tuple, optional
A tuple describing the output array's shape. Allows for decimated
reads without constructing an output Numpy array.
Cannot be combined with `out`.
window : a pair (tuple) of pairs of ints or Window, optional
The optional `window` argument is a 2 item tuple. The first