patch.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Apr 2 18:57:42 2013
  4. @author: pietro
  5. """
  6. from __future__ import (nested_scopes, generators, division, absolute_import,
  7. with_statement, print_function, unicode_literals)
  8. from grass.pygrass.gis.region import Region
  9. from grass.pygrass.raster import RasterRow
  10. from grass.pygrass.functions import coor2pixel
  11. def get_start_end_index(bbox_list):
  12. """Convert a Bounding Box to a list of the index of
  13. column start, end, row start and end
  14. """
  15. ss_list = []
  16. reg = Region()
  17. for bbox in bbox_list:
  18. r_start, c_start = coor2pixel((bbox.west, bbox.north), reg)
  19. r_end, c_end = coor2pixel((bbox.east, bbox.south), reg)
  20. ss_list.append((int(r_start), int(r_end), int(c_start), int(c_end)))
  21. return ss_list
  22. def rpatch_row(rast, rasts, bboxes):
  23. """Patch a row of bound boxes."""
  24. sei = get_start_end_index(bboxes)
  25. # instantiate two buffer
  26. buff = rasts[0][0]
  27. rbuff = rasts[0][0]
  28. r_start, r_end, c_start, c_end = sei[0]
  29. for row in range(r_start, r_end):
  30. for col, ras in enumerate(rasts):
  31. r_start, r_end, c_start, c_end = sei[col]
  32. buff = ras.get_row(row, buff)
  33. rbuff[c_start:c_end] = buff[c_start:c_end]
  34. rast.put_row(rbuff)
  35. def rpatch_map(raster, mapset, mset_str, bbox_list, overwrite=False,
  36. start_row=0, start_col=0, prefix=''):
  37. """Patch raster using a bounding box list to trim the raster."""
  38. # Instantiate the RasterRow input objects
  39. rast = RasterRow(prefix + raster, mapset)
  40. rtype = RasterRow(name=raster, mapset=mset_str % (0, 0))
  41. rtype.open('r')
  42. rast.open('w', mtype=rtype.mtype, overwrite=overwrite)
  43. rtype.close()
  44. rasts = []
  45. for row, rbbox in enumerate(bbox_list):
  46. rrasts = []
  47. for col in range(len(rbbox)):
  48. rrasts.append(RasterRow(name=raster,
  49. mapset=mset_str % (start_row + row,
  50. start_col + col)))
  51. rrasts[-1].open('r')
  52. rasts.append(rrasts)
  53. rpatch_row(rast, rrasts, rbbox)
  54. for rst in rrasts:
  55. rst.close()
  56. del(rst)
  57. rast.close()