__init__.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. # -*- coding: utf-8 -*-
  2. from __future__ import (nested_scopes, generators, division, absolute_import,
  3. with_statement, print_function, unicode_literals)
  4. import ctypes
  5. import numpy as np
  6. #
  7. # import GRASS modules
  8. #
  9. from grass.script import fatal
  10. import grass.lib.gis as libgis
  11. import grass.lib.raster as libraster
  12. import grass.lib.rowio as librowio
  13. libgis.G_gisinit('')
  14. #
  15. # import pygrass modules
  16. #
  17. from grass.pygrass.errors import OpenError, must_be_open
  18. from grass.pygrass.gis.region import Region
  19. from grass.pygrass import utils
  20. #
  21. # import raster classes
  22. #
  23. from grass.pygrass.raster.abstract import RasterAbstractBase
  24. from grass.pygrass.raster.raster_type import TYPE as RTYPE, RTYPE_STR
  25. from grass.pygrass.raster.buffer import Buffer
  26. from grass.pygrass.raster.segment import Segment
  27. from grass.pygrass.raster.rowio import RowIO
  28. WARN_OVERWRITE = "Raster map <{0}> already exists and will be overwritten"
  29. test_raster_name = "Raster_test_map"
  30. class RasterRow(RasterAbstractBase):
  31. """Raster_row_access": Inherits: "Raster_abstract_base" and implements
  32. the default row access of the Rast library.
  33. * Implements row access using row id
  34. * The get_row() method must accept a Row object as argument that will
  35. be used for value storage, so no new buffer will be allocated
  36. * Implements sequential writing of rows
  37. * Implements indexed value read only access using the [row][col]
  38. operator
  39. * Implements the [row] read method that returns a new Row object
  40. * Writing is limited using the put_row() method which accepts a
  41. Row as argument
  42. * No mathematical operation like __add__ and stuff for the Raster
  43. object (only for rows), since r.mapcalc is more sophisticated and
  44. faster
  45. * Raises IndexError if [row] is out of range
  46. Examples:
  47. >>> elev = RasterRow(test_raster_name)
  48. >>> elev.exist()
  49. True
  50. >>> elev.is_open()
  51. False
  52. >>> elev.open()
  53. >>> elev.is_open()
  54. True
  55. >>> elev.has_cats()
  56. True
  57. >>> elev.mode
  58. u'r'
  59. >>> elev.mtype
  60. 'CELL'
  61. >>> elev.num_cats()
  62. 16
  63. >>> elev.info.range
  64. (11, 44)
  65. >>> elev.info.cols
  66. 4
  67. >>> elev.info.rows
  68. 4
  69. Editing the history
  70. >>> elev.hist.read()
  71. >>> elev.hist.title = "A test map"
  72. >>> elev.hist.write()
  73. >>> elev.hist.title
  74. 'A test map'
  75. >>> elev.hist.keyword
  76. 'This is a test map'
  77. >>> attrs = list(elev.hist)
  78. >>> attrs[0]
  79. ('name', u'Raster_test_map')
  80. >>> attrs[2]
  81. ('mtype', '')
  82. Each Raster map have an attribute call ``cats`` that allow user
  83. to interact with the raster categories.
  84. >>> elev.cats # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  85. [(u'A', 11, None),
  86. (u'B', 12, None),
  87. ...
  88. (u'P', 44, None)]
  89. >>> elev.cats.labels() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  90. [u'A', u'B', u'C', u'D', u'E',
  91. u'F', u'G', u'H', u'I', u'J',
  92. u'K', u'L', u'M', u'n', u'O', u'P']
  93. >>> elev.cats[0]
  94. (u'A', 11, None)
  95. >>> elev.cats[2]
  96. (u'C', 13, None)
  97. >>> elev.cats[0] = ('AA', 11)
  98. >>> elev.cats[1] = ('BB', 12)
  99. >>> elev.cats.write()
  100. >>> elev.cats.read()
  101. >>> elev.cats[0]
  102. (u'AA', 11, None)
  103. >>> elev.cats[1]
  104. (u'BB', 12, None)
  105. Open a raster map using the *with statement*:
  106. >>> with RasterRow(test_raster_name) as elev:
  107. ... for row in elev:
  108. ... row
  109. Buffer([11, 21, 31, 41], dtype=int32)
  110. Buffer([12, 22, 32, 42], dtype=int32)
  111. Buffer([13, 23, 33, 43], dtype=int32)
  112. Buffer([14, 24, 34, 44], dtype=int32)
  113. >>> elev.is_open()
  114. False
  115. """
  116. def __init__(self, name, mapset='', *args, **kargs):
  117. super(RasterRow, self).__init__(name, mapset, *args, **kargs)
  118. # mode = "r", method = "row",
  119. @must_be_open
  120. def get_row(self, row, row_buffer=None):
  121. """Private method that return the row using the read mode
  122. call the `Rast_get_row` C function.
  123. :param row: the number of row to obtain
  124. :type row: int
  125. :param row_buffer: Buffer object instance with the right dim and type
  126. :type row_buffer: Buffer
  127. >>> elev = RasterRow(test_raster_name)
  128. >>> elev.open()
  129. >>> elev[0]
  130. Buffer([11, 21, 31, 41], dtype=int32)
  131. >>> elev.get_row(0)
  132. Buffer([11, 21, 31, 41], dtype=int32)
  133. """
  134. if row_buffer is None:
  135. row_buffer = Buffer((self._cols,), self.mtype)
  136. libraster.Rast_get_row(self._fd, row_buffer.p, row, self._gtype)
  137. return row_buffer
  138. @must_be_open
  139. def put_row(self, row):
  140. """Private method to write the row sequentially.
  141. :param row: a Row object to insert into raster
  142. :type row: Buffer object
  143. """
  144. libraster.Rast_put_row(self._fd, row.p, self._gtype)
  145. def open(self, mode=None, mtype=None, overwrite=None):
  146. """Open the raster if exist or created a new one.
  147. :param str mode: Specify if the map will be open with read or write mode
  148. ('r', 'w')
  149. :param str type: If a new map is open, specify the type of the map(`CELL`,
  150. `FCELL`, `DCELL`)
  151. :param bool overwrite: Use this flag to set the overwrite mode of existing
  152. raster maps
  153. if the map already exist, automatically check the type and set:
  154. * self.mtype
  155. Set all the privite, attributes:
  156. * self._fd;
  157. * self._gtype
  158. * self._rows and self._cols
  159. """
  160. self.mode = mode if mode else self.mode
  161. self.mtype = mtype if mtype else self.mtype
  162. self.overwrite = overwrite if overwrite is not None else self.overwrite
  163. if self.mode == 'r':
  164. if self.exist():
  165. self.info.read()
  166. self.cats.mtype = self.mtype
  167. self.cats.read()
  168. self.hist.read()
  169. self._fd = libraster.Rast_open_old(self.name, self.mapset)
  170. self._gtype = libraster.Rast_get_map_type(self._fd)
  171. self.mtype = RTYPE_STR[self._gtype]
  172. else:
  173. str_err = _("The map does not exist, I can't open in 'r' mode")
  174. raise OpenError(str_err)
  175. elif self.mode == 'w':
  176. if self.exist():
  177. if not self.overwrite:
  178. str_err = _("Raster map <{0}> already exists"
  179. " and will be not overwritten")
  180. raise OpenError(str_err.format(self))
  181. if self._gtype is None:
  182. raise OpenError(_("Raster type not defined"))
  183. self._fd = libraster.Rast_open_new(self.name, self._gtype)
  184. else:
  185. raise OpenError("Open mode: %r not supported,"
  186. " valid mode are: r, w")
  187. # read rows and cols from the active region
  188. self._rows = libraster.Rast_window_rows()
  189. self._cols = libraster.Rast_window_cols()
  190. class RasterRowIO(RasterRow):
  191. """Raster_row_cache_access": The same as "Raster_row_access" but uses
  192. the ROWIO library for cached row access
  193. """
  194. def __init__(self, name, *args, **kargs):
  195. self.rowio = RowIO()
  196. super(RasterRowIO, self).__init__(name, *args, **kargs)
  197. def open(self, mode=None, mtype=None, overwrite=False):
  198. """Open the raster if exist or created a new one.
  199. :param mode: specify if the map will be open with read or write mode
  200. ('r', 'w')
  201. :type mode: str
  202. :param type: if a new map is open, specify the type of the map(`CELL`,
  203. `FCELL`, `DCELL`)
  204. :type type: str
  205. :param overwrite: use this flag to set the overwrite mode of existing
  206. raster maps
  207. :type overwrite: bool
  208. """
  209. super(RasterRowIO, self).open(mode, mtype, overwrite)
  210. self.rowio.open(self._fd, self._rows, self._cols, self.mtype)
  211. @must_be_open
  212. def close(self):
  213. """Function to close the raster"""
  214. self.rowio.release()
  215. libraster.Rast_close(self._fd)
  216. # update rows and cols attributes
  217. self._rows = None
  218. self._cols = None
  219. self._fd = None
  220. @must_be_open
  221. def get_row(self, row, row_buffer=None):
  222. """This method returns the row using:
  223. * the read mode and
  224. * `rowcache` method
  225. :param row: the number of row to obtain
  226. :type row: int
  227. :param row_buffer: Specify the Buffer object that will be instantiate
  228. :type row_buffer: Buffer object
  229. >>> elev = RasterRowIO(test_raster_name)
  230. >>> elev.open('r')
  231. >>> for row in elev:
  232. ... row
  233. Buffer([11, 21, 31, 41], dtype=int32)
  234. Buffer([12, 22, 32, 42], dtype=int32)
  235. Buffer([13, 23, 33, 43], dtype=int32)
  236. Buffer([14, 24, 34, 44], dtype=int32)
  237. >>> elev.close()
  238. """
  239. if row_buffer is None:
  240. row_buffer = Buffer((self._cols,), self.mtype)
  241. rowio_buf = librowio.Rowio_get(ctypes.byref(self.rowio.c_rowio), row)
  242. ctypes.memmove(row_buffer.p, rowio_buf, self.rowio.row_size)
  243. return row_buffer
  244. class RasterSegment(RasterAbstractBase):
  245. """Raster_segment_access": Inherits "Raster_abstract_base" and uses the
  246. segment library for cached randomly reading and writing access.
  247. * Implements the [row][col] operator for read and write access using
  248. Segment_get() and Segment_put() functions internally
  249. * Implements row read and write access with the [row] operator using
  250. Segment_get_row() Segment_put_row() internally
  251. * Implements the get_row() and put_row() method using
  252. Segment_get_row() Segment_put_row() internally
  253. * Implements the flush_segment() method
  254. * Implements the copying of raster maps to segments and vice verse
  255. * Overwrites the open and close methods
  256. * No mathematical operation like __add__ and stuff for the Raster
  257. object (only for rows), since r.mapcalc is more sophisticated and
  258. faster
  259. """
  260. def __init__(self, name, srows=64, scols=64, maxmem=100,
  261. *args, **kargs):
  262. self.segment = Segment(srows, scols, maxmem)
  263. super(RasterSegment, self).__init__(name, *args, **kargs)
  264. def _get_mode(self):
  265. return self._mode
  266. def _set_mode(self, mode):
  267. if mode and mode.lower() not in ('r', 'w', 'rw'):
  268. str_err = _("Mode type: {0} not supported ('r', 'w','rw')")
  269. raise ValueError(str_err.format(mode))
  270. self._mode = mode
  271. mode = property(fget=_get_mode, fset=_set_mode,
  272. doc="Set or obtain the opening mode of raster")
  273. def __setitem__(self, key, row):
  274. """Return the row of Raster object, slice allowed."""
  275. if isinstance(key, slice):
  276. # Get the start, stop, and step from the slice
  277. return [self.put_row(ii, row)
  278. for ii in range(*key.indices(len(self)))]
  279. elif isinstance(key, tuple):
  280. x, y = key
  281. return self.put(x, y, row)
  282. elif isinstance(key, int):
  283. if key < 0: # Handle negative indices
  284. key += self._rows
  285. if key >= self._rows:
  286. raise IndexError(_("Index out of range: %r.") % key)
  287. return self.put_row(key, row)
  288. else:
  289. raise TypeError("Invalid argument type.")
  290. @must_be_open
  291. def map2segment(self):
  292. """Transform an existing map to segment file.
  293. """
  294. row_buffer = Buffer((self._cols), self.mtype)
  295. for row in range(self._rows):
  296. libraster.Rast_get_row(
  297. self._fd, row_buffer.p, row, self._gtype)
  298. self.segment.put_row(row, row_buffer)
  299. @must_be_open
  300. def segment2map(self):
  301. """Transform the segment file to a map.
  302. """
  303. row_buffer = Buffer((self._cols), self.mtype)
  304. for row in range(self._rows):
  305. row_buffer = self.segment.get_row(row, row_buffer)
  306. libraster.Rast_put_row(self._fd, row_buffer.p, self._gtype)
  307. @must_be_open
  308. def get_row(self, row, row_buffer=None):
  309. """Return the row using the `segment.get_row` method
  310. :param row: specify the row number
  311. :type row: int
  312. :param row_buffer: specify the Buffer object that will be instantiate
  313. :type row_buffer: Buffer object
  314. >>> elev = RasterRowIO(test_raster_name)
  315. >>> elev.open('r')
  316. >>> for row in elev:
  317. ... row
  318. Buffer([11, 21, 31, 41], dtype=int32)
  319. Buffer([12, 22, 32, 42], dtype=int32)
  320. Buffer([13, 23, 33, 43], dtype=int32)
  321. Buffer([14, 24, 34, 44], dtype=int32)
  322. >>> elev.close()
  323. >>> with RasterSegment(test_raster_name) as elev:
  324. ... for row in elev:
  325. ... row
  326. Buffer([11, 21, 31, 41], dtype=int32)
  327. Buffer([12, 22, 32, 42], dtype=int32)
  328. Buffer([13, 23, 33, 43], dtype=int32)
  329. Buffer([14, 24, 34, 44], dtype=int32)
  330. """
  331. if row_buffer is None:
  332. row_buffer = Buffer((self._cols), self.mtype)
  333. return self.segment.get_row(row, row_buffer)
  334. @must_be_open
  335. def put_row(self, row, row_buffer):
  336. """Write the row using the `segment.put_row` method
  337. :param row: a Row object to insert into raster
  338. :type row: Buffer object
  339. Input and output must have the same type in case of row copy
  340. >>> map_a = RasterSegment(test_raster_name)
  341. >>> map_b = RasterSegment(test_raster_name + "_segment")
  342. >>> map_a.open('r')
  343. >>> map_b.open('w', mtype="CELL", overwrite=True)
  344. >>> for row in xrange(map_a.info.rows):
  345. ... map_b[row] = map_a[row] + 1000
  346. >>> map_a.close()
  347. >>> map_b.close()
  348. >>> map_b = RasterSegment(test_raster_name + "_segment")
  349. >>> map_b.open("r")
  350. >>> for row in map_b:
  351. ... row
  352. Buffer([1011, 1021, 1031, 1041], dtype=int32)
  353. Buffer([1012, 1022, 1032, 1042], dtype=int32)
  354. Buffer([1013, 1023, 1033, 1043], dtype=int32)
  355. Buffer([1014, 1024, 1034, 1044], dtype=int32)
  356. >>> map_b.close()
  357. """
  358. self.segment.put_row(row, row_buffer)
  359. @must_be_open
  360. def get(self, row, col):
  361. """Return the map value using the `segment.get` method
  362. :param row: Specify the row number
  363. :type row: int
  364. :param col: Specify the column number
  365. :type col: int
  366. >>> elev = RasterSegment(test_raster_name)
  367. >>> elev.open('r')
  368. >>> for i in xrange(4):
  369. ... elev.get(i,i)
  370. 11
  371. 22
  372. 33
  373. 44
  374. >>> elev.close()
  375. >>> with RasterSegment(test_raster_name) as elev:
  376. ... elev.get(0,0)
  377. ... elev.get(1,1)
  378. ... elev.get(2,2)
  379. ... elev.get(3,3)
  380. 11
  381. 22
  382. 33
  383. 44
  384. """
  385. return self.segment.get(row, col)
  386. @must_be_open
  387. def put(self, row, col, val):
  388. """Write the value to the map using the `segment.put` method
  389. :param row: Specify the row number
  390. :type row: int
  391. :param col: Specify the column number
  392. :type col: int
  393. :param val: Specify the value that will be write to the map cell
  394. :type val: value
  395. >>> map_a = RasterSegment(test_raster_name)
  396. >>> map_b = RasterSegment(test_raster_name + "_segment")
  397. >>> map_a.open('r')
  398. >>> map_b.open('w', mtype="FCELL", overwrite=True)
  399. >>> for row in xrange(map_a.info.rows):
  400. ... for col in xrange(map_a.info.cols):
  401. ... value = map_a.get(row,col)
  402. ... map_b.put(row,col,value + 100)
  403. >>> map_a.close()
  404. >>> map_b.close()
  405. >>> map_b = RasterSegment(test_raster_name + "_segment")
  406. >>> map_b.open("r")
  407. >>> for row in map_b:
  408. ... row
  409. Buffer([ 111., 121., 131., 141.], dtype=float32)
  410. Buffer([ 112., 122., 132., 142.], dtype=float32)
  411. Buffer([ 113., 123., 133., 143.], dtype=float32)
  412. Buffer([ 114., 124., 134., 144.], dtype=float32)
  413. >>> map_b.close()
  414. """
  415. self.segment.val.value = val
  416. self.segment.put(row, col)
  417. def open(self, mode=None, mtype=None, overwrite=None):
  418. """Open the map, if the map already exist: determine the map type
  419. and copy the map to the segment files;
  420. else, open a new segment map.
  421. :param mode: specify if the map will be open with read, write or
  422. read/write mode ('r', 'w', 'rw')
  423. :type mode: str
  424. :param mtype: specify the map type, valid only for new maps: CELL,
  425. FCELL, DCELL
  426. :type mtype: str
  427. :param overwrite: use this flag to set the overwrite mode of existing
  428. raster maps
  429. :type overwrite: bool
  430. """
  431. # read rows and cols from the active region
  432. self._rows = libraster.Rast_window_rows()
  433. self._cols = libraster.Rast_window_cols()
  434. self.mode = mode if mode else self.mode
  435. self.mtype = mtype if mtype else self.mtype
  436. self.overwrite = overwrite if overwrite is not None else self.overwrite
  437. if self.exist():
  438. self.info.read()
  439. self.cats.mtype = self.mtype
  440. self.cats.read()
  441. self.hist.read()
  442. if ((self.mode == "w" or self.mode == "rw") and
  443. self.overwrite is False):
  444. str_err = _("Raster map <{0}> already exists. Use overwrite.")
  445. fatal(str_err.format(self))
  446. # We copy the raster map content into the segments
  447. if self.mode == "rw" or self.mode == "r":
  448. self._fd = libraster.Rast_open_old(self.name, self.mapset)
  449. self._gtype = libraster.Rast_get_map_type(self._fd)
  450. self.mtype = RTYPE_STR[self._gtype]
  451. # initialize the segment, I need to determine the mtype of the
  452. # map
  453. # before to open the segment
  454. self.segment.open(self)
  455. self.map2segment()
  456. self.segment.flush()
  457. self.cats.read()
  458. self.hist.read()
  459. if self.mode == "rw":
  460. # warning(_(WARN_OVERWRITE.format(self)))
  461. # Close the file descriptor and open it as new again
  462. libraster.Rast_close(self._fd)
  463. self._fd = libraster.Rast_open_new(
  464. self.name, self._gtype)
  465. # Here we simply overwrite the existing map without content copying
  466. elif self.mode == "w":
  467. # warning(_(WARN_OVERWRITE.format(self)))
  468. self._gtype = RTYPE[self.mtype]['grass type']
  469. self.segment.open(self)
  470. self._fd = libraster.Rast_open_new(self.name, self._gtype)
  471. else:
  472. if self.mode == "r":
  473. str_err = _("Raster map <{0}> does not exist")
  474. raise OpenError(str_err.format(self.name))
  475. self._gtype = RTYPE[self.mtype]['grass type']
  476. self.segment.open(self)
  477. self._fd = libraster.Rast_open_new(self.name, self._gtype)
  478. @must_be_open
  479. def close(self, rm_temp_files=True):
  480. """Close the map, copy the segment files to the map.
  481. :param rm_temp_files: if True all the segments file will be removed
  482. :type rm_temp_files: bool
  483. """
  484. if self.mode == "w" or self.mode == "rw":
  485. self.segment.flush()
  486. self.segment2map()
  487. if rm_temp_files:
  488. self.segment.close()
  489. else:
  490. self.segment.release()
  491. libraster.Rast_close(self._fd)
  492. # update rows and cols attributes
  493. self._rows = None
  494. self._cols = None
  495. self._fd = None
  496. def random_map_only_columns(mapname, mtype, overwrite=True, factor=100):
  497. region = Region()
  498. random_map = RasterRow(mapname)
  499. row_buf = Buffer((region.cols, ), mtype,
  500. buffer=(np.random.random(region.cols,) * factor).data)
  501. random_map.open('w', mtype, overwrite)
  502. for _ in range(region.rows):
  503. random_map.put_row(row_buf)
  504. random_map.close()
  505. return random_map
  506. def random_map(mapname, mtype, overwrite=True, factor=100):
  507. region = Region()
  508. random_map = RasterRow(mapname)
  509. random_map.open('w', mtype, overwrite)
  510. for _ in range(region.rows):
  511. row_buf = Buffer((region.cols, ), mtype,
  512. buffer=(np.random.random(region.cols,) * factor).data)
  513. random_map.put_row(row_buf)
  514. random_map.close()
  515. return random_map
  516. def raster2numpy(rastname, mapset=''):
  517. """Return a numpy array from a raster map
  518. :param str rastname: the name of raster map
  519. :parar str mapset: the name of mapset containig raster map
  520. """
  521. with RasterRow(rastname, mapset=mapset, mode='r') as rast:
  522. return np.array(rast)
  523. def raster2numpy_img(rastname, region, color="ARGB", array=None):
  524. """Convert a raster map layer into a string with
  525. 32Bit ARGB, 24Bit RGB or 8Bit Gray little endian encoding.
  526. Return a numpy array from a raster map of type uint8
  527. that contains the colored map data as 32 bit ARGB, 32Bit RGB
  528. or 8 bit image
  529. :param rastname: The name of raster map
  530. :type rastname: string
  531. :param region: The region to be used for raster map reading
  532. :type region: grass.pygrass.gis.region.Region
  533. :param color: "ARGB", "RGB", "GRAY1", "GRAY2"
  534. ARGB -> 32Bit RGB with alpha channel (0xAARRGGBB)
  535. RGB -> 32Bit RGB (0xffRRGGBB)
  536. GRAY1 -> grey scale formular: .33R+ .5G+ .17B
  537. GRAY2 -> grey scale formular: .30R+ .59G+ .11B
  538. :type color: String
  539. :param array: A numpy array (optional) to store the image,
  540. the array needs to setup as follows:
  541. array = np.ndarray((region.rows*region.cols*scale), np.uint8)
  542. scale = 4 in case of ARGB and RGB or scale = 1
  543. in case of Gray scale
  544. :type array: numpy.ndarray
  545. :return: A numpy array of size rows*cols*4 in case of ARGB, RGB and
  546. rows*cols*1 in case of gray scale
  547. Attention: This function will change the computational raster region
  548. of the current process while running.
  549. """
  550. from copy import deepcopy
  551. region_orig = deepcopy(region)
  552. # Set the raster region
  553. region.set_raster_region()
  554. scale = 1
  555. color_mode = 1
  556. if color.upper() == "ARGB":
  557. scale = 4
  558. color_mode = 1
  559. elif color.upper() == "RGB":
  560. scale = 4
  561. color_mode = 2
  562. elif color.upper() == "GRAY1":
  563. scale = 1
  564. color_mode = 3
  565. elif color.upper() == "GRAY2":
  566. scale = 1
  567. color_mode = 4
  568. if array is None:
  569. array = np.ndarray((region.rows * region.cols * scale), np.uint8)
  570. libraster.Rast_map_to_img_str(rastname, color_mode,
  571. array.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)))
  572. # Restore the raster region
  573. region_orig.set_raster_region()
  574. return array
  575. def numpy2raster(array, mtype, rastname, overwrite=False):
  576. """Save a numpy array to a raster map
  577. :param obj array: a numpy array
  578. :param obj mtype: the datatype of array
  579. :param str rastername: the name of output map
  580. :param bool overwrite: True to overwrite existing map
  581. """
  582. reg = Region()
  583. if (reg.rows, reg.cols) != array.shape:
  584. msg = "Region and array are different: %r != %r"
  585. raise TypeError(msg % ((reg.rows, reg.cols), array.shape))
  586. with RasterRow(rastname, mode='w', mtype=mtype, overwrite=overwrite) as new:
  587. newrow = Buffer((array.shape[1],), mtype=mtype)
  588. for row in array:
  589. newrow[:] = row[:]
  590. new.put_row(newrow)
  591. if __name__ == "__main__":
  592. import doctest
  593. from grass.pygrass.modules import Module
  594. Module("g.region", n=40, s=0, e=40, w=0, res=10)
  595. Module("r.mapcalc",
  596. expression="%s = row() + (10 * col())" % (test_raster_name),
  597. overwrite=True)
  598. Module("r.support", map=test_raster_name,
  599. title="A test map",
  600. history="Generated by r.mapcalc",
  601. description="This is a test map")
  602. cats = """11:A
  603. 12:B
  604. 13:C
  605. 14:D
  606. 21:E
  607. 22:F
  608. 23:G
  609. 24:H
  610. 31:I
  611. 32:J
  612. 33:K
  613. 34:L
  614. 41:M
  615. 42:n
  616. 43:O
  617. 44:P"""
  618. Module("r.category", rules="-", map=test_raster_name,
  619. stdin_=cats, separator=":")
  620. doctest.testmod()
  621. """Remove the generated vector map, if exist"""
  622. mset = utils.get_mapset_raster(test_raster_name, mapset='')
  623. if mset:
  624. Module("g.remove", flags='f', type='raster', name=test_raster_name)
  625. mset = utils.get_mapset_raster(test_raster_name + "_segment",
  626. mapset='')
  627. if mset:
  628. Module("g.remove", flags='f', type='raster',
  629. name=test_raster_name + "_segment")