__init__.py 25 KB

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