gdal.txt 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183
  1. ========
  2. GDAL API
  3. ========
  4. .. module:: django.contrib.gis.gdal
  5. :synopsis: GeoDjango's high-level interface to the GDAL library.
  6. `GDAL`__ stands for **Geospatial Data Abstraction Library**,
  7. and is a veritable "Swiss army knife" of GIS data functionality. A subset
  8. of GDAL is the `OGR`__ Simple Features Library, which specializes
  9. in reading and writing vector geographic data in a variety of standard
  10. formats.
  11. GeoDjango provides a high-level Python interface for some of the
  12. capabilities of OGR, including the reading and coordinate transformation
  13. of vector spatial data and minimal support for GDAL's features with respect
  14. to raster (image) data.
  15. .. note::
  16. Although the module is named ``gdal``, GeoDjango only supports some of the
  17. capabilities of OGR and GDAL's raster features at this time.
  18. __ https://gdal.org/
  19. __ https://gdal.org/user/vector_data_model.html
  20. Overview
  21. ========
  22. .. _gdal_sample_data:
  23. Sample Data
  24. -----------
  25. The GDAL/OGR tools described here are designed to help you read in
  26. your geospatial data, in order for most of them to be useful you have
  27. to have some data to work with. If you're starting out and don't yet
  28. have any data of your own to use, GeoDjango tests contain a number of
  29. data sets that you can use for testing. You can download them here:
  30. .. code-block:: shell
  31. $ wget https://raw.githubusercontent.com/django/django/main/tests/gis_tests/data/cities/cities.{shp,prj,shx,dbf}
  32. $ wget https://raw.githubusercontent.com/django/django/main/tests/gis_tests/data/rasters/raster.tif
  33. Vector Data Source Objects
  34. ==========================
  35. ``DataSource``
  36. --------------
  37. :class:`DataSource` is a wrapper for the OGR data source object that
  38. supports reading data from a variety of OGR-supported geospatial file
  39. formats and data sources using a consistent interface. Each
  40. data source is represented by a :class:`DataSource` object which contains
  41. one or more layers of data. Each layer, represented by a :class:`Layer`
  42. object, contains some number of geographic features (:class:`Feature`),
  43. information about the type of features contained in that layer (e.g.
  44. points, polygons, etc.), as well as the names and types of any
  45. additional fields (:class:`Field`) of data that may be associated with
  46. each feature in that layer.
  47. .. class:: DataSource(ds_input, encoding='utf-8')
  48. The constructor for ``DataSource`` only requires one parameter: the path of
  49. the file you want to read. However, OGR also supports a variety of more
  50. complex data sources, including databases, that may be accessed by passing
  51. a special name string instead of a path. For more information, see the
  52. `OGR Vector Formats`__ documentation. The :attr:`name` property of a
  53. ``DataSource`` instance gives the OGR name of the underlying data source
  54. that it is using.
  55. The optional ``encoding`` parameter allows you to specify a non-standard
  56. encoding of the strings in the source. This is typically useful when you
  57. obtain ``DjangoUnicodeDecodeError`` exceptions while reading field values.
  58. Once you've created your ``DataSource``, you can find out how many layers
  59. of data it contains by accessing the :attr:`layer_count` property, or
  60. (equivalently) by using the ``len()`` function. For information on
  61. accessing the layers of data themselves, see the next section:
  62. .. code-block:: pycon
  63. >>> from django.contrib.gis.gdal import DataSource
  64. >>> ds = DataSource("/path/to/your/cities.shp")
  65. >>> ds.name
  66. '/path/to/your/cities.shp'
  67. >>> ds.layer_count # This file only contains one layer
  68. 1
  69. .. attribute:: layer_count
  70. Returns the number of layers in the data source.
  71. .. attribute:: name
  72. Returns the name of the data source.
  73. __ https://gdal.org/drivers/vector/
  74. ``Layer``
  75. ---------
  76. .. class:: Layer
  77. ``Layer`` is a wrapper for a layer of data in a ``DataSource`` object. You
  78. never create a ``Layer`` object directly. Instead, you retrieve them from
  79. a :class:`DataSource` object, which is essentially a standard Python
  80. container of ``Layer`` objects. For example, you can access a specific
  81. layer by its index (e.g. ``ds[0]`` to access the first layer), or you can
  82. iterate over all the layers in the container in a ``for`` loop. The
  83. ``Layer`` itself acts as a container for geometric features.
  84. Typically, all the features in a given layer have the same geometry type.
  85. The :attr:`geom_type` property of a layer is an :class:`OGRGeomType` that
  86. identifies the feature type. We can use it to print out some basic
  87. information about each layer in a :class:`DataSource`:
  88. .. code-block:: pycon
  89. >>> for layer in ds:
  90. ... print('Layer "%s": %i %ss' % (layer.name, len(layer), layer.geom_type.name))
  91. ...
  92. Layer "cities": 3 Points
  93. The example output is from the cities data source, loaded above, which
  94. evidently contains one layer, called ``"cities"``, which contains three
  95. point features. For simplicity, the examples below assume that you've
  96. stored that layer in the variable ``layer``:
  97. .. code-block:: pycon
  98. >>> layer = ds[0]
  99. .. attribute:: name
  100. Returns the name of this layer in the data source.
  101. .. code-block:: pycon
  102. >>> layer.name
  103. 'cities'
  104. .. attribute:: num_feat
  105. Returns the number of features in the layer. Same as ``len(layer)``:
  106. .. code-block:: pycon
  107. >>> layer.num_feat
  108. 3
  109. .. attribute:: geom_type
  110. Returns the geometry type of the layer, as an :class:`OGRGeomType` object:
  111. .. code-block:: pycon
  112. >>> layer.geom_type.name
  113. 'Point'
  114. .. attribute:: num_fields
  115. Returns the number of fields in the layer, i.e the number of fields of
  116. data associated with each feature in the layer:
  117. .. code-block:: pycon
  118. >>> layer.num_fields
  119. 4
  120. .. attribute:: fields
  121. Returns a list of the names of each of the fields in this layer:
  122. .. code-block:: pycon
  123. >>> layer.fields
  124. ['Name', 'Population', 'Density', 'Created']
  125. .. attribute field_types
  126. Returns a list of the data types of each of the fields in this layer. These
  127. are subclasses of ``Field``, discussed below:
  128. .. code-block:: pycon
  129. >>> [ft.__name__ for ft in layer.field_types]
  130. ['OFTString', 'OFTReal', 'OFTReal', 'OFTDate']
  131. .. attribute:: field_widths
  132. Returns a list of the maximum field widths for each of the fields in this
  133. layer:
  134. .. code-block:: pycon
  135. >>> layer.field_widths
  136. [80, 11, 24, 10]
  137. .. attribute:: field_precisions
  138. Returns a list of the numeric precisions for each of the fields in this
  139. layer. This is meaningless (and set to zero) for non-numeric fields:
  140. .. code-block:: pycon
  141. >>> layer.field_precisions
  142. [0, 0, 15, 0]
  143. .. attribute:: extent
  144. Returns the spatial extent of this layer, as an :class:`Envelope` object:
  145. .. code-block:: pycon
  146. >>> layer.extent.tuple
  147. (-104.609252, 29.763374, -95.23506, 38.971823)
  148. .. attribute:: srs
  149. Property that returns the :class:`SpatialReference` associated with this
  150. layer:
  151. .. code-block:: pycon
  152. >>> print(layer.srs)
  153. GEOGCS["GCS_WGS_1984",
  154. DATUM["WGS_1984",
  155. SPHEROID["WGS_1984",6378137,298.257223563]],
  156. PRIMEM["Greenwich",0],
  157. UNIT["Degree",0.017453292519943295]]
  158. If the :class:`Layer` has no spatial reference information associated
  159. with it, ``None`` is returned.
  160. .. attribute:: spatial_filter
  161. Property that may be used to retrieve or set a spatial filter for this
  162. layer. A spatial filter can only be set with an :class:`OGRGeometry`
  163. instance, a 4-tuple extent, or ``None``. When set with something other than
  164. ``None``, only features that intersect the filter will be returned when
  165. iterating over the layer:
  166. .. code-block:: pycon
  167. >>> print(layer.spatial_filter)
  168. None
  169. >>> print(len(layer))
  170. 3
  171. >>> [feat.get("Name") for feat in layer]
  172. ['Pueblo', 'Lawrence', 'Houston']
  173. >>> ks_extent = (-102.051, 36.99, -94.59, 40.00) # Extent for state of Kansas
  174. >>> layer.spatial_filter = ks_extent
  175. >>> len(layer)
  176. 1
  177. >>> [feat.get("Name") for feat in layer]
  178. ['Lawrence']
  179. >>> layer.spatial_filter = None
  180. >>> len(layer)
  181. 3
  182. .. method:: get_fields()
  183. A method that returns a list of the values of a given field for each
  184. feature in the layer:
  185. .. code-block:: pycon
  186. >>> layer.get_fields("Name")
  187. ['Pueblo', 'Lawrence', 'Houston']
  188. .. method:: get_geoms(geos=False)
  189. A method that returns a list containing the geometry of each feature in the
  190. layer. If the optional argument ``geos`` is set to ``True`` then the
  191. geometries are converted to :class:`~django.contrib.gis.geos.GEOSGeometry`
  192. objects. Otherwise, they are returned as :class:`OGRGeometry` objects:
  193. .. code-block:: pycon
  194. >>> [pt.tuple for pt in layer.get_geoms()]
  195. [(-104.609252, 38.255001), (-95.23506, 38.971823), (-95.363151, 29.763374)]
  196. .. method:: test_capability(capability)
  197. Returns a boolean indicating whether this layer supports the given
  198. capability (a string). Examples of valid capability strings include:
  199. ``'RandomRead'``, ``'SequentialWrite'``, ``'RandomWrite'``,
  200. ``'FastSpatialFilter'``, ``'FastFeatureCount'``, ``'FastGetExtent'``,
  201. ``'CreateField'``, ``'Transactions'``, ``'DeleteFeature'``, and
  202. ``'FastSetNextByIndex'``.
  203. ``Feature``
  204. -----------
  205. .. class:: Feature
  206. ``Feature`` wraps an OGR feature. You never create a ``Feature`` object
  207. directly. Instead, you retrieve them from a :class:`Layer` object. Each
  208. feature consists of a geometry and a set of fields containing additional
  209. properties. The geometry of a field is accessible via its ``geom`` property,
  210. which returns an :class:`OGRGeometry` object. A ``Feature`` behaves like a
  211. standard Python container for its fields, which it returns as :class:`Field`
  212. objects: you can access a field directly by its index or name, or you can
  213. iterate over a feature's fields, e.g. in a ``for`` loop.
  214. .. attribute:: geom
  215. Returns the geometry for this feature, as an ``OGRGeometry`` object:
  216. .. code-block:: pycon
  217. >>> city.geom.tuple
  218. (-104.609252, 38.255001)
  219. .. attribute:: get
  220. A method that returns the value of the given field (specified by name)
  221. for this feature, **not** a ``Field`` wrapper object:
  222. .. code-block:: pycon
  223. >>> city.get("Population")
  224. 102121
  225. .. attribute:: geom_type
  226. Returns the type of geometry for this feature, as an :class:`OGRGeomType`
  227. object. This will be the same for all features in a given layer and is
  228. equivalent to the :attr:`Layer.geom_type` property of the :class:`Layer`
  229. object the feature came from.
  230. .. attribute:: num_fields
  231. Returns the number of fields of data associated with the feature. This will
  232. be the same for all features in a given layer and is equivalent to the
  233. :attr:`Layer.num_fields` property of the :class:`Layer` object the feature
  234. came from.
  235. .. attribute:: fields
  236. Returns a list of the names of the fields of data associated with the
  237. feature. This will be the same for all features in a given layer and is
  238. equivalent to the :attr:`Layer.fields` property of the :class:`Layer`
  239. object the feature came from.
  240. .. attribute:: fid
  241. Returns the feature identifier within the layer:
  242. .. code-block:: pycon
  243. >>> city.fid
  244. 0
  245. .. attribute:: layer_name
  246. Returns the name of the :class:`Layer` that the feature came from. This
  247. will be the same for all features in a given layer:
  248. .. code-block:: pycon
  249. >>> city.layer_name
  250. 'cities'
  251. .. attribute:: index
  252. A method that returns the index of the given field name. This will be the
  253. same for all features in a given layer:
  254. .. code-block:: pycon
  255. >>> city.index("Population")
  256. 1
  257. ``Field``
  258. ---------
  259. .. class:: Field
  260. .. attribute:: name
  261. Returns the name of this field:
  262. .. code-block:: pycon
  263. >>> city["Name"].name
  264. 'Name'
  265. .. attribute:: type
  266. Returns the OGR type of this field, as an integer. The ``FIELD_CLASSES``
  267. dictionary maps these values onto subclasses of ``Field``:
  268. .. code-block:: pycon
  269. >>> city["Density"].type
  270. 2
  271. .. attribute:: type_name
  272. Returns a string with the name of the data type of this field:
  273. .. code-block:: pycon
  274. >>> city["Name"].type_name
  275. 'String'
  276. .. attribute:: value
  277. Returns the value of this field. The ``Field`` class itself returns the
  278. value as a string, but each subclass returns the value in the most
  279. appropriate form:
  280. .. code-block:: pycon
  281. >>> city["Population"].value
  282. 102121
  283. .. attribute:: width
  284. Returns the width of this field:
  285. .. code-block:: pycon
  286. >>> city["Name"].width
  287. 80
  288. .. attribute:: precision
  289. Returns the numeric precision of this field. This is meaningless (and set
  290. to zero) for non-numeric fields:
  291. .. code-block:: pycon
  292. >>> city["Density"].precision
  293. 15
  294. .. method:: as_double()
  295. Returns the value of the field as a double (float):
  296. .. code-block:: pycon
  297. >>> city["Density"].as_double()
  298. 874.7
  299. .. method:: as_int()
  300. Returns the value of the field as an integer:
  301. .. code-block:: pycon
  302. >>> city["Population"].as_int()
  303. 102121
  304. .. method:: as_string()
  305. Returns the value of the field as a string:
  306. .. code-block:: pycon
  307. >>> city["Name"].as_string()
  308. 'Pueblo'
  309. .. method:: as_datetime()
  310. Returns the value of the field as a tuple of date and time components:
  311. .. code-block:: pycon
  312. >>> city["Created"].as_datetime()
  313. (c_long(1999), c_long(5), c_long(23), c_long(0), c_long(0), c_long(0), c_long(0))
  314. ``Driver``
  315. ----------
  316. .. class:: Driver(dr_input)
  317. The ``Driver`` class is used internally to wrap an OGR :class:`DataSource`
  318. driver.
  319. .. attribute:: driver_count
  320. Returns the number of OGR vector drivers currently registered.
  321. OGR Geometries
  322. ==============
  323. ``OGRGeometry``
  324. ---------------
  325. :class:`OGRGeometry` objects share similar functionality with
  326. :class:`~django.contrib.gis.geos.GEOSGeometry` objects and are thin wrappers
  327. around OGR's internal geometry representation. Thus, they allow for more
  328. efficient access to data when using :class:`DataSource`. Unlike its GEOS
  329. counterpart, :class:`OGRGeometry` supports spatial reference systems and
  330. coordinate transformation:
  331. .. code-block:: pycon
  332. >>> from django.contrib.gis.gdal import OGRGeometry
  333. >>> polygon = OGRGeometry("POLYGON((0 0, 5 0, 5 5, 0 5))")
  334. .. class:: OGRGeometry(geom_input, srs=None)
  335. This object is a wrapper for the `OGR Geometry`__ class. These objects are
  336. instantiated directly from the given ``geom_input`` parameter, which may be
  337. a string containing WKT, HEX, GeoJSON, a ``buffer`` containing WKB data, or
  338. an :class:`OGRGeomType` object. These objects are also returned from the
  339. :class:`Feature.geom` attribute, when reading vector data from
  340. :class:`Layer` (which is in turn a part of a :class:`DataSource`).
  341. __ https://gdal.org/api/ogrgeometry_cpp.html#ogrgeometry-class
  342. .. classmethod:: from_gml(gml_string)
  343. Constructs an :class:`OGRGeometry` from the given GML string.
  344. .. classmethod:: from_bbox(bbox)
  345. Constructs a :class:`Polygon` from the given bounding-box (a 4-tuple).
  346. .. method:: __len__()
  347. Returns the number of points in a :class:`LineString`, the number of rings
  348. in a :class:`Polygon`, or the number of geometries in a
  349. :class:`GeometryCollection`. Not applicable to other geometry types.
  350. .. method:: __iter__()
  351. Iterates over the points in a :class:`LineString`, the rings in a
  352. :class:`Polygon`, or the geometries in a :class:`GeometryCollection`.
  353. Not applicable to other geometry types.
  354. .. method:: __getitem__()
  355. Returns the point at the specified index for a :class:`LineString`, the
  356. interior ring at the specified index for a :class:`Polygon`, or the geometry
  357. at the specified index in a :class:`GeometryCollection`. Not applicable to
  358. other geometry types.
  359. .. attribute:: dimension
  360. Returns the number of coordinated dimensions of the geometry, i.e. 0
  361. for points, 1 for lines, and so forth:
  362. .. code-block:: pycon
  363. >>> polygon.dimension
  364. 2
  365. .. attribute:: coord_dim
  366. Returns the coordinate dimension of this geometry. For example, the value
  367. would be 2 for two-dimensional geometries.
  368. .. deprecated:: 5.1
  369. The ``coord_dim`` setter is deprecated. Use :meth:`.set_3d` instead.
  370. .. attribute:: is_3d
  371. .. versionadded:: 5.1
  372. A boolean indicating if this geometry has Z coordinates.
  373. .. method:: set_3d(value)
  374. .. versionadded:: 5.1
  375. A method that adds or removes the Z coordinate dimension.
  376. .. code-block:: pycon
  377. >>> p = OGRGeometry("POINT (1 2 3)")
  378. >>> p.is_3d
  379. True
  380. >>> p.set_3d(False)
  381. >>> p.wkt
  382. "POINT (1 2)"
  383. .. attribute:: is_measured
  384. .. versionadded:: 5.1
  385. A boolean indicating if this geometry has M coordinates.
  386. .. method:: set_measured(value)
  387. .. versionadded:: 5.1
  388. A method to add or remove the M coordinate dimension.
  389. .. code-block:: pycon
  390. >>> p = OGRGeometry("POINT (1 2)")
  391. >>> p.is_measured
  392. False
  393. >>> p.set_measured(True)
  394. >>> p.wkt
  395. "POINT M (1 2 0)"
  396. .. attribute:: geom_count
  397. Returns the number of elements in this geometry:
  398. .. code-block:: pycon
  399. >>> polygon.geom_count
  400. 1
  401. .. attribute:: has_curve
  402. .. versionadded:: 5.2
  403. A boolean indicating if this geometry is or contains a curve geometry.
  404. .. method:: get_linear_geometry
  405. .. versionadded:: 5.2
  406. Returns a linear version of the geometry. If no conversion can be made, the
  407. original geometry is returned.
  408. .. method:: get_curve_geometry
  409. .. versionadded:: 5.2
  410. Returns a curved version of the geometry. If no conversion can be made, the
  411. original geometry is returned.
  412. .. attribute:: point_count
  413. Returns the number of points used to describe this geometry:
  414. .. code-block:: pycon
  415. >>> polygon.point_count
  416. 4
  417. .. attribute:: num_points
  418. Alias for :attr:`point_count`.
  419. .. attribute:: num_coords
  420. Alias for :attr:`point_count`.
  421. .. attribute:: geom_type
  422. Returns the type of this geometry, as an :class:`OGRGeomType` object.
  423. .. attribute:: geom_name
  424. Returns the name of the type of this geometry:
  425. .. code-block:: pycon
  426. >>> polygon.geom_name
  427. 'POLYGON'
  428. .. attribute:: area
  429. Returns the area of this geometry, or 0 for geometries that do not contain
  430. an area:
  431. .. code-block:: pycon
  432. >>> polygon.area
  433. 25.0
  434. .. attribute:: envelope
  435. Returns the envelope of this geometry, as an :class:`Envelope` object.
  436. .. attribute:: extent
  437. Returns the envelope of this geometry as a 4-tuple, instead of as an
  438. :class:`Envelope` object:
  439. .. code-block:: pycon
  440. >>> point.extent
  441. (0.0, 0.0, 5.0, 5.0)
  442. .. attribute:: srs
  443. This property controls the spatial reference for this geometry, or
  444. ``None`` if no spatial reference system has been assigned to it.
  445. If assigned, accessing this property returns a :class:`SpatialReference`
  446. object. It may be set with another :class:`SpatialReference` object,
  447. or any input that :class:`SpatialReference` accepts. Example:
  448. .. code-block:: pycon
  449. >>> city.geom.srs.name
  450. 'GCS_WGS_1984'
  451. .. attribute:: srid
  452. Returns or sets the spatial reference identifier corresponding to
  453. :class:`SpatialReference` of this geometry. Returns ``None`` if
  454. there is no spatial reference information associated with this
  455. geometry, or if an SRID cannot be determined.
  456. .. attribute:: geos
  457. Returns a :class:`~django.contrib.gis.geos.GEOSGeometry` object
  458. corresponding to this geometry.
  459. .. attribute:: gml
  460. Returns a string representation of this geometry in GML format:
  461. .. code-block:: pycon
  462. >>> OGRGeometry("POINT(1 2)").gml
  463. '<gml:Point><gml:coordinates>1,2</gml:coordinates></gml:Point>'
  464. .. attribute:: hex
  465. Returns a string representation of this geometry in HEX WKB format:
  466. .. code-block:: pycon
  467. >>> OGRGeometry("POINT(1 2)").hex
  468. '0101000000000000000000F03F0000000000000040'
  469. .. attribute:: json
  470. Returns a string representation of this geometry in JSON format:
  471. .. code-block:: pycon
  472. >>> OGRGeometry("POINT(1 2)").json
  473. '{ "type": "Point", "coordinates": [ 1.000000, 2.000000 ] }'
  474. .. attribute:: kml
  475. Returns a string representation of this geometry in KML format.
  476. .. attribute:: wkb_size
  477. Returns the size of the WKB buffer needed to hold a WKB representation
  478. of this geometry:
  479. .. code-block:: pycon
  480. >>> OGRGeometry("POINT(1 2)").wkb_size
  481. 21
  482. .. attribute:: wkb
  483. Returns a ``buffer`` containing a WKB representation of this geometry.
  484. .. attribute:: wkt
  485. Returns a string representation of this geometry in WKT format.
  486. .. attribute:: ewkt
  487. Returns the EWKT representation of this geometry.
  488. .. method:: clone()
  489. Returns a new :class:`OGRGeometry` clone of this geometry object.
  490. .. method:: close_rings()
  491. If there are any rings within this geometry that have not been closed,
  492. this routine will do so by adding the starting point to the end:
  493. .. code-block:: pycon
  494. >>> triangle = OGRGeometry("LINEARRING (0 0,0 1,1 0)")
  495. >>> triangle.close_rings()
  496. >>> triangle.wkt
  497. 'LINEARRING (0 0,0 1,1 0,0 0)'
  498. .. method:: transform(coord_trans, clone=False)
  499. Transforms this geometry to a different spatial reference system. May take
  500. a :class:`CoordTransform` object, a :class:`SpatialReference` object, or
  501. any other input accepted by :class:`SpatialReference` (including spatial
  502. reference WKT and PROJ strings, or an integer SRID).
  503. By default nothing is returned and the geometry is transformed in-place.
  504. However, if the ``clone`` keyword is set to ``True`` then a transformed
  505. clone of this geometry is returned instead.
  506. .. method:: intersects(other)
  507. Returns ``True`` if this geometry intersects the other, otherwise returns
  508. ``False``.
  509. .. method:: equals(other)
  510. Returns ``True`` if this geometry is equivalent to the other, otherwise
  511. returns ``False``.
  512. .. method:: disjoint(other)
  513. Returns ``True`` if this geometry is spatially disjoint to (i.e. does
  514. not intersect) the other, otherwise returns ``False``.
  515. .. method:: touches(other)
  516. Returns ``True`` if this geometry touches the other, otherwise returns
  517. ``False``.
  518. .. method:: crosses(other)
  519. Returns ``True`` if this geometry crosses the other, otherwise returns
  520. ``False``.
  521. .. method:: within(other)
  522. Returns ``True`` if this geometry is contained within the other, otherwise
  523. returns ``False``.
  524. .. method:: contains(other)
  525. Returns ``True`` if this geometry contains the other, otherwise returns
  526. ``False``.
  527. .. method:: overlaps(other)
  528. Returns ``True`` if this geometry overlaps the other, otherwise returns
  529. ``False``.
  530. .. method:: boundary()
  531. The boundary of this geometry, as a new :class:`OGRGeometry` object.
  532. .. attribute:: convex_hull
  533. The smallest convex polygon that contains this geometry, as a new
  534. :class:`OGRGeometry` object.
  535. .. method:: difference()
  536. Returns the region consisting of the difference of this geometry and
  537. the other, as a new :class:`OGRGeometry` object.
  538. .. method:: intersection()
  539. Returns the region consisting of the intersection of this geometry and
  540. the other, as a new :class:`OGRGeometry` object.
  541. .. method:: sym_difference()
  542. Returns the region consisting of the symmetric difference of this
  543. geometry and the other, as a new :class:`OGRGeometry` object.
  544. .. method:: union()
  545. Returns the region consisting of the union of this geometry and
  546. the other, as a new :class:`OGRGeometry` object.
  547. .. attribute:: centroid
  548. Returns a :class:`Point` representing the centroid of this geometry.
  549. .. versionchanged:: 5.1
  550. ``centroid`` was promoted from a :class:`.Polygon` only attribute to
  551. being available on all geometry types.
  552. .. attribute:: tuple
  553. Returns the coordinates of a point geometry as a tuple, the
  554. coordinates of a line geometry as a tuple of tuples, and so forth:
  555. .. code-block:: pycon
  556. >>> OGRGeometry("POINT (1 2)").tuple
  557. (1.0, 2.0)
  558. >>> OGRGeometry("LINESTRING (1 2,3 4)").tuple
  559. ((1.0, 2.0), (3.0, 4.0))
  560. .. attribute:: coords
  561. An alias for :attr:`tuple`.
  562. .. class:: Point
  563. .. attribute:: x
  564. Returns the X coordinate of this point:
  565. .. code-block:: pycon
  566. >>> OGRGeometry("POINT (1 2)").x
  567. 1.0
  568. .. attribute:: y
  569. Returns the Y coordinate of this point:
  570. .. code-block:: pycon
  571. >>> OGRGeometry("POINT (1 2)").y
  572. 2.0
  573. .. attribute:: z
  574. Returns the Z coordinate of this point, or ``None`` if the point does not
  575. have a Z coordinate:
  576. .. code-block:: pycon
  577. >>> OGRGeometry("POINT (1 2 3)").z
  578. 3.0
  579. .. attribute:: m
  580. .. versionadded:: 5.1
  581. Returns the M coordinate of this point, or ``None`` if the Point does not
  582. have an M coordinate:
  583. .. code-block:: pycon
  584. >>> OGRGeometry("POINT ZM (1 2 3 4)").m
  585. 4.0
  586. .. class:: LineString
  587. .. attribute:: x
  588. Returns a list of X coordinates in this line:
  589. .. code-block:: pycon
  590. >>> OGRGeometry("LINESTRING (1 2,3 4)").x
  591. [1.0, 3.0]
  592. .. attribute:: y
  593. Returns a list of Y coordinates in this line:
  594. .. code-block:: pycon
  595. >>> OGRGeometry("LINESTRING (1 2,3 4)").y
  596. [2.0, 4.0]
  597. .. attribute:: z
  598. Returns a list of Z coordinates in this line, or ``None`` if the line does
  599. not have Z coordinates:
  600. .. code-block:: pycon
  601. >>> OGRGeometry("LINESTRING (1 2 3,4 5 6)").z
  602. [3.0, 6.0]
  603. .. attribute:: m
  604. .. versionadded:: 5.1
  605. Returns a list of M coordinates in this line or ``None`` if the line does
  606. not have M coordinates:
  607. .. code-block:: pycon
  608. >>> OGRGeometry("LINESTRING(0 1 2 10, 1 2 3 11, 2 3 4 12)").m
  609. [10.0, 11.0, 12.0]
  610. .. class:: Polygon
  611. .. attribute:: shell
  612. Returns the shell or exterior ring of this polygon, as a ``LinearRing``
  613. geometry.
  614. .. attribute:: exterior_ring
  615. An alias for :attr:`shell`.
  616. .. class:: GeometryCollection
  617. .. method:: add(geom)
  618. Adds a geometry to this geometry collection. Not applicable to other
  619. geometry types.
  620. ``OGRGeomType``
  621. ---------------
  622. .. class:: OGRGeomType(type_input)
  623. This class allows for the representation of an OGR geometry type
  624. in any of several ways:
  625. .. code-block:: pycon
  626. >>> from django.contrib.gis.gdal import OGRGeomType
  627. >>> gt1 = OGRGeomType(3) # Using an integer for the type
  628. >>> gt2 = OGRGeomType("Polygon") # Using a string
  629. >>> gt3 = OGRGeomType("POLYGON") # It's case-insensitive
  630. >>> print(gt1 == 3, gt1 == "Polygon") # Equivalence works w/non-OGRGeomType objects
  631. True True
  632. .. attribute:: name
  633. Returns a short-hand string form of the OGR Geometry type:
  634. .. code-block:: pycon
  635. >>> gt1.name
  636. 'Polygon'
  637. .. attribute:: num
  638. Returns the number corresponding to the OGR geometry type:
  639. .. code-block:: pycon
  640. >>> gt1.num
  641. 3
  642. .. attribute:: django
  643. Returns the Django field type (a subclass of GeometryField) to use for
  644. storing this OGR type, or ``None`` if there is no appropriate Django type:
  645. .. code-block:: pycon
  646. >>> gt1.django
  647. 'PolygonField'
  648. ``Envelope``
  649. ------------
  650. .. class:: Envelope(*args)
  651. Represents an OGR Envelope structure that contains the minimum and maximum
  652. X, Y coordinates for a rectangle bounding box. The naming of the variables
  653. is compatible with the OGR Envelope C structure.
  654. .. attribute:: min_x
  655. The value of the minimum X coordinate.
  656. .. attribute:: min_y
  657. The value of the maximum X coordinate.
  658. .. attribute:: max_x
  659. The value of the minimum Y coordinate.
  660. .. attribute:: max_y
  661. The value of the maximum Y coordinate.
  662. .. attribute:: ur
  663. The upper-right coordinate, as a tuple.
  664. .. attribute:: ll
  665. The lower-left coordinate, as a tuple.
  666. .. attribute:: tuple
  667. A tuple representing the envelope.
  668. .. attribute:: wkt
  669. A string representing this envelope as a polygon in WKT format.
  670. .. method:: expand_to_include(*args)
  671. Coordinate System Objects
  672. =========================
  673. ``SpatialReference``
  674. --------------------
  675. .. class:: SpatialReference(srs_input)
  676. Spatial reference objects are initialized on the given ``srs_input``,
  677. which may be one of the following:
  678. * OGC Well Known Text (WKT) (a string)
  679. * EPSG code (integer or string)
  680. * PROJ string
  681. * A shorthand string for well-known standards (``'WGS84'``, ``'WGS72'``,
  682. ``'NAD27'``, ``'NAD83'``)
  683. Example:
  684. .. code-block:: pycon
  685. >>> wgs84 = SpatialReference("WGS84") # shorthand string
  686. >>> wgs84 = SpatialReference(4326) # EPSG code
  687. >>> wgs84 = SpatialReference("EPSG:4326") # EPSG string
  688. >>> proj = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs "
  689. >>> wgs84 = SpatialReference(proj) # PROJ string
  690. >>> wgs84 = SpatialReference(
  691. ... """GEOGCS["WGS 84",
  692. ... DATUM["WGS_1984",
  693. ... SPHEROID["WGS 84",6378137,298.257223563,
  694. ... AUTHORITY["EPSG","7030"]],
  695. ... AUTHORITY["EPSG","6326"]],
  696. ... PRIMEM["Greenwich",0,
  697. ... AUTHORITY["EPSG","8901"]],
  698. ... UNIT["degree",0.01745329251994328,
  699. ... AUTHORITY["EPSG","9122"]],
  700. ... AUTHORITY["EPSG","4326"]]"""
  701. ... ) # OGC WKT
  702. .. method:: __getitem__(target)
  703. Returns the value of the given string attribute node, ``None`` if the node
  704. doesn't exist. Can also take a tuple as a parameter, (target, child), where
  705. child is the index of the attribute in the WKT. For example:
  706. .. code-block:: pycon
  707. >>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]'
  708. >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326
  709. >>> print(srs["GEOGCS"])
  710. WGS 84
  711. >>> print(srs["DATUM"])
  712. WGS_1984
  713. >>> print(srs["AUTHORITY"])
  714. EPSG
  715. >>> print(srs["AUTHORITY", 1]) # The authority value
  716. 4326
  717. >>> print(srs["TOWGS84", 4]) # the fourth value in this wkt
  718. 0
  719. >>> print(srs["UNIT|AUTHORITY"]) # For the units authority, have to use the pipe symbol.
  720. EPSG
  721. >>> print(srs["UNIT|AUTHORITY", 1]) # The authority value for the units
  722. 9122
  723. .. method:: attr_value(target, index=0)
  724. The attribute value for the given target node (e.g. ``'PROJCS'``).
  725. The index keyword specifies an index of the child node to return.
  726. .. method:: auth_name(target)
  727. Returns the authority name for the given string target node.
  728. .. method:: auth_code(target)
  729. Returns the authority code for the given string target node.
  730. .. method:: clone()
  731. Returns a clone of this spatial reference object.
  732. .. method:: identify_epsg()
  733. This method inspects the WKT of this ``SpatialReference`` and will add EPSG
  734. authority nodes where an EPSG identifier is applicable.
  735. .. method:: from_esri()
  736. Morphs this SpatialReference from ESRI's format to EPSG
  737. .. method:: to_esri()
  738. Morphs this SpatialReference to ESRI's format.
  739. .. method:: validate()
  740. Checks to see if the given spatial reference is valid, if not
  741. an exception will be raised.
  742. .. method:: import_epsg(epsg)
  743. Import spatial reference from EPSG code.
  744. .. method:: import_proj(proj)
  745. Import spatial reference from PROJ string.
  746. .. method:: import_user_input(user_input)
  747. .. method:: import_wkt(wkt)
  748. Import spatial reference from WKT.
  749. .. method:: import_xml(xml)
  750. Import spatial reference from XML.
  751. .. attribute:: name
  752. Returns the name of this Spatial Reference.
  753. .. attribute:: srid
  754. Returns the SRID of top-level authority, or ``None`` if undefined.
  755. .. attribute:: linear_name
  756. Returns the name of the linear units.
  757. .. attribute:: linear_units
  758. Returns the value of the linear units.
  759. .. attribute:: angular_name
  760. Returns the name of the angular units."
  761. .. attribute:: angular_units
  762. Returns the value of the angular units.
  763. .. attribute:: units
  764. Returns a 2-tuple of the units value and the units name and will
  765. automatically determines whether to return the linear or angular units.
  766. .. attribute:: ellipsoid
  767. Returns a tuple of the ellipsoid parameters for this spatial reference:
  768. (semimajor axis, semiminor axis, and inverse flattening).
  769. .. attribute:: semi_major
  770. Returns the semi major axis of the ellipsoid for this spatial reference.
  771. .. attribute:: semi_minor
  772. Returns the semi minor axis of the ellipsoid for this spatial reference.
  773. .. attribute:: inverse_flattening
  774. Returns the inverse flattening of the ellipsoid for this spatial reference.
  775. .. attribute:: geographic
  776. Returns ``True`` if this spatial reference is geographic (root node is
  777. ``GEOGCS``).
  778. .. attribute:: local
  779. Returns ``True`` if this spatial reference is local (root node is
  780. ``LOCAL_CS``).
  781. .. attribute:: projected
  782. Returns ``True`` if this spatial reference is a projected coordinate system
  783. (root node is ``PROJCS``).
  784. .. attribute:: wkt
  785. Returns the WKT representation of this spatial reference.
  786. .. attribute:: pretty_wkt
  787. Returns the 'pretty' representation of the WKT.
  788. .. attribute:: proj
  789. Returns the PROJ representation for this spatial reference.
  790. .. attribute:: proj4
  791. Alias for :attr:`SpatialReference.proj`.
  792. .. attribute:: xml
  793. Returns the XML representation of this spatial reference.
  794. ``CoordTransform``
  795. ------------------
  796. .. class:: CoordTransform(source, target)
  797. Represents a coordinate system transform. It is initialized with two
  798. :class:`SpatialReference`, representing the source and target coordinate
  799. systems, respectively. These objects should be used when performing the same
  800. coordinate transformation repeatedly on different geometries:
  801. .. code-block:: pycon
  802. >>> ct = CoordTransform(SpatialReference("WGS84"), SpatialReference("NAD83"))
  803. >>> for feat in layer:
  804. ... geom = feat.geom # getting clone of feature geometry
  805. ... geom.transform(ct) # transforming
  806. ...
  807. .. _raster-data-source-objects:
  808. Raster Data Objects
  809. ===================
  810. ``GDALRaster``
  811. ----------------
  812. :class:`GDALRaster` is a wrapper for the GDAL raster source object that
  813. supports reading data from a variety of GDAL-supported geospatial file
  814. formats and data sources using a consistent interface. Each
  815. data source is represented by a :class:`GDALRaster` object which contains
  816. one or more layers of data named bands. Each band, represented by a
  817. :class:`GDALBand` object, contains georeferenced image data. For example, an RGB
  818. image is represented as three bands: one for red, one for green, and one for
  819. blue.
  820. .. note::
  821. For raster data there is no difference between a raster instance and its
  822. data source. Unlike for the Geometry objects, :class:`GDALRaster` objects are
  823. always a data source. Temporary rasters can be instantiated in memory
  824. using the corresponding driver, but they will be of the same class as file-based
  825. raster sources.
  826. .. class:: GDALRaster(ds_input, write=False)
  827. The constructor for ``GDALRaster`` accepts two parameters. The first
  828. parameter defines the raster source, and the second parameter defines if a
  829. raster should be opened in write mode. For newly-created rasters, the second
  830. parameter is ignored and the new raster is always created in write mode.
  831. The first parameter can take three forms: a string or
  832. :class:`~pathlib.Path` representing a file path (filesystem or GDAL virtual
  833. filesystem), a dictionary with values defining a new raster, or a bytes
  834. object representing a raster file.
  835. If the input is a file path, the raster is opened from there. If the input
  836. is raw data in a dictionary, the parameters ``width``, ``height``, and
  837. ``srid`` are required. If the input is a bytes object, it will be opened
  838. using a GDAL virtual filesystem.
  839. For a detailed description of how to create rasters using dictionary input,
  840. see :ref:`gdal-raster-ds-input`. For a detailed description of how to
  841. create rasters in the virtual filesystem, see :ref:`gdal-raster-vsimem`.
  842. The following example shows how rasters can be created from different input
  843. sources (using the sample data from the GeoDjango tests; see also the
  844. :ref:`gdal_sample_data` section).
  845. .. code-block:: pycon
  846. >>> from django.contrib.gis.gdal import GDALRaster
  847. >>> rst = GDALRaster("/path/to/your/raster.tif", write=False)
  848. >>> rst.name
  849. '/path/to/your/raster.tif'
  850. >>> rst.width, rst.height # This file has 163 x 174 pixels
  851. (163, 174)
  852. >>> rst = GDALRaster(
  853. ... { # Creates an in-memory raster
  854. ... "srid": 4326,
  855. ... "width": 4,
  856. ... "height": 4,
  857. ... "datatype": 1,
  858. ... "bands": [
  859. ... {
  860. ... "data": (2, 3),
  861. ... "offset": (1, 1),
  862. ... "size": (2, 2),
  863. ... "shape": (2, 1),
  864. ... "nodata_value": 5,
  865. ... }
  866. ... ],
  867. ... }
  868. ... )
  869. >>> rst.srs.srid
  870. 4326
  871. >>> rst.width, rst.height
  872. (4, 4)
  873. >>> rst.bands[0].data()
  874. array([[5, 5, 5, 5],
  875. [5, 2, 3, 5],
  876. [5, 2, 3, 5],
  877. [5, 5, 5, 5]], dtype=uint8)
  878. >>> rst_file = open("/path/to/your/raster.tif", "rb")
  879. >>> rst_bytes = rst_file.read()
  880. >>> rst = GDALRaster(rst_bytes)
  881. >>> rst.is_vsi_based
  882. True
  883. >>> rst.name # Stored in a random path in the vsimem filesystem.
  884. '/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'
  885. .. attribute:: name
  886. The name of the source which is equivalent to the input file path or the name
  887. provided upon instantiation.
  888. .. code-block:: pycon
  889. >>> GDALRaster({"width": 10, "height": 10, "name": "myraster", "srid": 4326}).name
  890. 'myraster'
  891. .. attribute:: driver
  892. The name of the GDAL driver used to handle the input file. For ``GDALRaster``\s created
  893. from a file, the driver type is detected automatically. The creation of rasters from
  894. scratch is an in-memory raster by default (``'MEM'``), but can be
  895. altered as needed. For instance, use ``GTiff`` for a ``GeoTiff`` file.
  896. For a list of file types, see also the `GDAL Raster Formats`__ list.
  897. __ https://gdal.org/drivers/raster/
  898. An in-memory raster is created through the following example:
  899. .. code-block:: pycon
  900. >>> GDALRaster({"width": 10, "height": 10, "srid": 4326}).driver.name
  901. 'MEM'
  902. A file based GeoTiff raster is created through the following example:
  903. .. code-block:: pycon
  904. >>> import tempfile
  905. >>> rstfile = tempfile.NamedTemporaryFile(suffix=".tif")
  906. >>> rst = GDALRaster(
  907. ... {
  908. ... "driver": "GTiff",
  909. ... "name": rstfile.name,
  910. ... "srid": 4326,
  911. ... "width": 255,
  912. ... "height": 255,
  913. ... "nr_of_bands": 1,
  914. ... }
  915. ... )
  916. >>> rst.name
  917. '/tmp/tmp7x9H4J.tif' # The exact filename will be different on your computer
  918. >>> rst.driver.name
  919. 'GTiff'
  920. .. attribute:: width
  921. The width of the source in pixels (X-axis).
  922. .. code-block:: pycon
  923. >>> GDALRaster({"width": 10, "height": 20, "srid": 4326}).width
  924. 10
  925. .. attribute:: height
  926. The height of the source in pixels (Y-axis).
  927. .. code-block:: pycon
  928. >>> GDALRaster({"width": 10, "height": 20, "srid": 4326}).height
  929. 20
  930. .. attribute:: srs
  931. The spatial reference system of the raster, as a
  932. :class:`SpatialReference` instance. The SRS can be changed by
  933. setting it to an other :class:`SpatialReference` or providing any input
  934. that is accepted by the :class:`SpatialReference` constructor.
  935. .. code-block:: pycon
  936. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  937. >>> rst.srs.srid
  938. 4326
  939. >>> rst.srs = 3086
  940. >>> rst.srs.srid
  941. 3086
  942. .. attribute:: srid
  943. The Spatial Reference System Identifier (SRID) of the raster. This
  944. property is a shortcut to getting or setting the SRID through the
  945. :attr:`srs` attribute.
  946. .. code-block:: pycon
  947. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  948. >>> rst.srid
  949. 4326
  950. >>> rst.srid = 3086
  951. >>> rst.srid
  952. 3086
  953. >>> rst.srs.srid # This is equivalent
  954. 3086
  955. .. attribute:: geotransform
  956. The affine transformation matrix used to georeference the source, as a
  957. tuple of six coefficients which map pixel/line coordinates into
  958. georeferenced space using the following relationship::
  959. Xgeo = GT(0) + Xpixel * GT(1) + Yline * GT(2)
  960. Ygeo = GT(3) + Xpixel * GT(4) + Yline * GT(5)
  961. The same values can be retrieved by accessing the :attr:`origin`
  962. (indices 0 and 3), :attr:`scale` (indices 1 and 5) and :attr:`skew`
  963. (indices 2 and 4) properties.
  964. The default is ``[0.0, 1.0, 0.0, 0.0, 0.0, -1.0]``.
  965. .. code-block:: pycon
  966. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  967. >>> rst.geotransform
  968. [0.0, 1.0, 0.0, 0.0, 0.0, -1.0]
  969. .. attribute:: origin
  970. Coordinates of the top left origin of the raster in the spatial
  971. reference system of the source, as a point object with ``x`` and ``y``
  972. members.
  973. .. code-block:: pycon
  974. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  975. >>> rst.origin
  976. [0.0, 0.0]
  977. >>> rst.origin.x = 1
  978. >>> rst.origin
  979. [1.0, 0.0]
  980. .. attribute:: scale
  981. Pixel width and height used for georeferencing the raster, as a point
  982. object with ``x`` and ``y`` members. See :attr:`geotransform` for more
  983. information.
  984. .. code-block:: pycon
  985. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  986. >>> rst.scale
  987. [1.0, -1.0]
  988. >>> rst.scale.x = 2
  989. >>> rst.scale
  990. [2.0, -1.0]
  991. .. attribute:: skew
  992. Skew coefficients used to georeference the raster, as a point object
  993. with ``x`` and ``y`` members. In case of north up images, these
  994. coefficients are both ``0``.
  995. .. code-block:: pycon
  996. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  997. >>> rst.skew
  998. [0.0, 0.0]
  999. >>> rst.skew.x = 3
  1000. >>> rst.skew
  1001. [3.0, 0.0]
  1002. .. attribute:: extent
  1003. Extent (boundary values) of the raster source, as a 4-tuple
  1004. ``(xmin, ymin, xmax, ymax)`` in the spatial reference system of the
  1005. source.
  1006. .. code-block:: pycon
  1007. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  1008. >>> rst.extent
  1009. (0.0, -20.0, 10.0, 0.0)
  1010. >>> rst.origin.x = 100
  1011. >>> rst.extent
  1012. (100.0, -20.0, 110.0, 0.0)
  1013. .. attribute:: bands
  1014. List of all bands of the source, as :class:`GDALBand` instances.
  1015. .. code-block:: pycon
  1016. >>> rst = GDALRaster(
  1017. ... {
  1018. ... "width": 1,
  1019. ... "height": 2,
  1020. ... "srid": 4326,
  1021. ... "bands": [{"data": [0, 1]}, {"data": [2, 3]}],
  1022. ... }
  1023. ... )
  1024. >>> len(rst.bands)
  1025. 2
  1026. >>> rst.bands[1].data()
  1027. array([[ 2., 3.]], dtype=float32)
  1028. .. method:: warp(ds_input, resampling='NearestNeighbour', max_error=0.0)
  1029. Returns a warped version of this raster.
  1030. The warping parameters can be specified through the ``ds_input``
  1031. argument. The use of ``ds_input`` is analogous to the corresponding
  1032. argument of the class constructor. It is a dictionary with the
  1033. characteristics of the target raster. Allowed dictionary key values are
  1034. width, height, SRID, origin, scale, skew, datatype, driver, and name
  1035. (filename).
  1036. By default, the warp functions keeps most parameters equal to the
  1037. values of the original source raster, so only parameters that should be
  1038. changed need to be specified. Note that this includes the driver, so
  1039. for file-based rasters the warp function will create a new raster on
  1040. disk.
  1041. The only parameter that is set differently from the source raster is the
  1042. name. The default value of the raster name is the name of the source
  1043. raster appended with ``'_copy' + source_driver_name``. For file-based
  1044. rasters it is recommended to provide the file path of the target raster.
  1045. The resampling algorithm used for warping can be specified with the
  1046. ``resampling`` argument. The default is ``NearestNeighbor``, and the
  1047. other allowed values are ``Bilinear``, ``Cubic``, ``CubicSpline``,
  1048. ``Lanczos``, ``Average``, and ``Mode``.
  1049. The ``max_error`` argument can be used to specify the maximum error
  1050. measured in input pixels that is allowed in approximating the
  1051. transformation. The default is 0.0 for exact calculations.
  1052. For users familiar with ``GDAL``, this function has a similar
  1053. functionality to the ``gdalwarp`` command-line utility.
  1054. For example, the warp function can be used for aggregating a raster to
  1055. the double of its original pixel scale:
  1056. .. code-block:: pycon
  1057. >>> rst = GDALRaster(
  1058. ... {
  1059. ... "width": 6,
  1060. ... "height": 6,
  1061. ... "srid": 3086,
  1062. ... "origin": [500000, 400000],
  1063. ... "scale": [100, -100],
  1064. ... "bands": [{"data": range(36), "nodata_value": 99}],
  1065. ... }
  1066. ... )
  1067. >>> target = rst.warp({"scale": [200, -200], "width": 3, "height": 3})
  1068. >>> target.bands[0].data()
  1069. array([[ 7., 9., 11.],
  1070. [ 19., 21., 23.],
  1071. [ 31., 33., 35.]], dtype=float32)
  1072. .. method:: transform(srs, driver=None, name=None, resampling='NearestNeighbour', max_error=0.0)
  1073. Transforms this raster to a different spatial reference system
  1074. (``srs``), which may be a :class:`SpatialReference` object, or any
  1075. other input accepted by :class:`SpatialReference` (including spatial
  1076. reference WKT and PROJ strings, or an integer SRID).
  1077. It calculates the bounds and scale of the current raster in the new
  1078. spatial reference system and warps the raster using the
  1079. :attr:`~GDALRaster.warp` function.
  1080. By default, the driver of the source raster is used and the name of the
  1081. raster is the original name appended with
  1082. ``'_copy' + source_driver_name``. A different driver or name can be
  1083. specified with the ``driver`` and ``name`` arguments.
  1084. The default resampling algorithm is ``NearestNeighbour`` but can be
  1085. changed using the ``resampling`` argument. The default maximum allowed
  1086. error for resampling is 0.0 and can be changed using the ``max_error``
  1087. argument. Consult the :attr:`~GDALRaster.warp` documentation for detail
  1088. on those arguments.
  1089. .. code-block:: pycon
  1090. >>> rst = GDALRaster(
  1091. ... {
  1092. ... "width": 6,
  1093. ... "height": 6,
  1094. ... "srid": 3086,
  1095. ... "origin": [500000, 400000],
  1096. ... "scale": [100, -100],
  1097. ... "bands": [{"data": range(36), "nodata_value": 99}],
  1098. ... }
  1099. ... )
  1100. >>> target_srs = SpatialReference(4326)
  1101. >>> target = rst.transform(target_srs)
  1102. >>> target.origin
  1103. [-82.98492744885776, 27.601924753080144]
  1104. .. attribute:: info
  1105. Returns a string with a summary of the raster. This is equivalent to
  1106. the `gdalinfo`__ command line utility.
  1107. __ https://gdal.org/programs/gdalinfo.html
  1108. .. attribute:: metadata
  1109. The metadata of this raster, represented as a nested dictionary. The
  1110. first-level key is the metadata domain. The second-level contains the
  1111. metadata item names and values from each domain.
  1112. To set or update a metadata item, pass the corresponding metadata item
  1113. to the method using the nested structure described above. Only keys
  1114. that are in the specified dictionary are updated; the rest of the
  1115. metadata remains unchanged.
  1116. To remove a metadata item, use ``None`` as the metadata value.
  1117. .. code-block:: pycon
  1118. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  1119. >>> rst.metadata
  1120. {}
  1121. >>> rst.metadata = {"DEFAULT": {"OWNER": "Django", "VERSION": "1.0"}}
  1122. >>> rst.metadata
  1123. {'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0'}}
  1124. >>> rst.metadata = {"DEFAULT": {"OWNER": None, "VERSION": "2.0"}}
  1125. >>> rst.metadata
  1126. {'DEFAULT': {'VERSION': '2.0'}}
  1127. .. attribute:: vsi_buffer
  1128. A ``bytes`` representation of this raster. Returns ``None`` for rasters
  1129. that are not stored in GDAL's virtual filesystem.
  1130. .. attribute:: is_vsi_based
  1131. A boolean indicating if this raster is stored in GDAL's virtual
  1132. filesystem.
  1133. ``GDALBand``
  1134. ------------
  1135. .. class:: GDALBand
  1136. ``GDALBand`` instances are not created explicitly, but rather obtained
  1137. from a :class:`GDALRaster` object, through its :attr:`~GDALRaster.bands`
  1138. attribute. The GDALBands contain the actual pixel values of the raster.
  1139. .. attribute:: description
  1140. The name or description of the band, if any.
  1141. .. attribute:: width
  1142. The width of the band in pixels (X-axis).
  1143. .. attribute:: height
  1144. The height of the band in pixels (Y-axis).
  1145. .. attribute:: pixel_count
  1146. The total number of pixels in this band. Is equal to ``width * height``.
  1147. .. method:: statistics(refresh=False, approximate=False)
  1148. Compute statistics on the pixel values of this band. The return value
  1149. is a tuple with the following structure:
  1150. ``(minimum, maximum, mean, standard deviation)``.
  1151. If the ``approximate`` argument is set to ``True``, the statistics may
  1152. be computed based on overviews or a subset of image tiles.
  1153. If the ``refresh`` argument is set to ``True``, the statistics will be
  1154. computed from the data directly, and the cache will be updated with the
  1155. result.
  1156. If a persistent cache value is found, that value is returned. For
  1157. raster formats using Persistent Auxiliary Metadata (PAM) services, the
  1158. statistics might be cached in an auxiliary file. In some cases this
  1159. metadata might be out of sync with the pixel values or cause values
  1160. from a previous call to be returned which don't reflect the value of
  1161. the ``approximate`` argument. In such cases, use the ``refresh``
  1162. argument to get updated values and store them in the cache.
  1163. For empty bands (where all pixel values are "no data"), all statistics
  1164. are returned as ``None``.
  1165. The statistics can also be retrieved directly by accessing the
  1166. :attr:`min`, :attr:`max`, :attr:`mean`, and :attr:`std` properties.
  1167. .. attribute:: min
  1168. The minimum pixel value of the band (excluding the "no data" value).
  1169. .. attribute:: max
  1170. The maximum pixel value of the band (excluding the "no data" value).
  1171. .. attribute:: mean
  1172. The mean of all pixel values of the band (excluding the "no data"
  1173. value).
  1174. .. attribute:: std
  1175. The standard deviation of all pixel values of the band (excluding the
  1176. "no data" value).
  1177. .. attribute:: nodata_value
  1178. The "no data" value for a band is generally a special marker value used
  1179. to mark pixels that are not valid data. Such pixels should generally not
  1180. be displayed, nor contribute to analysis operations.
  1181. To delete an existing "no data" value, set this property to ``None``.
  1182. .. method:: datatype(as_string=False)
  1183. The data type contained in the band, as an integer constant between 0
  1184. (Unknown) and 14. If ``as_string`` is ``True``, the data type is
  1185. returned as a string. Check out the "GDAL Pixel Type" column in the
  1186. :ref:`datatype value table <gdal-raster-datatype>` for possible values.
  1187. .. method:: color_interp(as_string=False)
  1188. The color interpretation for the band, as an integer between 0and 16.
  1189. If ``as_string`` is ``True``, the data type is returned as a string
  1190. with the following possible values:
  1191. ``GCI_Undefined``, ``GCI_GrayIndex``, ``GCI_PaletteIndex``,
  1192. ``GCI_RedBand``, ``GCI_GreenBand``, ``GCI_BlueBand``, ``GCI_AlphaBand``,
  1193. ``GCI_HueBand``, ``GCI_SaturationBand``, ``GCI_LightnessBand``,
  1194. ``GCI_CyanBand``, ``GCI_MagentaBand``, ``GCI_YellowBand``,
  1195. ``GCI_BlackBand``, ``GCI_YCbCr_YBand``, ``GCI_YCbCr_CbBand``, and
  1196. ``GCI_YCbCr_CrBand``. ``GCI_YCbCr_CrBand`` also represents ``GCI_Max``
  1197. because both correspond to the integer 16, but only ``GCI_YCbCr_CrBand``
  1198. is returned as a string.
  1199. .. method:: data(data=None, offset=None, size=None, shape=None)
  1200. The accessor to the pixel values of the ``GDALBand``. Returns the complete
  1201. data array if no parameters are provided. A subset of the pixel array can
  1202. be requested by specifying an offset and block size as tuples.
  1203. If NumPy is available, the data is returned as NumPy array. For performance
  1204. reasons, it is highly recommended to use NumPy.
  1205. Data is written to the ``GDALBand`` if the ``data`` parameter is provided.
  1206. The input can be of one of the following types - packed string, buffer, list,
  1207. array, and NumPy array. The number of items in the input should normally
  1208. correspond to the total number of pixels in the band, or to the number
  1209. of pixels for a specific block of pixel values if the ``offset`` and
  1210. ``size`` parameters are provided.
  1211. If the number of items in the input is different from the target pixel
  1212. block, the ``shape`` parameter must be specified. The shape is a tuple
  1213. that specifies the width and height of the input data in pixels. The
  1214. data is then replicated to update the pixel values of the selected
  1215. block. This is useful to fill an entire band with a single value, for
  1216. instance.
  1217. For example:
  1218. .. code-block:: pycon
  1219. >>> rst = GDALRaster(
  1220. ... {"width": 4, "height": 4, "srid": 4326, "datatype": 1, "nr_of_bands": 1}
  1221. ... )
  1222. >>> bnd = rst.bands[0]
  1223. >>> bnd.data(range(16))
  1224. >>> bnd.data()
  1225. array([[ 0, 1, 2, 3],
  1226. [ 4, 5, 6, 7],
  1227. [ 8, 9, 10, 11],
  1228. [12, 13, 14, 15]], dtype=int8)
  1229. >>> bnd.data(offset=(1, 1), size=(2, 2))
  1230. array([[ 5, 6],
  1231. [ 9, 10]], dtype=int8)
  1232. >>> bnd.data(data=[-1, -2, -3, -4], offset=(1, 1), size=(2, 2))
  1233. >>> bnd.data()
  1234. array([[ 0, 1, 2, 3],
  1235. [ 4, -1, -2, 7],
  1236. [ 8, -3, -4, 11],
  1237. [12, 13, 14, 15]], dtype=int8)
  1238. >>> bnd.data(data="\x9d\xa8\xb3\xbe", offset=(1, 1), size=(2, 2))
  1239. >>> bnd.data()
  1240. array([[ 0, 1, 2, 3],
  1241. [ 4, -99, -88, 7],
  1242. [ 8, -77, -66, 11],
  1243. [ 12, 13, 14, 15]], dtype=int8)
  1244. >>> bnd.data([1], shape=(1, 1))
  1245. >>> bnd.data()
  1246. array([[1, 1, 1, 1],
  1247. [1, 1, 1, 1],
  1248. [1, 1, 1, 1],
  1249. [1, 1, 1, 1]], dtype=uint8)
  1250. >>> bnd.data(range(4), shape=(1, 4))
  1251. array([[0, 0, 0, 0],
  1252. [1, 1, 1, 1],
  1253. [2, 2, 2, 2],
  1254. [3, 3, 3, 3]], dtype=uint8)
  1255. .. attribute:: metadata
  1256. The metadata of this band. The functionality is identical to
  1257. :attr:`GDALRaster.metadata`.
  1258. .. _gdal-raster-ds-input:
  1259. Creating rasters from data
  1260. --------------------------
  1261. This section describes how to create rasters from scratch using the
  1262. ``ds_input`` parameter.
  1263. A new raster is created when a ``dict`` is passed to the :class:`GDALRaster`
  1264. constructor. The dictionary contains defining parameters of the new raster,
  1265. such as the origin, size, or spatial reference system. The dictionary can also
  1266. contain pixel data and information about the format of the new raster. The
  1267. resulting raster can therefore be file-based or memory-based, depending on the
  1268. driver specified.
  1269. There's no standard for describing raster data in a dictionary or JSON flavor.
  1270. The definition of the dictionary input to the :class:`GDALRaster` class is
  1271. therefore specific to Django. It's inspired by the `geojson`__ format, but the
  1272. ``geojson`` standard is currently limited to vector formats.
  1273. Examples of using the different keys when creating rasters can be found in the
  1274. documentation of the corresponding attributes and methods of the
  1275. :class:`GDALRaster` and :class:`GDALBand` classes.
  1276. __ https://geojson.org/
  1277. The ``ds_input`` dictionary
  1278. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1279. Only a few keys are required in the ``ds_input`` dictionary to create a raster:
  1280. ``width``, ``height``, and ``srid``. All other parameters have default values
  1281. (see the table below). The list of keys that can be passed in the ``ds_input``
  1282. dictionary is closely related but not identical to the :class:`GDALRaster`
  1283. properties. Many of the parameters are mapped directly to those properties;
  1284. the others are described below.
  1285. The following table describes all keys that can be set in the ``ds_input``
  1286. dictionary.
  1287. ================= ======== ==================================================
  1288. Key Default Usage
  1289. ================= ======== ==================================================
  1290. ``srid`` required Mapped to the :attr:`~GDALRaster.srid` attribute
  1291. ``width`` required Mapped to the :attr:`~GDALRaster.width` attribute
  1292. ``height`` required Mapped to the :attr:`~GDALRaster.height` attribute
  1293. ``driver`` ``MEM`` Mapped to the :attr:`~GDALRaster.driver` attribute
  1294. ``name`` ``''`` See below
  1295. ``origin`` ``0`` Mapped to the :attr:`~GDALRaster.origin` attribute
  1296. ``scale`` ``0`` Mapped to the :attr:`~GDALRaster.scale` attribute
  1297. ``skew`` ``0`` Mapped to the :attr:`~GDALRaster.width` attribute
  1298. ``bands`` ``[]`` See below
  1299. ``nr_of_bands`` ``0`` See below
  1300. ``datatype`` ``6`` See below
  1301. ``papsz_options`` ``{}`` See below
  1302. ================= ======== ==================================================
  1303. .. object:: name
  1304. String representing the name of the raster. When creating a file-based
  1305. raster, this parameter must be the file path for the new raster. If the
  1306. name starts with ``/vsimem/``, the raster is created in GDAL's virtual
  1307. filesystem.
  1308. .. _gdal-raster-datatype:
  1309. .. object:: datatype
  1310. Integer representing the data type for all the bands. Defaults to ``6``
  1311. (Float32). All bands of a new raster are required to have the same datatype.
  1312. The value mapping is:
  1313. ===== =============== ===================================
  1314. Value GDAL Pixel Type Description
  1315. ===== =============== ===================================
  1316. 1 GDT_Byte 8 bit unsigned integer
  1317. 2 GDT_UInt16 16 bit unsigned integer
  1318. 3 GDT_Int16 16 bit signed integer
  1319. 4 GDT_UInt32 32 bit unsigned integer
  1320. 5 GDT_Int32 32 bit signed integer
  1321. 6 GDT_Float32 32 bit floating point
  1322. 7 GDT_Float64 64 bit floating point
  1323. 12 GDT_UInt64 64 bit unsigned integer (GDAL 3.5+)
  1324. 13 GDT_Int64 64 bit signed integer (GDAL 3.5+)
  1325. 14 GDT_Int8 8 bit signed integer (GDAL 3.7+)
  1326. ===== =============== ===================================
  1327. .. object:: nr_of_bands
  1328. Integer representing the number of bands of the raster. A raster can be
  1329. created without passing band data upon creation. If the number of bands
  1330. isn't specified, it's automatically calculated from the length of the
  1331. ``bands`` input. The number of bands can't be changed after creation.
  1332. .. object:: bands
  1333. A list of ``band_input`` dictionaries with band input data. The resulting
  1334. band indices are the same as in the list provided. The definition of the
  1335. band input dictionary is given below. If band data isn't provided, the
  1336. raster bands values are instantiated as an array of zeros and the "no
  1337. data" value is set to ``None``.
  1338. .. object:: papsz_options
  1339. A dictionary with raster creation options. The key-value pairs of the
  1340. input dictionary are passed to the driver on creation of the raster.
  1341. The available options are driver-specific and are described in the
  1342. documentation of each driver.
  1343. The values in the dictionary are not case-sensitive and are automatically
  1344. converted to the correct string format upon creation.
  1345. The following example uses some of the options available for the
  1346. `GTiff driver`__. The result is a compressed raster with an internal tiling
  1347. scheme. The internal tiles have a block size of 23 by 23:
  1348. .. code-block:: pycon
  1349. >>> GDALRaster(
  1350. ... {
  1351. ... "driver": "GTiff",
  1352. ... "name": "/path/to/new/file.tif",
  1353. ... "srid": 4326,
  1354. ... "width": 255,
  1355. ... "height": 255,
  1356. ... "nr_of_bands": 1,
  1357. ... "papsz_options": {
  1358. ... "compress": "packbits",
  1359. ... "tiled": "yes",
  1360. ... "blockxsize": 23,
  1361. ... "blockysize": 23,
  1362. ... },
  1363. ... }
  1364. ... )
  1365. __ https://gdal.org/drivers/raster/gtiff.html
  1366. The ``band_input`` dictionary
  1367. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1368. The ``bands`` key in the ``ds_input`` dictionary is a list of ``band_input``
  1369. dictionaries. Each ``band_input`` dictionary can contain pixel values and the
  1370. "no data" value to be set on the bands of the new raster. The data array can
  1371. have the full size of the new raster or be smaller. For arrays that are smaller
  1372. than the full raster, the ``size``, ``shape``, and ``offset`` keys control the
  1373. pixel values. The corresponding keys are passed to the :meth:`~GDALBand.data`
  1374. method. Their functionality is the same as setting the band data with that
  1375. method. The following table describes the keys that can be used.
  1376. ================ ================================= ======================================================
  1377. Key Default Usage
  1378. ================ ================================= ======================================================
  1379. ``nodata_value`` ``None`` Mapped to the :attr:`~GDALBand.nodata_value` attribute
  1380. ``data`` Same as ``nodata_value`` or ``0`` Passed to the :meth:`~GDALBand.data` method
  1381. ``size`` ``(with, height)`` of raster Passed to the :meth:`~GDALBand.data` method
  1382. ``shape`` Same as size Passed to the :meth:`~GDALBand.data` method
  1383. ``offset`` ``(0, 0)`` Passed to the :meth:`~GDALBand.data` method
  1384. ================ ================================= ======================================================
  1385. .. _gdal-raster-vsimem:
  1386. Using GDAL's Virtual Filesystem
  1387. -------------------------------
  1388. GDAL can access files stored in the filesystem, but also supports virtual
  1389. filesystems to abstract accessing other kind of files, such as compressed,
  1390. encrypted, or remote files.
  1391. Using memory-based Virtual Filesystem
  1392. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1393. GDAL has an internal memory-based filesystem, which allows treating blocks of
  1394. memory as files. It can be used to read and write :class:`GDALRaster` objects
  1395. to and from binary file buffers.
  1396. This is useful in web contexts where rasters might be obtained as a buffer
  1397. from a remote storage or returned from a view without being written to disk.
  1398. :class:`GDALRaster` objects are created in the virtual filesystem when a
  1399. ``bytes`` object is provided as input, or when the file path starts with
  1400. ``/vsimem/``.
  1401. Input provided as ``bytes`` has to be a full binary representation of a file.
  1402. For instance:
  1403. .. code-block:: pycon
  1404. # Read a raster as a file object from a remote source.
  1405. >>> from urllib.request import urlopen
  1406. >>> dat = urlopen("https://example.com/raster.tif").read()
  1407. # Instantiate a raster from the bytes object.
  1408. >>> rst = GDALRaster(dat)
  1409. # The name starts with /vsimem/, indicating that the raster lives in the
  1410. # virtual filesystem.
  1411. >>> rst.name
  1412. '/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'
  1413. To create a new virtual file-based raster from scratch, use the ``ds_input``
  1414. dictionary representation and provide a ``name`` argument that starts with
  1415. ``/vsimem/`` (for detail of the dictionary representation, see
  1416. :ref:`gdal-raster-ds-input`). For virtual file-based rasters, the
  1417. :attr:`~GDALRaster.vsi_buffer` attribute returns the ``bytes`` representation
  1418. of the raster.
  1419. Here's how to create a raster and return it as a file in an
  1420. :class:`~django.http.HttpResponse`:
  1421. .. code-block:: pycon
  1422. >>> from django.http import HttpResponse
  1423. >>> rst = GDALRaster(
  1424. ... {
  1425. ... "name": "/vsimem/temporarymemfile",
  1426. ... "driver": "tif",
  1427. ... "width": 6,
  1428. ... "height": 6,
  1429. ... "srid": 3086,
  1430. ... "origin": [500000, 400000],
  1431. ... "scale": [100, -100],
  1432. ... "bands": [{"data": range(36), "nodata_value": 99}],
  1433. ... }
  1434. ... )
  1435. >>> HttpResponse(rast.vsi_buffer, "image/tiff")
  1436. Using other Virtual Filesystems
  1437. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1438. Depending on the local build of GDAL other virtual filesystems may be
  1439. supported. You can use them by prepending the provided path with the
  1440. appropriate ``/vsi*/`` prefix. See the `GDAL Virtual Filesystems
  1441. documentation`_ for more details.
  1442. .. warning:
  1443. Rasters with names starting with `/vsi*/` will be treated as rasters from
  1444. the GDAL virtual filesystems. Django doesn't perform any extra validation.
  1445. Compressed rasters
  1446. ^^^^^^^^^^^^^^^^^^
  1447. Instead decompressing the file and instantiating the resulting raster, GDAL can
  1448. directly access compressed files using the ``/vsizip/``, ``/vsigzip/``, or
  1449. ``/vsitar/`` virtual filesystems:
  1450. .. code-block:: pycon
  1451. >>> from django.contrib.gis.gdal import GDALRaster
  1452. >>> rst = GDALRaster("/vsizip/path/to/your/file.zip/path/to/raster.tif")
  1453. >>> rst = GDALRaster("/vsigzip/path/to/your/file.gz")
  1454. >>> rst = GDALRaster("/vsitar/path/to/your/file.tar/path/to/raster.tif")
  1455. Network rasters
  1456. ^^^^^^^^^^^^^^^
  1457. GDAL can support online resources and storage providers transparently. As long
  1458. as it's built with such capabilities.
  1459. To access a public raster file with no authentication, you can use
  1460. ``/vsicurl/``:
  1461. .. code-block:: pycon
  1462. >>> from django.contrib.gis.gdal import GDALRaster
  1463. >>> rst = GDALRaster("/vsicurl/https://example.com/raster.tif")
  1464. >>> rst.name
  1465. '/vsicurl/https://example.com/raster.tif'
  1466. For commercial storage providers (e.g. ``/vsis3/``) the system should be
  1467. previously configured for authentication and possibly other settings (see the
  1468. `GDAL Virtual Filesystems documentation`_ for available options).
  1469. .. _`GDAL Virtual Filesystems documentation`: https://gdal.org/user/virtual_file_systems.html
  1470. Settings
  1471. ========
  1472. .. setting:: GDAL_LIBRARY_PATH
  1473. ``GDAL_LIBRARY_PATH``
  1474. ---------------------
  1475. A string specifying the location of the GDAL library. Typically,
  1476. this setting is only used if the GDAL library is in a non-standard
  1477. location (e.g., ``/home/john/lib/libgdal.so``).
  1478. Exceptions
  1479. ==========
  1480. .. exception:: GDALException
  1481. The base GDAL exception, indicating a GDAL-related error.
  1482. .. exception:: SRSException
  1483. An exception raised when an error occurs when constructing or using a
  1484. spatial reference system object.