No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

354 líneas
16 KiB

  1. #!/usr/bin/env python3
  2. # Requires Python 3.2+, the Python Pillow and NumPy packages, and
  3. # nona (from Hugin). The Python pyshtools package is also needed for creating
  4. # spherical-harmonic-transform previews (which are recommended).
  5. # generate.py - A multires tile set generator for Pannellum
  6. # Extensions to cylindrical input and partial panoramas by David von Oheimb
  7. # Copyright (c) 2014-2022 Matthew Petroff
  8. #
  9. # Permission is hereby granted, free of charge, to any person obtaining a copy
  10. # of this software and associated documentation files (the "Software"), to deal
  11. # in the Software without restriction, including without limitation the rights
  12. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. # copies of the Software, and to permit persons to whom the Software is
  14. # furnished to do so, subject to the following conditions:
  15. #
  16. # The above copyright notice and this permission notice shall be included in
  17. # all copies or substantial portions of the Software.
  18. #
  19. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. # THE SOFTWARE.
  26. from __future__ import print_function
  27. import argparse
  28. from PIL import Image
  29. import os
  30. import sys
  31. import math
  32. import ast
  33. from distutils.spawn import find_executable
  34. import subprocess
  35. import base64
  36. import io
  37. import numpy as np
  38. # Allow large images (this could lead to a denial of service attack if you're
  39. # running this script on user-submitted images.)
  40. Image.MAX_IMAGE_PIXELS = None
  41. # Find external programs
  42. try:
  43. nona = find_executable('nona')
  44. except KeyError:
  45. # Handle case of PATH not being set
  46. nona = None
  47. # Handle Pillow deprecation
  48. ANTIALIAS = Image.Resampling.LANCZOS if hasattr(Image, "Resampling") else Image.ANTIALIAS
  49. genPreview = False
  50. try:
  51. import pyshtools as pysh
  52. genPreview = True
  53. except:
  54. sys.stderr.write("Unable to import pyshtools. Not generating SHT preview.\n")
  55. def img2shtHash(img, lmax=5):
  56. '''
  57. Create spherical harmonic transform (SHT) hash preview.
  58. '''
  59. def encodeFloat(f, maxVal):
  60. return np.maximum(0, np.minimum(2 * maxVal, np.round(np.sign(f) * np.sqrt(np.abs(f)) * maxVal + maxVal))).astype(int)
  61. def encodeCoeff(r, g, b, maxVal):
  62. quantR = encodeFloat(r / maxVal, 9)
  63. quantG = encodeFloat(g / maxVal, 9)
  64. quantB = encodeFloat(b / maxVal, 9)
  65. return quantR * 19 ** 2 + quantG * 19 + quantB
  66. b83chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~"
  67. def b83encode(vals, length):
  68. result = ""
  69. for val in vals:
  70. for i in range(1, length + 1):
  71. result += b83chars[int(val // (83 ** (length - i))) % 83]
  72. return result
  73. # Calculate SHT coefficients
  74. r = pysh.expand.SHExpandDH(img[..., 0], sampling=2, lmax_calc=lmax)
  75. g = pysh.expand.SHExpandDH(img[..., 1], sampling=2, lmax_calc=lmax)
  76. b = pysh.expand.SHExpandDH(img[..., 2], sampling=2, lmax_calc=lmax)
  77. # Remove values above diagonal for both sine and cosine components
  78. # Also remove first row and column for sine component
  79. # These values are always zero
  80. r = np.append(r[0][np.tril_indices(lmax + 1)], r[1, 1:, 1:][np.tril_indices(lmax)])
  81. g = np.append(g[0][np.tril_indices(lmax + 1)], g[1, 1:, 1:][np.tril_indices(lmax)])
  82. b = np.append(b[0][np.tril_indices(lmax + 1)], b[1, 1:, 1:][np.tril_indices(lmax)])
  83. # Encode as string
  84. maxVal = np.max([np.max(r), np.max(b), np.max(g)])
  85. vals = encodeCoeff(r, g, b, maxVal).flatten()
  86. asstr = b83encode(vals, 2)
  87. lmaxStr = b83encode([lmax], 1)
  88. maxValStr = b83encode(encodeFloat([2 * maxVal / 255 - 1], 41), 1)
  89. return lmaxStr + maxValStr + asstr
  90. # Subclass parser to add explaination for semi-option nona flag
  91. class GenParser(argparse.ArgumentParser):
  92. def error(self, message):
  93. if '--nona' in message:
  94. sys.stderr.write('''IMPORTANT: The location of the nona utility (from Hugin) must be specified
  95. with -n, since it was not found on the PATH!\n\n''')
  96. super(GenParser, self).error(message)
  97. # Parse input
  98. parser = GenParser(description='Generate a Pannellum multires tile set from a full or partial equirectangular or cylindrical panorama.',
  99. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  100. parser.add_argument('inputFile', metavar='INPUT',
  101. help='panorama to be processed')
  102. parser.add_argument('-C', '--cylindrical', action='store_true',
  103. help='input projection is cylindrical (default is equirectangular)')
  104. parser.add_argument('-H', '--haov', dest='haov', default=-1, type=float,
  105. help='horizontal angle of view (defaults to 360.0 for full panorama)')
  106. parser.add_argument('-F', '--hfov', dest='hfov', default=100.0, type=float,
  107. help='starting horizontal field of view (defaults to 100.0)')
  108. parser.add_argument('-V', '--vaov', dest='vaov', default=-1, type=float,
  109. help='vertical angle of view (defaults to 180.0 for full panorama)')
  110. parser.add_argument('-O', '--voffset', dest='vOffset', default=0.0, type=float,
  111. help='starting pitch position (defaults to 0.0)')
  112. parser.add_argument('-e', '--horizon', dest='horizon', default=0.0, type=int,
  113. help='offset of the horizon in pixels (negative if above middle, defaults to 0)')
  114. parser.add_argument('-o', '--output', dest='output', default='./output',
  115. help='output directory, optionally to be used as basePath (defaults to "./output")')
  116. parser.add_argument('-s', '--tilesize', dest='tileSize', default=512, type=int,
  117. help='tile size in pixels')
  118. parser.add_argument('-f', '--fallbacksize', dest='fallbackSize', default=1024, type=int,
  119. help='fallback tile size in pixels (defaults to 1024, set to 0 to skip)')
  120. parser.add_argument('-c', '--cubesize', dest='cubeSize', default=0, type=int,
  121. help='cube size in pixels, or 0 to retain all details')
  122. parser.add_argument('-b', '--backgroundcolor', dest='backgroundColor', default="[0.0, 0.0, 0.0]", type=str,
  123. 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]")')
  124. parser.add_argument('-B', '--avoidbackground', action='store_true',
  125. help='viewer should limit view to avoid showing background, so using --backgroundcolor is not needed')
  126. parser.add_argument('-a', '--autoload', action='store_true',
  127. help='automatically load panorama in viewer')
  128. parser.add_argument('-q', '--quality', dest='quality', default=75, type=int,
  129. help='output JPEG quality 0-100')
  130. parser.add_argument('--png', action='store_true',
  131. help='output PNG tiles instead of JPEG tiles')
  132. parser.add_argument('--thumbnailsize', dest='thumbnailSize', default=0, type=int,
  133. help='width of equirectangular thumbnail preview (defaults to no thumbnail; must be power of two; >512 not recommended)')
  134. parser.add_argument('-n', '--nona', default=nona, required=nona is None,
  135. metavar='EXECUTABLE',
  136. help='location of the nona executable to use')
  137. parser.add_argument('-G', '--gpu', action='store_true',
  138. help='perform image remapping by nona on the GPU')
  139. parser.add_argument('-d', '--debug', action='store_true',
  140. help='debug mode (print status info and keep intermediate files)')
  141. args = parser.parse_args()
  142. # Check argument
  143. if args.thumbnailSize > 0:
  144. if args.thumbnailSize & (args.thumbnailSize - 1) != 0:
  145. print('Thumbnail size, if specified, must be a power of two')
  146. sys.exit(1)
  147. # Create output directory
  148. if os.path.exists(args.output):
  149. print('Output directory "' + args.output + '" already exists')
  150. if not args.debug:
  151. sys.exit(1)
  152. else:
  153. os.makedirs(args.output)
  154. # Process input image information
  155. print('Processing input image information...')
  156. origWidth, origHeight = Image.open(args.inputFile).size
  157. haov = args.haov
  158. if haov == -1:
  159. if args.cylindrical or float(origWidth) / origHeight == 2:
  160. print('Assuming --haov 360.0')
  161. haov = 360.0
  162. else:
  163. print('Unless given the --haov option, equirectangular input image must be a full (not partial) panorama!')
  164. sys.exit(1)
  165. vaov = args.vaov
  166. if vaov == -1:
  167. if args.cylindrical or float(origWidth) / origHeight == 2:
  168. print('Assuming --vaov 180.0')
  169. vaov = 180.0
  170. else:
  171. print('Unless given the --vaov option, equirectangular input image must be a full (not partial) panorama!')
  172. sys.exit(1)
  173. if args.cubeSize != 0:
  174. cubeSize = args.cubeSize
  175. else:
  176. cubeSize = 8 * int((360 / haov) * origWidth / math.pi / 8)
  177. tileSize = min(args.tileSize, cubeSize)
  178. levels = int(math.ceil(math.log(float(cubeSize) / tileSize, 2))) + 1
  179. if round(cubeSize / 2**(levels - 2)) == tileSize:
  180. levels -= 1 # Handle edge case
  181. origHeight = str(origHeight)
  182. origWidth = str(origWidth)
  183. origFilename = os.path.join(os.getcwd(), args.inputFile)
  184. extension = '.jpg'
  185. if args.png:
  186. extension = '.png'
  187. partialPano = True if args.haov != -1 and args.vaov != -1 else False
  188. colorList = ast.literal_eval(args.backgroundColor)
  189. colorTuple = (int(colorList[0]*255), int(colorList[1]*255), int(colorList[2]*255))
  190. if args.debug:
  191. print('maxLevel: '+ str(levels))
  192. print('tileResolution: '+ str(tileSize))
  193. print('cubeResolution: '+ str(cubeSize))
  194. # Generate PTO file for nona to generate cube faces
  195. # Face order: front, back, up, down, left, right
  196. faceLetters = ['f', 'b', 'u', 'd', 'l', 'r']
  197. projection = "f1" if args.cylindrical else "f4"
  198. pitch = 0
  199. text = []
  200. facestr = 'i a0 b0 c0 d0 e'+ str(args.horizon) +' '+ projection + ' h' + origHeight +' w'+ origWidth +' n"'+ origFilename +'" r0 v' + str(haov)
  201. text.append('p E0 R0 f0 h' + str(cubeSize) + ' w' + str(cubeSize) + ' n"TIFF_m" u0 v90')
  202. text.append('m g1 i0 m2 p0.00784314')
  203. text.append(facestr +' p' + str(pitch+ 0) +' y0' )
  204. text.append(facestr +' p' + str(pitch+ 0) +' y180')
  205. text.append(facestr +' p' + str(pitch-90) +' y0' )
  206. text.append(facestr +' p' + str(pitch+90) +' y0' )
  207. text.append(facestr +' p' + str(pitch+ 0) +' y90' )
  208. text.append(facestr +' p' + str(pitch+ 0) +' y-90')
  209. text.append('v')
  210. text.append('*')
  211. text = '\n'.join(text)
  212. with open(os.path.join(args.output, 'cubic.pto'), 'w') as f:
  213. f.write(text)
  214. # Create cube faces
  215. print('Generating cube faces...')
  216. 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')])
  217. faces = ['face0000.tif', 'face0001.tif', 'face0002.tif', 'face0003.tif', 'face0004.tif', 'face0005.tif']
  218. # Generate tiles
  219. print('Generating tiles...')
  220. for f in range(0, 6):
  221. size = cubeSize
  222. faceExists = os.path.exists(os.path.join(args.output, faces[f]))
  223. if faceExists:
  224. face = Image.open(os.path.join(args.output, faces[f]))
  225. for level in range(levels, 0, -1):
  226. if not os.path.exists(os.path.join(args.output, str(level))):
  227. os.makedirs(os.path.join(args.output, str(level)))
  228. tiles = int(math.ceil(float(size) / tileSize))
  229. if (level < levels):
  230. face = face.resize([size, size], ANTIALIAS)
  231. for i in range(0, tiles):
  232. for j in range(0, tiles):
  233. left = j * tileSize
  234. upper = i * tileSize
  235. right = min(j * args.tileSize + args.tileSize, size) # min(...) not really needed
  236. lower = min(i * args.tileSize + args.tileSize, size) # min(...) not really needed
  237. tile = face.crop([left, upper, right, lower])
  238. if args.debug:
  239. print('level: '+ str(level) + ' tiles: '+ str(tiles) + ' tileSize: ' + str(tileSize) + ' size: '+ str(size))
  240. print('left: '+ str(left) + ' upper: '+ str(upper) + ' right: '+ str(right) + ' lower: '+ str(lower))
  241. colors = tile.getcolors(1)
  242. if not partialPano or colors == None or colors[0][1] != colorTuple:
  243. # More than just one color (the background), i.e., non-empty tile
  244. if tile.mode in ('RGBA', 'LA'):
  245. background = Image.new(tile.mode[:-1], tile.size, colorTuple)
  246. background.paste(tile, tile.split()[-1])
  247. tile = background
  248. tile.save(os.path.join(args.output, str(level), faceLetters[f] + str(i) + '_' + str(j) + extension), quality=args.quality)
  249. size = int(size / 2)
  250. # Generate fallback tiles
  251. if args.fallbackSize > 0:
  252. print('Generating fallback tiles...')
  253. for f in range(0, 6):
  254. if not os.path.exists(os.path.join(args.output, 'fallback')):
  255. os.makedirs(os.path.join(args.output, 'fallback'))
  256. if os.path.exists(os.path.join(args.output, faces[f])):
  257. face = Image.open(os.path.join(args.output, faces[f]))
  258. if face.mode in ('RGBA', 'LA'):
  259. background = Image.new(face.mode[:-1], face.size, colorTuple)
  260. background.paste(face, face.split()[-1])
  261. face = background
  262. face = face.resize([args.fallbackSize, args.fallbackSize], ANTIALIAS)
  263. face.save(os.path.join(args.output, 'fallback', faceLetters[f] + extension), quality = args.quality)
  264. # Clean up temporary files
  265. if not args.debug:
  266. os.remove(os.path.join(args.output, 'cubic.pto'))
  267. for face in faces:
  268. if os.path.exists(os.path.join(args.output, face)):
  269. os.remove(os.path.join(args.output, face))
  270. # Generate preview (but not for partial panoramas)
  271. if haov < 360 or vaov < 180:
  272. genPreview = False
  273. if genPreview:
  274. # Generate SHT-hash preview
  275. shtHash = img2shtHash(np.array(Image.open(args.inputFile).resize((1024, 512))))
  276. if args.thumbnailSize > 0:
  277. # Create low-resolution base64-encoded equirectangular preview image
  278. img = Image.open(args.inputFile)
  279. img = img.resize((args.thumbnailSize, args.thumbnailSize // 2))
  280. buf = io.BytesIO()
  281. img.save(buf, format='JPEG', quality=75, optimize=True)
  282. equiPreview = bytes('data:image/jpeg;base64,', encoding='utf-8')
  283. equiPreview += base64.b64encode(buf.getvalue())
  284. equiPreview = equiPreview.decode()
  285. # Generate config file
  286. text = []
  287. text.append('{')
  288. text.append(' "hfov": ' + str(args.hfov)+ ',')
  289. if haov < 360:
  290. text.append(' "haov": ' + str(haov)+ ',')
  291. text.append(' "minYaw": ' + str(-haov/2+0)+ ',')
  292. text.append(' "yaw": ' + str(-haov/2+args.hfov/2)+ ',')
  293. text.append(' "maxYaw": ' + str(+haov/2+0)+ ',')
  294. if vaov < 180:
  295. text.append(' "vaov": ' + str(vaov)+ ',')
  296. text.append(' "vOffset": ' + str(args.vOffset)+ ',')
  297. text.append(' "minPitch": ' + str(-vaov/2+args.vOffset)+ ',')
  298. text.append(' "pitch": ' + str( args.vOffset)+ ',')
  299. text.append(' "maxPitch": ' + str(+vaov/2+args.vOffset)+ ',')
  300. if colorTuple != (0, 0, 0):
  301. text.append(' "backgroundColor": "' + args.backgroundColor+ '",')
  302. if args.avoidbackground and (haov < 360 or vaov < 180):
  303. text.append(' "avoidShowingBackground": true,')
  304. if args.autoload:
  305. text.append(' "autoLoad": true,')
  306. text.append(' "type": "multires",')
  307. text.append(' "multiRes": {')
  308. if genPreview:
  309. text.append(' "shtHash": "' + shtHash + '",')
  310. if args.thumbnailSize > 0:
  311. text.append(' "equirectangularThumbnail": "' + equiPreview + '",')
  312. text.append(' "path": "/%l/%s%y_%x",')
  313. if args.fallbackSize > 0:
  314. text.append(' "fallbackPath": "/fallback/%s",')
  315. text.append(' "extension": "' + extension[1:] + '",')
  316. text.append(' "tileResolution": ' + str(tileSize) + ',')
  317. text.append(' "maxLevel": ' + str(levels) + ',')
  318. text.append(' "cubeResolution": ' + str(cubeSize))
  319. text.append(' }')
  320. text.append('}')
  321. text = '\n'.join(text)
  322. with open(os.path.join(args.output, 'config.json'), 'w') as f:
  323. f.write(text)