1Tagging datasets and bands 2========================== 3 4GDAL's `data model <https://gdal.org/user/raster_data_model.html>`__ includes 5collections of key, value pairs for major classes. In that model, these are 6"metadata", but since they don't have to be just for metadata, these key, value 7pairs are called "tags" in rasterio. 8 9Reading tags 10------------ 11 12I'm going to use the rasterio interactive inspector in these examples below. 13 14.. code-block:: console 15 16 $ rio insp tests/data/RGB.byte.tif 17 Rasterio 1.2.0 Interactive Inspector (Python 3.7.8) 18 Type "src.name", "src.read(1)", or "help(src)" for more information. 19 >>> 20 21Tags belong to namespaces. To get a copy of a dataset's tags from the default 22namespace, call ``tags()`` with no arguments. 23 24.. code-block:: pycon 25 26 >>> import rasterio 27 >>> src = rasterio.open("tests/data/RGB.byte.tif") 28 >>> src.tags() 29 {'AREA_OR_POINT': 'Area'} 30 31A dataset's bands may have tags, too. Here are the tags from the default namespace 32for the first band, accessed using the positional band index argument of ``tags()``. 33 34.. code-block:: pycon 35 36 >>> src.tags(1)['STATISTICS_MEAN'] 37 '29.947726688477' 38 39These are the tags that came with the sample data I'm using to test rasterio. In 40practice, maintaining stats in the tags can be unreliable as there is no automatic 41update of the tags when the band's image data changes. 42 43The 3 standard, non-default GDAL tag namespaces are 'SUBDATASETS', 'IMAGE_STRUCTURE', 44and 'RPC'. You can get the tags from these namespaces using the `ns` keyword of 45``tags()``. 46 47.. code-block:: pycon 48 49 >>> src.tags(ns='IMAGE_STRUCTURE') 50 {'INTERLEAVE': 'PIXEL'} 51 >>> src.tags(ns='SUBDATASETS') 52 {} 53 >>> src.tags(ns='RPC') 54 {} 55 56Writing tags 57------------ 58 59You can add new tags to a dataset or band, in the default or another namespace, 60using the ``update_tags()`` method. Unicode tag values, too, at least for TIFF 61files. 62 63.. code-block:: python 64 65 import rasterio 66 67 with rasterio.open( 68 '/tmp/test.tif', 69 'w', 70 driver='GTiff', 71 count=1, 72 dtype=rasterio.uint8, 73 width=10, 74 height=10) as dst: 75 76 dst.update_tags(a='1', b='2') 77 dst.update_tags(1, c=3) 78 with pytest.raises(ValueError): 79 dst.update_tags(4, d=4) 80 81 # True 82 assert dst.tags() == {'a': '1', 'b': '2'} 83 # True 84 assert dst.tags(1) == {'c': '3' } 85 86 dst.update_tags(ns='rasterio_testing', rus=u'другая строка') 87 # True 88 assert dst.tags(ns='rasterio_testing') == {'rus': u'другая строка'} 89 90As with image data, tags aren't written to the file on disk until the dataset 91is closed. 92