1+ #= =========================================================================================+
2+ | TABLE OF CONTENTS: |
3+ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4+ | - readtiff |
5+ +==========================================================================================#
6+
7+ export readtiff
8+
9+ """
10+ readtiff(filename::String, dst_crs::String="EPSG:3857")
11+
12+ Description:
13+ ---
14+ Reads a GeoTIFF file and returns the pixel coordinates and values as a 3D array
15+ with shape (3, N), where N is the number of pixels. `dst_crs` specifies the destination
16+ coordinate reference system (CRS) for the output coordinates. The default CRS is "EPSG:3857"
17+ (Web Mercator).
18+
19+ Example:
20+ ---
21+ ```julia
22+ xyz = readtiff("example.tiff")
23+ #or
24+ xyz = readtiff("example.tif")
25+ ```
26+ """
27+ function readtiff (filename:: String ; dst_crs:: String = " EPSG:3857" )
28+ isfile (filename) || throw (ArgumentError (" file not found: $filename " ))
29+ if endswith (filename, " .tif" )
30+ filename *= " f" # ensure .tiff extension
31+ end
32+ endswith (filename, " .tiff" ) || error (" filename must be a .tif file" )
33+
34+ @pyexec """
35+ def py_tmp(tif_path, dst_crs, rasterio, np):
36+ with rasterio.open(tif_path) as src:
37+ transform, width, height = rasterio.warp.calculate_default_transform(
38+ src.crs, dst_crs, src.width, src.height, *src.bounds)
39+ kwargs = src.meta.copy()
40+ kwargs.update({
41+ 'crs': dst_crs,
42+ 'transform': transform,
43+ 'width': width,
44+ 'height': height
45+ })
46+ data = np.empty((height, width), dtype=src.dtypes[0])
47+ rasterio.warp.reproject(
48+ source=rasterio.band(src, 1),
49+ destination=data,
50+ src_transform=src.transform,
51+ src_crs=src.crs,
52+ dst_transform=transform,
53+ dst_crs=dst_crs,
54+ resampling=rasterio.warp.Resampling.bilinear
55+ )
56+ nodata = kwargs.get('nodata', None)
57+ H, W = data.shape
58+ rows, cols = np.indices((H, W))
59+ rows = rows.ravel()
60+ cols = cols.ravel()
61+ zs = data.ravel().astype(np.float32)
62+ if nodata is not None:
63+ zs[zs == nodata] = np.nan
64+ xs, ys = rasterio.transform.xy(transform, rows, cols)
65+ xs = np.array(xs)
66+ ys = np.array(ys)
67+ xyz = np.column_stack([xs, ys, zs])
68+ return xyz.T
69+ """ => py_tmp
70+
71+ return py2ju (Array, py_tmp (filename, dst_crs, rasterio, np))
72+ end
0 commit comments