Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

256 rader
12 KiB

  1. #!/usr/bin/env python3
  2. # Requires Python 3.2+ (or Python 2.7), the Python Pillow package,
  3. # and nona (from Hugin)
  4. # generate.py - A multires tile set generator for Pannellum
  5. # Extensions to cylindrical input and partial panoramas by David von Oheimb
  6. # Copyright (c) 2014-2018 Matthew Petroff
  7. #
  8. # Permission is hereby granted, free of charge, to any person obtaining a copy
  9. # of this software and associated documentation files (the "Software"), to deal
  10. # in the Software without restriction, including without limitation the rights
  11. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. # copies of the Software, and to permit persons to whom the Software is
  13. # furnished to do so, subject to the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be included in
  16. # all copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. # THE SOFTWARE.
  25. from __future__ import print_function
  26. import argparse
  27. from PIL import Image
  28. import os
  29. import sys
  30. import math
  31. import ast
  32. from distutils.spawn import find_executable
  33. import subprocess
  34. # Allow large images (this could lead to a denial of service attach if you're
  35. # running this script on user-submitted images.)
  36. Image.MAX_IMAGE_PIXELS = None
  37. # Find external programs
  38. try:
  39. nona = find_executable('nona')
  40. except KeyError:
  41. # Handle case of PATH not being set
  42. nona = None
  43. # Parse input
  44. parser = argparse.ArgumentParser(description='Generate a Pannellum multires tile set from a full or partial equirectangular or cylindrical panorama.',
  45. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  46. parser.add_argument('inputFile', metavar='INPUT',
  47. help='panorama to be processed')
  48. parser.add_argument('-C', '--cylindrical', action='store_true',
  49. help='input projection is cylindrical (default is equirectangular)')
  50. parser.add_argument('-H', '--haov', dest='haov', default=-1, type=float,
  51. help='horizontal angle of view (defaults to 360.0 for full panorama)')
  52. parser.add_argument('-F', '--hfov', dest='hfov', default=100.0, type=float,
  53. help='starting horizontal field of view (defaults to 100.0)')
  54. parser.add_argument('-V', '--vaov', dest='vaov', default=-1, type=float,
  55. help='vertical angle of view (defaults to 180.0 for full panorama)')
  56. parser.add_argument('-O', '--voffset', dest='vOffset', default=0.0, type=float,
  57. help='starting pitch position (defaults to 0.0)')
  58. parser.add_argument('-e', '--horizon', dest='horizon', default=0.0, type=int,
  59. help='offset of the horizon in pixels (negative if above middle, defaults to 0)')
  60. parser.add_argument('-o', '--output', dest='output', default='./output',
  61. help='output directory, optionally to be used as basePath (defaults to "./output")')
  62. parser.add_argument('-s', '--tilesize', dest='tileSize', default=512, type=int,
  63. help='tile size in pixels')
  64. parser.add_argument('-f', '--fallbacksize', dest='fallbackSize', default=1024, type=int,
  65. help='fallback tile size in pixels (defaults to 1024)')
  66. parser.add_argument('-c', '--cubesize', dest='cubeSize', default=0, type=int,
  67. help='cube size in pixels, or 0 to retain all details')
  68. parser.add_argument('-b', '--backgroundcolor', dest='backgroundColor', default="[0.0, 0.0, 0.0]", type=str,
  69. help='RGB triple of values [0, 1] defining background color shown past the edges of a partial panorama (defaults to "[0.0, 0.0, 0.0]")')
  70. parser.add_argument('-B', '--avoidbackground', action='store_true',
  71. help='viewer should limit view to avoid showing background, so using --backgroundcolor is not needed')
  72. parser.add_argument('-a', '--autoload', action='store_true',
  73. help='automatically load panorama in viewer')
  74. parser.add_argument('-q', '--quality', dest='quality', default=75, type=int,
  75. help='output JPEG quality 0-100')
  76. parser.add_argument('--png', action='store_true',
  77. help='output PNG tiles instead of JPEG tiles')
  78. parser.add_argument('-n', '--nona', default=nona, required=nona is None,
  79. metavar='EXECUTABLE',
  80. help='location of the nona executable to use')
  81. parser.add_argument('-G', '--gpu', action='store_true',
  82. help='perform image remapping by nona on the GPU')
  83. parser.add_argument('-d', '--debug', action='store_true',
  84. help='debug mode (print status info and keep intermediate files)')
  85. args = parser.parse_args()
  86. # Create output directory
  87. if os.path.exists(args.output):
  88. print('Output directory "' + args.output + '" already exists')
  89. if not args.debug:
  90. sys.exit(1)
  91. else:
  92. os.makedirs(args.output)
  93. # Process input image information
  94. print('Processing input image information...')
  95. origWidth, origHeight = Image.open(args.inputFile).size
  96. haov = args.haov
  97. if haov == -1:
  98. if args.cylindrical or float(origWidth) / origHeight == 2:
  99. print('Assuming --haov 360.0')
  100. haov = 360.0
  101. else:
  102. print('Unless given the --haov option, equirectangular input image must be a full (not partial) panorama!')
  103. sys.exit(1)
  104. vaov = args.vaov
  105. if vaov == -1:
  106. if args.cylindrical or float(origWidth) / origHeight == 2:
  107. print('Assuming --vaov 180.0')
  108. vaov = 180.0
  109. else:
  110. print('Unless given the --vaov option, equirectangular input image must be a full (not partial) panorama!')
  111. sys.exit(1)
  112. if args.cubeSize != 0:
  113. cubeSize = args.cubeSize
  114. else:
  115. cubeSize = 8 * int((360 / haov) * origWidth / math.pi / 8)
  116. tileSize = min(args.tileSize, cubeSize)
  117. levels = int(math.ceil(math.log(float(cubeSize) / tileSize, 2))) + 1
  118. origHeight = str(origHeight)
  119. origWidth = str(origWidth)
  120. origFilename = os.path.join(os.getcwd(), args.inputFile)
  121. extension = '.jpg'
  122. if args.png:
  123. extension = '.png'
  124. partialPano = True if args.haov != -1 and args.vaov != -1 else False
  125. colorList = ast.literal_eval(args.backgroundColor)
  126. colorTuple = (int(colorList[0]*255), int(colorList[1]*255), int(colorList[2]*255))
  127. if args.debug:
  128. print('maxLevel: '+ str(levels))
  129. print('tileResolution: '+ str(tileSize))
  130. print('cubeResolution: '+ str(cubeSize))
  131. # Generate PTO file for nona to generate cube faces
  132. # Face order: front, back, up, down, left, right
  133. faceLetters = ['f', 'b', 'u', 'd', 'l', 'r']
  134. projection = "f1" if args.cylindrical else "f4"
  135. pitch = 0
  136. text = []
  137. facestr = 'i a0 b0 c0 d0 e'+ str(args.horizon) +' '+ projection + ' h' + origHeight +' w'+ origWidth +' n"'+ origFilename +'" r0 v' + str(haov)
  138. text.append('p E0 R0 f0 h' + str(cubeSize) + ' w' + str(cubeSize) + ' n"TIFF_m" u0 v90')
  139. text.append('m g1 i0 m2 p0.00784314')
  140. text.append(facestr +' p' + str(pitch+ 0) +' y0' )
  141. text.append(facestr +' p' + str(pitch+ 0) +' y180')
  142. text.append(facestr +' p' + str(pitch-90) +' y0' )
  143. text.append(facestr +' p' + str(pitch+90) +' y0' )
  144. text.append(facestr +' p' + str(pitch+ 0) +' y90' )
  145. text.append(facestr +' p' + str(pitch+ 0) +' y-90')
  146. text.append('v')
  147. text.append('*')
  148. text = '\n'.join(text)
  149. with open(os.path.join(args.output, 'cubic.pto'), 'w') as f:
  150. f.write(text)
  151. # Create cube faces
  152. print('Generating cube faces...')
  153. subprocess.check_call([args.nona, ('-g' if args.gpu else '-d') , '-o', os.path.join(args.output, 'face'), os.path.join(args.output, 'cubic.pto')])
  154. faces = ['face0000.tif', 'face0001.tif', 'face0002.tif', 'face0003.tif', 'face0004.tif', 'face0005.tif']
  155. # Generate tiles
  156. print('Generating tiles...')
  157. for f in range(0, 6):
  158. size = cubeSize
  159. faceExists = os.path.exists(os.path.join(args.output, faces[f]))
  160. if faceExists:
  161. face = Image.open(os.path.join(args.output, faces[f]))
  162. for level in range(levels, 0, -1):
  163. if not os.path.exists(os.path.join(args.output, str(level))):
  164. os.makedirs(os.path.join(args.output, str(level)))
  165. tiles = int(math.ceil(float(size) / tileSize))
  166. if (level < levels):
  167. face = face.resize([size, size], Image.ANTIALIAS)
  168. for i in range(0, tiles):
  169. for j in range(0, tiles):
  170. left = j * tileSize
  171. upper = i * tileSize
  172. right = min(j * args.tileSize + args.tileSize, size) # min(...) not really needed
  173. lower = min(i * args.tileSize + args.tileSize, size) # min(...) not really needed
  174. tile = face.crop([left, upper, right, lower])
  175. if args.debug:
  176. print('level: '+ str(level) + ' tiles: '+ str(tiles) + ' tileSize: ' + str(tileSize) + ' size: '+ str(size))
  177. print('left: '+ str(left) + ' upper: '+ str(upper) + ' right: '+ str(right) + ' lower: '+ str(lower))
  178. colors = tile.getcolors(1)
  179. if not partialPano or colors == None or colors[0][1] != colorTuple:
  180. # More than just one color (the background), i.e., non-empty tile
  181. if tile.mode in ('RGBA', 'LA'):
  182. background = Image.new(tile.mode[:-1], tile.size, colorTuple)
  183. background.paste(tile, tile.split()[-1])
  184. tile = background
  185. tile.save(os.path.join(args.output, str(level), faceLetters[f] + str(i) + '_' + str(j) + extension), quality=args.quality)
  186. size = int(size / 2)
  187. # Generate fallback tiles
  188. print('Generating fallback tiles...')
  189. for f in range(0, 6):
  190. if not os.path.exists(os.path.join(args.output, 'fallback')):
  191. os.makedirs(os.path.join(args.output, 'fallback'))
  192. if os.path.exists(os.path.join(args.output, faces[f])):
  193. face = Image.open(os.path.join(args.output, faces[f]))
  194. if face.mode in ('RGBA', 'LA'):
  195. background = Image.new(face.mode[:-1], face.size, colorTuple)
  196. background.paste(face, face.split()[-1])
  197. face = background
  198. face = face.resize([args.fallbackSize, args.fallbackSize], Image.ANTIALIAS)
  199. face.save(os.path.join(args.output, 'fallback', faceLetters[f] + extension), quality = args.quality)
  200. # Clean up temporary files
  201. if not args.debug:
  202. os.remove(os.path.join(args.output, 'cubic.pto'))
  203. for face in faces:
  204. if os.path.exists(os.path.join(args.output, face)):
  205. os.remove(os.path.join(args.output, face))
  206. # Generate config file
  207. text = []
  208. text.append('{')
  209. text.append(' "hfov": ' + str(args.hfov)+ ',')
  210. if haov < 360:
  211. text.append(' "haov": ' + str(haov)+ ',')
  212. text.append(' "minYaw": ' + str(-haov/2+0)+ ',')
  213. text.append(' "yaw": ' + str(-haov/2+args.hfov/2)+ ',')
  214. text.append(' "maxYaw": ' + str(+haov/2+0)+ ',')
  215. if vaov < 180:
  216. text.append(' "vaov": ' + str(vaov)+ ',')
  217. text.append(' "vOffset": ' + str(args.vOffset)+ ',')
  218. text.append(' "minPitch": ' + str(-vaov/2+args.vOffset)+ ',')
  219. text.append(' "pitch": ' + str( args.vOffset)+ ',')
  220. text.append(' "maxPitch": ' + str(+vaov/2+args.vOffset)+ ',')
  221. if colorTuple != (0, 0, 0):
  222. text.append(' "backgroundColor": "' + args.backgroundColor+ '",')
  223. if args.avoidbackground:
  224. text.append(' "avoidShowingBackground": true,')
  225. if args.autoload:
  226. text.append(' "autoLoad": true,')
  227. text.append(' "type": "multires",')
  228. text.append(' "multiRes": {')
  229. text.append(' "path": "/%l/%s%y_%x",')
  230. text.append(' "fallbackPath": "/fallback/%s",')
  231. text.append(' "extension": "' + extension[1:] + '",')
  232. text.append(' "tileResolution": ' + str(tileSize) + ',')
  233. text.append(' "maxLevel": ' + str(levels) + ',')
  234. text.append(' "cubeResolution": ' + str(cubeSize))
  235. text.append(' }')
  236. text.append('}')
  237. text = '\n'.join(text)
  238. with open(os.path.join(args.output, 'config.json'), 'w') as f:
  239. f.write(text)