thumbnails.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. #!/usr/bin/env python
  2. #
  3. # thumbnails.py: Create thumbnail sample images of the various GRASS color rules
  4. #
  5. # AUTHOR: Python version by Glynn Clements
  6. # Earlier Bourne script version by Hamish Bowman,
  7. # http://grasswiki.osgeo.org/wiki/Talk:Color_tables
  8. #
  9. # (C) 2009-2013 by the GRASS Development Team
  10. # This program is free software under the GNU General Public
  11. # License (>=v2). Read the file COPYING that comes with GRASS
  12. # for details.
  13. #
  14. import sys
  15. import os
  16. import atexit
  17. import string
  18. import array
  19. import grass.script as grass
  20. tmp_img = None
  21. tmp_grad_abs = None
  22. tmp_grad_rel = None
  23. height = 85
  24. width = 15
  25. def cleanup():
  26. if tmp_img:
  27. grass.try_remove(tmp_img)
  28. if tmp_grad_rel:
  29. grass.run_command('g.remove', flags = 'f', type = 'rast',
  30. pattern = tmp_grad_rel, quiet = True)
  31. if tmp_grad_abs:
  32. grass.run_command('g.remove', flags = 'f', type = 'rast',
  33. pattern = tmp_grad_abs, quiet = True)
  34. # def rotate(src, dst):
  35. # grass.call(["convert", "-rotate", "90", src, dst])
  36. def read_ppm(src):
  37. fh = open(src, "rb")
  38. text = fh.read()
  39. fh.close()
  40. i = 0
  41. j = text.find('\n', i)
  42. if text[i:j] != 'P6':
  43. raise IOError
  44. i = j + 1
  45. j = text.find('\n', i)
  46. w, h = text[i:j].split()
  47. if int(w) != width or int(h) != height:
  48. raise IOError
  49. i = j + 1
  50. j = text.find('\n', i)
  51. maxval = text[i:j]
  52. if int(maxval) != 255:
  53. raise IOError
  54. i = j + 1
  55. return array.array('B', text[i:])
  56. def write_ppm(dst, data):
  57. w = height
  58. h = width
  59. fh = open(dst, "wb")
  60. fh.write("P6\n%d %d\n%d\n" % (w, h, 255))
  61. data.tofile(fh)
  62. fh.close()
  63. def rotate_ppm(srcd):
  64. dstd = array.array('B', len(srcd) * '\0')
  65. for y in xrange(height):
  66. for x in xrange(width):
  67. for c in xrange(3):
  68. dstd[(x * height + (height - 1 - y)) * 3 + c] = srcd[(y * width + x) * 3 + c]
  69. return dstd
  70. def flip_ppm(srcd):
  71. dstd = array.array('B', len(srcd) * '\0')
  72. stride = width * 3
  73. for y in xrange(height):
  74. dy = (height - 1 - y)
  75. dstd[dy * stride:(dy + 1) * stride] = srcd[y * stride:(y + 1) * stride]
  76. return dstd
  77. def ppmtopng(dst, src):
  78. if grass.find_program("g.ppmtopng", '--help'):
  79. grass.run_command('g.ppmtopng', input = src, output = dst, quiet = True)
  80. elif grass.find_program("pnmtopng"):
  81. fh = open(dst, 'wb')
  82. grass.call(["pnmtopng", src], stdout = fh)
  83. fh.close()
  84. elif grass.find_program("convert"):
  85. grass.call(["convert", src, dst])
  86. else:
  87. grass.fatal(_("Cannot find g.ppmtopng, pnmtopng or convert"))
  88. def convert_and_rotate(src, dst, flip = False):
  89. ppm = read_ppm(src)
  90. if flip:
  91. ppm = flip_ppm(ppm)
  92. ppm = rotate_ppm(ppm)
  93. write_ppm(tmp_img, ppm)
  94. ppmtopng(dst, tmp_img)
  95. def make_gradient(path):
  96. fh = open(path)
  97. text = fh.read()
  98. fh.close()
  99. lines = text.splitlines()
  100. records = list()
  101. for line in lines:
  102. if line.startswith("#"):
  103. # skip comments
  104. continue
  105. if len(line) == 0:
  106. # skip empty lines
  107. continue
  108. records.append(line.split())
  109. records = [record for record in records if record[0] != 'nv' and record[0] != 'default']
  110. relative = False
  111. absolute = False
  112. for record in records:
  113. if record[0].endswith("%"):
  114. relative = True
  115. record[0] = record[0].rstrip("%")
  116. else:
  117. absolute = True
  118. if absolute:
  119. if relative:
  120. minval = -0.04
  121. maxval = 0.04
  122. else:
  123. minval = float(records[0][0])
  124. maxval = float(records[-1][0])
  125. maxval = min(maxval, 2500000)
  126. grad = tmp_grad_abs
  127. grass.mapcalc("$grad = if(row()==1, float($min), float($max))",
  128. grad = tmp_grad_abs, min = minval, max = maxval, quiet = True)
  129. else:
  130. grad = tmp_grad_rel
  131. return grad
  132. def make_image(output_dir, table, grad, discrete = False):
  133. if discrete:
  134. lines, cols = height, 1
  135. else:
  136. lines, cols = None, None
  137. grass.run_command("r.colors", map = grad, color = table, quiet = True)
  138. grass.run_command("d.colortable", flags = 'n', map = grad,
  139. lines = lines, cols = cols, quiet = True)
  140. outfile = os.path.join(output_dir, "colortables", "%s.png" % table)
  141. convert_and_rotate(tmp_img, outfile, discrete)
  142. def main():
  143. global tmp_img, tmp_grad_abs, tmp_grad_rel
  144. os.environ['GRASS_OVERWRITE'] = '1'
  145. color_dir = os.path.join(os.environ['GISBASE'], "etc", "colors")
  146. output_dir = os.path.join(os.environ['GISBASE'], "docs", "html")
  147. if not os.path.exists(output_dir):
  148. os.makedirs(output_dir)
  149. pid = os.getpid()
  150. tmp_grad_abs = "tmp_grad_abs_%d" % pid
  151. tmp_grad_rel = "tmp_grad_rel_%d" % pid
  152. tmp_img = grass.tempfile() + ".ppm"
  153. os.environ['GRASS_WIDTH'] = '%d' % width
  154. os.environ['GRASS_HEIGHT'] = '%d' % height
  155. os.environ['GRASS_FRAME'] = '%f,%f,%f,%f' % (0,height,0,width)
  156. os.environ['GRASS_PNGFILE'] = tmp_img
  157. os.environ['GRASS_TRUECOLOR'] = 'TRUE'
  158. os.environ['GRASS_PNG_READ'] = 'FALSE'
  159. os.environ['GRASS_PNG_MAPPED'] = 'FALSE'
  160. os.environ['GRASS_TRANSPARENT'] = 'FALSE'
  161. os.environ['GRASS_BACKGROUNDCOLOR'] = 'ffffff'
  162. os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'
  163. for var in ['GRASS_LINE_WIDTH', 'GRASS_ANTIALIAS']:
  164. if var in os.environ:
  165. del os.environ[var]
  166. grass.use_temp_region()
  167. grass.run_command('g.region', rows = 100, cols = 100)
  168. grass.mapcalc("$grad = row()/1.0", grad = tmp_grad_rel, quiet = True)
  169. for table in os.listdir(color_dir):
  170. path = os.path.join(color_dir, table)
  171. grad = make_gradient(path)
  172. make_image(output_dir, table, grad)
  173. grass.mapcalc("$grad = row()", grad = tmp_grad_abs, quiet = True)
  174. for table in ['grey.eq', 'grey.log', 'random']:
  175. make_image(output_dir, table, tmp_grad_abs, True)
  176. if __name__ == "__main__":
  177. atexit.register(cleanup)
  178. main()