Read a file#

Open a GeoTIFF, read its pixels into CuPy, and inspect its georeferencing. This tutorial uses a small Landsat 7 ETM sample distributed by Rasterio, with three RGB bands and approximately 300-metre pixels.

If you know the Rasterio quickstart, the dataset properties, one-based band indexes and read pattern will be familiar. Here, pixel reads return GPU arrays and array processing uses CuPy.

Prepare the environment#

You need an NVIDIA GPU, CuPy and cugeo-raster built with the nvtiff native feature. Follow the GPU installation recipe using the nvTIFF build. Python extras supply dependencies; the native feature must also be enabled when building the package.

The following blocks show one Python session. Lines beginning with >>> or ... are commands; the unprefixed lines are their output. Use the environment where you installed the GPU build, and start Python from the repository root. Keep the current CuPy device and stream unchanged during this exercise.

Download the sample image#

Download Rasterio’s 1.7 MB RGB sample from its pinned 1.4.4 release into a temporary directory:

>>> from pathlib import Path
>>> from tempfile import TemporaryDirectory
>>> from urllib.request import urlretrieve
>>> sample_dir = TemporaryDirectory()
>>> source_path = Path(sample_dir.name) / "RGB.byte.tif"
>>> url = ("https://raw.githubusercontent.com/rasterio/rasterio/"
...        "1.4.4/tests/data/RGB.byte.tif")
>>> _ = urlretrieve(url, source_path)

The file is downloaded unchanged; no GDAL, Rasterio or AWS credentials are needed. Keep sample_dir alive while using the file. Its temporary directory is removed when you call sample_dir.cleanup() or release the object.

Open the dataset#

>>> import cupy as cp
>>> import cugeo.raster as raster
>>> src = raster.open(source_path)
>>> src.closed
False

Opening the file reads its metadata. Pixel decoding happens when you call read().

Inspect the number of bands, image dimensions and stored sample types:

>>> src.count, src.width, src.height
(3, 791, 718)
>>> src.dtypes
('uint8', 'uint8', 'uint8')

The image has three bands, 791 columns and 718 rows. All three bands store uint8 samples. Band indexes start at one; array indexes start at zero.

Read pixels#

By default, read() allocates GPU memory and returns a CuPy array containing the decoded pixels. Calling it without a band index reads all bands:

>>> pixels = src.read()
>>> type(pixels)
<class 'cupy.ndarray'>
>>> pixels.shape
(3, 718, 791)
>>> pixels.dtype
dtype('uint8')
>>> pixels.device
<CUDA Device 0>

The result has shape (3, 718, 791) and dtype uint8. The axes are (bands, rows, columns), and device identifies the GPU holding its data.

RGB Landsat sample showing islands and shallow coastal waters.

The sample image displayed as RGB. Its three bands store red, green and blue values; the preview uses the original 0–255 display range.#

The black border is missing data. The file declares zero as the nodata value for each band: a zero sample is invalid in that band, independently of the other two bands.

>>> src.nodata
0.0

The image also contains some zero-valued dark pixels. Continue with Calculate statistics over valid pixels to see how the file’s validity masks affect a calculation.

The array’s logical axes do not specify its physical storage order. Inspect strides to find the byte step along each axis:

>>> pixels.strides
(1, 2373, 3)

The GeoTIFF stores samples in BIP (band interleaved by pixel) order, and this read preserves that physical order. Adjacent band values are one byte (8 bits) apart, and adjacent pixels are three bytes apart. The row stride is 2373 = 791 columns × 3 bands × 1 byte. CuPy operations use these strides. See memory layouts for the storage conventions.

For window selection and resizing, see the window read how-to. For CUDA stream handling with caller-owned tensors, see the PyTorch read how-to.

Band indexes are one-based for compatibility with GDAL and Rasterio: read(1) reads the first band. An integer band index removes the band axis:

>>> band1 = src.read(1)
>>> band1.shape
(718, 791)

Inspect the red, green and blue samples at row 500, column 500:

>>> pixels[:, 500, 500]
array([21, 26, 31], dtype=uint8)

Displaying a CuPy array waits for GPU work and copies data to the host for formatting. The image array remains on the GPU.

Locate the image#

A raster’s coordinate reference system (CRS) identifies its map coordinates. Its affine transform maps pixel columns and rows to positions in that CRS.

>>> src.crs.to_string()
'EPSG:32618'
>>> src.transform
Affine(300.0379266750948, 0.0, 101985.0,
       0.0, -300.041782729805, 2826915.0)
>>> src.bounds
BoundingBox(left=101985.0, bottom=2611485.0, right=339315.0, top=2826915.0)

The sample uses EPSG:32618, WGS 84 / UTM zone 18N, with coordinates in metres. The transform places pixel corners on the map. Each step to the right adds about 300 metres to X; each step down subtracts about 300 metres from Y. The bounds describe the outer edges of the image.

An array index such as (row=0, column=0) selects the first pixel. In the continuous pixel coordinates used by the transform, (0, 0) is that pixel’s upper-left corner (a vertex), and (0.5, 0.5) is its centre.

A pixel grid whose upper-left corner has easting 101985 metres and northing 2826915 metres. Each column adds about 300.04 metres to easting; each row subtracts about 300.04 metres from northing.

The transform’s offsets locate the upper-left pixel corner. Its scales give the change in map coordinates for one column or row. The grid shows a few pixels, with distances rounded for display.#

xy() takes a (row, column) index and returns the pixel’s centre by default. Pass offset="ul" to get its upper-left corner instead. For the first pixel:

>>> x, y = src.xy(0, 0)
>>> round(x, 2), round(y, 2)
(102135.02, 2826764.98)
>>> src.xy(0, 0, offset="ul")
(101985.0, 2826915.0)
>>> src.index(x, y)
(0, 0)

The centre is half a pixel to the right and down from the corner; its map coordinates are rounded to two decimal places above. index(x, y) returns the (row, column) of the pixel containing that map position. Both positions and the inverse lookup come from the grid metadata, without reading pixels.

Close the dataset when you have finished reading. The CuPy arrays remain valid after it closes. Remove the temporary download when you have finished with it:

>>> src.close()
>>> src.closed
True
>>> sample_dir.cleanup()

Continue with Write a file to create a GeoTIFF from synthetic GPU data, or Reproject an image to convert map coordinates to longitude and latitude and put the pixels on a new grid.