[GIS] rasterio “invalid dtype: ‘bool'”

gdalpythonrasterrasterio

I want to write a binary raster to disk. I have the numpy array whose dtype is:

dtype('bool')

I try to open a GTiff for writing:

img_output = rasterio.open(
            "../../binary_output.tif",
            'w',
            driver='GTiff',
            nodata=nd,
            height=self.raster.height,
            width = self.raster.width,
            count=1,
            dtype = binary_raster.dtype,
            crs=self.raster.crs,
            transform=self.raster.transform,)  

But I end up with:

TypeError: invalid dtype: 'bool'

I have also tried things like:

dtype = bool
dtype = 'bool'
dtype = "bool"

What is the problem with this? According to the docs, dtype can be any numpy dtype. How do I write a binary raster?

Best Answer

Yes, you can write a one bit raster with rasterio*.

You need to:

  1. write to a format that supports a 1bit dataset, such as GeoTIFF;
  2. ensure your numpy array is np.uint8/ubyte so rasterio doesnt raise the TypeError: invalid dtype: 'bool' exception; and
  3. pass the NBITS=1 creation option to tell the underlying GDAL GeoTIFF driver to create a one bit file.
import numpy as np
import rasterio as rio

with rio.open('test_byte.tif') as src:
    data = src.read()
    profile = src.profile

with rio.open('test_bit.tif', 'w', nbits=1, **profile) as dst:
    dst.write(data)
    # If your array is not a byte dtype, you need to cast it as ubyte/uint8
    # dst.write(data.astype(np.uint8))

Checking output file size

$ ls -sh test_bit.tif
228K test_bit.tif

$ ls -sh test_byte.tif
1.8M test_byte.tif

$ gdalinfo test_bit.tif
Driver: GTiff/GeoTIFF
Files: test_bit.tif
Size is 1588, 1167
<snip...>
Band 1 Block=1588x41 Type=Byte, ColorInterp=Palette
  Image Structure Metadata:
    NBITS=1

$ gdalinfo test_byte.tif
Driver: GTiff/GeoTIFF
Files: test_byte.tif
Size is 1588, 1167
<snip...>
Band 1 Block=1588x5 Type=Byte, ColorInterp=Gray

Related Question