thumbnails.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. #!/usr/bin/env python3
  2. #
  3. # thumbnails.py: Create thumbnail images of the GRASS color tables
  4. #
  5. # AUTHOR: Vaclav Petras (non-PPM version using r.mapcalc)
  6. # Glynn Clements (Python version)
  7. # Earlier Bourne script version by Hamish Bowman,
  8. # https://grasswiki.osgeo.org/wiki/Talk:Color_tables
  9. #
  10. # (C) 2009-2017 by the GRASS Development Team
  11. # This program is free software under the GNU General Public
  12. # License (>=v2). Read the file COPYING that comes with GRASS
  13. # for details.
  14. #
  15. import sys
  16. import os
  17. import atexit
  18. import grass.script as grass
  19. tmp_grad_abs = None
  20. tmp_grad_rel = None
  21. def cleanup():
  22. if tmp_grad_rel:
  23. grass.run_command('g.remove', flags='f', type='raster',
  24. name=tmp_grad_rel, quiet=True)
  25. if tmp_grad_abs:
  26. grass.run_command('g.remove', flags='f', type='raster',
  27. name=tmp_grad_abs, quiet=True)
  28. def make_gradient(path):
  29. fh = open(path)
  30. text = fh.read()
  31. fh.close()
  32. lines = text.splitlines()
  33. records = list()
  34. for line in lines:
  35. if line.startswith("#"):
  36. # skip comments
  37. continue
  38. if len(line) == 0:
  39. # skip empty lines
  40. continue
  41. records.append(line.split())
  42. records = [record for record in records
  43. if record[0] != 'nv' and record[0] != 'default']
  44. relative = False
  45. absolute = False
  46. for record in records:
  47. if record[0].endswith("%"):
  48. relative = True
  49. record[0] = record[0].rstrip("%")
  50. else:
  51. absolute = True
  52. if absolute:
  53. if relative:
  54. minval = -0.04
  55. maxval = 0.04
  56. else:
  57. minval = float(records[0][0])
  58. # shift min up for floating point values so that
  59. # first color in color table is visible
  60. if '.' in records[0][0]:
  61. # assumes that 1% of min does not go to the next value
  62. # and is still represented as float and does not make
  63. # too much difference in color
  64. # works better than 1% of the difference to the next value
  65. minval += abs(minval / 100)
  66. maxval = float(records[-1][0])
  67. maxval = min(maxval, 2500000)
  68. if os.path.basename(path) in ('ndvi', 'ndwi', 'ndwi2'):
  69. minval = -1.0
  70. maxval = 1.0
  71. if os.path.basename(path) == 'ndvi_MODIS':
  72. minval = -10000.0
  73. maxval = 10000.0
  74. if os.path.basename(path) == 'population_dens':
  75. maxval = 1000.0
  76. if os.path.basename(path) == 'precipitation':
  77. maxval = 2000.0
  78. if os.path.basename(path) in ('terrain', 'srtm', 'srtm_plus'):
  79. minval = -500.0
  80. maxval = 3000.0
  81. grad = tmp_grad_abs
  82. grass.mapcalc("$grad = "
  83. " float($min) + (col() - 1) * "
  84. " (float($max) - float($min)) / ncols()",
  85. grad=tmp_grad_abs, min=minval, max=maxval, quiet=True)
  86. else:
  87. grad = tmp_grad_rel
  88. return grad
  89. def make_image(output_dir, table, grad, height, width):
  90. outfile = os.path.join(output_dir, "colortables", "%s.png" % table)
  91. os.environ['GRASS_RENDER_FILE'] = outfile
  92. grass.run_command("r.colors", map=grad, color=table, quiet=True)
  93. os.environ['GRASS_RENDER_FRAME'] = '%f,%f,%f,%f' % (0, height, 2, width - 2)
  94. grass.run_command("d.rast", map=grad, quiet=True)
  95. if 1:
  96. os.environ['GRASS_RENDER_FRAME'] = '%f,%f,%f,%f' % (0, height, 0, width)
  97. grass.write_command("d.graph", quiet=True, flags='m', stdin="""
  98. width 1
  99. color {outcolor}
  100. polyline
  101. {x1} {y1}
  102. {x2} {y1}
  103. {x2} {y2}
  104. {x1} {y2}
  105. {x1} {y1}
  106. color {incolor}
  107. polyline
  108. {x3} {y3}
  109. {x4} {y3}
  110. {x4} {y4}
  111. {x3} {y4}
  112. {x3} {y3}
  113. """.format(x1=1, x2=width, y1=0, y2=height - 1,
  114. x3=2, x4=width - 1, y3=1, y4=height - 2,
  115. outcolor='white', incolor='black'))
  116. def main():
  117. global tmp_img, tmp_grad_abs, tmp_grad_rel
  118. height = 15
  119. width = 85
  120. os.environ['GRASS_OVERWRITE'] = '1'
  121. color_dir = os.path.join(os.environ['GISBASE'], "etc", "colors")
  122. output_dir = os.path.join(os.environ['GISBASE'], "docs", "html")
  123. if not os.path.exists(output_dir):
  124. os.makedirs(output_dir)
  125. pid = os.getpid()
  126. tmp_grad_abs = "tmp_grad_abs_%d" % pid
  127. tmp_grad_rel = "tmp_grad_rel_%d" % pid
  128. os.environ['GRASS_RENDER_WIDTH'] = '%d' % width
  129. os.environ['GRASS_RENDER_HEIGHT'] = '%d' % height
  130. os.environ['GRASS_RENDER_TRUECOLOR'] = 'TRUE'
  131. # for multiple d commands (requires to delete/move image each time)
  132. os.environ['GRASS_RENDER_FILE_READ'] = 'TRUE'
  133. os.environ['GRASS_RENDER_FILE_MAPPED'] = 'FALSE'
  134. os.environ['GRASS_RENDER_TRANSPARENT'] = 'FALSE'
  135. os.environ['GRASS_RENDER_BACKGROUNDCOLOR'] = 'ffffff'
  136. os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'
  137. # for one pixel wide lines
  138. os.environ['GRASS_RENDER_ANTIALIAS'] = 'none'
  139. for var in ['GRASS_RENDER_LINE_WIDTH']:
  140. if var in os.environ:
  141. del os.environ[var]
  142. os.environ['GRASS_ANTIALIAS'] = 'none'
  143. grass.use_temp_region()
  144. grass.run_command('g.region', s=0, w=0, n=height, e=width,
  145. rows=height, cols=width, res=1, flags='a')
  146. grass.mapcalc("$grad = float(col())", grad=tmp_grad_rel, quiet=True)
  147. for table in os.listdir(color_dir):
  148. path = os.path.join(color_dir, table)
  149. grad = make_gradient(path)
  150. make_image(output_dir, table, grad,
  151. height=height, width=width)
  152. grass.mapcalc("$grad = col()", grad=tmp_grad_abs, quiet=True)
  153. for table in ['grey.eq', 'grey.log', 'random']:
  154. make_image(output_dir, table, tmp_grad_abs,
  155. height=height, width=width)
  156. if __name__ == "__main__":
  157. atexit.register(cleanup)
  158. main()