You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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-2021 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. genPreview = False
  48. try:
  49. import pyshtools as pysh
  50. genPreview = True
  51. except:
  52. sys.stderr.write("Unable to import pyshtools. Not generating SHT preview.\n")
  53. def img2shtHash(img, lmax=5):
  54. '''
  55. Create spherical harmonic transform (SHT) hash preview.
  56. '''
  57. def encodeFloat(f, maxVal):
  58. return np.maximum(0, np.minimum(2 * maxVal, np.round(np.sign(f) * np.sqrt(np.abs(f)) * maxVal + maxVal))).astype(int)
  59. def encodeCoeff(r, g, b, maxVal):
  60. quantR = encodeFloat(r / maxVal, 9)
  61. quantG = encodeFloat(g / maxVal, 9)
  62. quantB = encodeFloat(b / maxVal, 9)
  63. return quantR * 19 ** 2 + quantG * 19 + quantB
  64. b83chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~"
  65. def b83encode(vals, length):
  66. result = ""
  67. for val in vals:
  68. for i in range(1, length + 1):
  69. result += b83chars[int(val // (83 ** (length - i))) % 83]
  70. return result
  71. # Calculate SHT coefficients
  72. r = pysh.expand.SHExpandDH(img[..., 0], sampling=2, lmax_calc=lmax)
  73. g = pysh.expand.SHExpandDH(img[..., 1], sampling=2, lmax_calc=lmax)
  74. b = pysh.expand.SHExpandDH(img[..., 2], sampling=2, lmax_calc=lmax)
  75. # Remove values above diagonal for both sine and cosine components
  76. # Also remove first row and column for sine component
  77. # These values are always zero
  78. r = np.append(r[0][np.tril_indices(lmax + 1)], r[1, 1:, 1:][np.tril_indices(lmax)])
  79. g = np.append(g[0][np.tril_indices(lmax + 1)], g[1, 1:, 1:][np.tril_indices(lmax)])
  80. b = np.append(b[0][np.tril_indices(lmax + 1)], b[1, 1:, 1:][np.tril_indices(lmax)])
  81. # Encode as string
  82. maxVal = np.max([np.max(r), np.max(b), np.max(g)])
  83. vals = encodeCoeff(r, g, b, maxVal).flatten()
  84. asstr = b83encode(vals, 2)
  85. lmaxStr = b83encode([lmax], 1)
  86. maxValStr = b83encode(encodeFloat([2 * maxVal / 255 - 1], 41), 1)
  87. return lmaxStr + maxValStr + asstr
  88. # Subclass parser to add explaination for semi-option nona flag
  89. class GenParser(argparse.ArgumentParser):
  90. def error(self, message):
  91. if '--nona' in message:
  92. sys.stderr.write('''IMPORTANT: The location of the nona utility (from Hugin) must be specified
  93. with -n, since it was not found on the PATH!\n\n''')
  94. super(GenParser, self).error(message)
  95. # Parse input
  96. parser = GenParser(description='Generate a Pannellum multires tile set from a full or partial equirectangular or cylindrical panorama.',
  97. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  98. parser.add_argument('inputFile', metavar='INPUT',
  99. help='panorama to be processed')
  100. parser.add_argument('-C', '--cylindrical', action='store_true',
  101. help='input projection is cylindrical (default is equirectangular)')
  102. parser.add_argument('-H', '--haov', dest='haov', default=-1, type=float,
  103. help='horizontal angle of view (defaults to 360.0 for full panorama)')
  104. parser.add_argument('-F', '--hfov', dest='hfov', default=100.0, type=float,
  105. help='starting horizontal field of view (defaults to 100.0)')
  106. parser.add_argument('-V', '--vaov', dest='vaov', default=-1, type=float,
  107. help='vertical angle of view (defaults to 180.0 for full panorama)')
  108. parser.add_argument('-O', '--voffset', dest='vOffset', default=0.0, type=float,
  109. help='starting pitch position (defaults to 0.0)')
  110. parser.add_argument('-e', '--horizon', dest='horizon', default=0.0, type=int,
  111. help='offset of the horizon in pixels (negative if above middle, defaults to 0)')
  112. parser.add_argument('-o', '--output', dest='output', default='./output',
  113. help='output directory, optionally to be used as basePath (defaults to "./output")')
  114. parser.add_argument('-s', '--tilesize', dest='tileSize', default=512, type=int,
  115. help='tile size in pixels')
  116. parser.add_argument('-f', '--fallbacksize', dest='fallbackSize', default=1024, type=int,
  117. help='fallback tile size in pixels (defaults to 1024)')
  118. parser.add_argument('-c', '--cubesize', dest='cubeSize', default=0, type=int,
  119. help='cube size in pixels, or 0 to retain all details')
  120. parser.add_argument('-b', '--backgroundcolor', dest='backgroundColor', default="[0.0, 0.0, 0.0]", type=str,
  121. 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]")')
  122. parser.add_argument('-B', '--avoidbackground', action='store_true',
  123. help='viewer should limit view to avoid showing background, so using --backgroundcolor is not needed')
  124. parser.add_argument('-a', '--autoload', action='store_true',
  125. help='automatically load panorama in viewer')
  126. parser.add_argument('-q', '--quality', dest='quality', default=75, type=int,
  127. help='output JPEG quality 0-100')
  128. parser.add_argument('--png', action='store_true',
  129. help='output PNG tiles instead of JPEG tiles')
  130. parser.add_argument('--thumbnailsize', dest='thumbnailSize', default=0, type=int,
  131. help='width of equirectangular thumbnail preview (defaults to no thumbnail; must be power of two; >512 not recommended)')
  132. parser.add_argument('-n', '--nona', default=nona, required=nona is None,
  133. metavar='EXECUTABLE',
  134. help='location of the nona executable to use')
  135. parser.add_argument('-G', '--gpu', action='store_true',
  136. help='perform image remapping by nona on the GPU')
  137. parser.add_argument('-d', '--debug', action='store_true',
  138. help='debug mode (print status info and keep intermediate files)')
  139. args = parser.parse_args()
  140. # Check argument
  141. if args.thumbnailSize > 0:
  142. if args.thumbnailSize & (args.thumbnailSize - 1) != 0:
  143. print('Thumbnail size, if specified, must be a power of two')
  144. sys.exit(1)
  145. # Create output directory
  146. if os.path.exists(args.output):
  147. print('Output directory "' + args.output + '" already exists')
  148. if not args.debug:
  149. sys.exit(1)
  150. else:
  151. os.makedirs(args.output)
  152. # Process input image information
  153. print('Processing input image information...')
  154. origWidth, origHeight = Image.open(args.inputFile).size
  155. haov = args.haov
  156. if haov == -1:
  157. if args.cylindrical or float(origWidth) / origHeight == 2:
  158. print('Assuming --haov 360.0')
  159. haov = 360.0
  160. else:
  161. print('Unless given the --haov option, equirectangular input image must be a full (not partial) panorama!')
  162. sys.exit(1)
  163. vaov = args.vaov
  164. if vaov == -1:
  165. if args.cylindrical or float(origWidth) / origHeight == 2:
  166. print('Assuming --vaov 180.0')
  167. vaov = 180.0
  168. else:
  169. print('Unless given the --vaov option, equirectangular input image must be a full (not partial) panorama!')
  170. sys.exit(1)
  171. if args.cubeSize != 0:
  172. cubeSize = args.cubeSize
  173. else:
  174. cubeSize = 8 * int((360 / haov) * origWidth / math.pi / 8)
  175. tileSize = min(args.tileSize, cubeSize)
  176. levels = int(math.ceil(math.log(float(cubeSize) / tileSize, 2))) + 1
  177. if round(cubeSize / 2**(levels - 2)) == tileSize:
  178. levels -= 1 # Handle edge case
  179. origHeight = str(origHeight)
  180. origWidth = str(origWidth)
  181. origFilename = os.path.join(os.getcwd(), args.inputFile)
  182. extension = '.jpg'
  183. if args.png:
  184. extension = '.png'
  185. partialPano = True if args.haov != -1 and args.vaov != -1 else False
  186. colorList = ast.literal_eval(args.backgroundColor)
  187. colorTuple = (int(colorList[0]*255), int(colorList[1]*255), int(colorList[2]*255))
  188. if args.debug:
  189. print('maxLevel: '+ str(levels))
  190. print('tileResolution: '+ str(tileSize))
  191. print('cubeResolution: '+ str(cubeSize))
  192. # Generate PTO file for nona to generate cube faces
  193. # Face order: front, back, up, down, left, right
  194. faceLetters = ['f', 'b', 'u', 'd', 'l', 'r']
  195. projection = "f1" if args.cylindrical else "f4"
  196. pitch = 0
  197. text = []
  198. facestr = 'i a0 b0 c0 d0 e'+ str(args.horizon) +' '+ projection + ' h' + origHeight +' w'+ origWidth +' n"'+ origFilename +'" r0 v' + str(haov)
  199. text.append('p E0 R0 f0 h' + str(cubeSize) + ' w' + str(cubeSize) + ' n"TIFF_m" u0 v90')
  200. text.append('m g1 i0 m2 p0.00784314')
  201. text.append(facestr +' p' + str(pitch+ 0) +' y0' )
  202. text.append(facestr +' p' + str(pitch+ 0) +' y180')
  203. text.append(facestr +' p' + str(pitch-90) +' y0' )
  204. text.append(facestr +' p' + str(pitch+90) +' y0' )
  205. text.append(facestr +' p' + str(pitch+ 0) +' y90' )
  206. text.append(facestr +' p' + str(pitch+ 0) +' y-90')
  207. text.append('v')
  208. text.append('*')
  209. text = '\n'.join(text)
  210. with open(os.path.join(args.output, 'cubic.pto'), 'w') as f:
  211. f.write(text)
  212. # Create cube faces
  213. print('Generating cube faces...')
  214. 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')])
  215. faces = ['face0000.tif', 'face0001.tif', 'face0002.tif', 'face0003.tif', 'face0004.tif', 'face0005.tif']
  216. # Generate tiles
  217. print('Generating tiles...')
  218. for f in range(0, 6):
  219. size = cubeSize
  220. faceExists = os.path.exists(os.path.join(args.output, faces[f]))
  221. if faceExists:
  222. face = Image.open(os.path.join(args.output, faces[f]))
  223. for level in range(levels, 0, -1):
  224. if not os.path.exists(os.path.join(args.output, str(level))):
  225. os.makedirs(os.path.join(args.output, str(level)))
  226. tiles = int(math.ceil(float(size) / tileSize))
  227. if (level < levels):
  228. face = face.resize([size, size], Image.ANTIALIAS)
  229. for i in range(0, tiles):
  230. for j in range(0, tiles):
  231. left = j * tileSize
  232. upper = i * tileSize
  233. right = min(j * args.tileSize + args.tileSize, size) # min(...) not really needed
  234. lower = min(i * args.tileSize + args.tileSize, size) # min(...) not really needed
  235. tile = face.crop([left, upper, right, lower])
  236. if args.debug:
  237. print('level: '+ str(level) + ' tiles: '+ str(tiles) + ' tileSize: ' + str(tileSize) + ' size: '+ str(size))
  238. print('left: '+ str(left) + ' upper: '+ str(upper) + ' right: '+ str(right) + ' lower: '+ str(lower))
  239. colors = tile.getcolors(1)
  240. if not partialPano or colors == None or colors[0][1] != colorTuple:
  241. # More than just one color (the background), i.e., non-empty tile
  242. if tile.mode in ('RGBA', 'LA'):
  243. background = Image.new(tile.mode[:-1], tile.size, colorTuple)
  244. background.paste(tile, tile.split()[-1])
  245. tile = background
  246. tile.save(os.path.join(args.output, str(level), faceLetters[f] + str(i) + '_' + str(j) + extension), quality=args.quality)
  247. size = int(size / 2)
  248. # Generate fallback tiles
  249. print('Generating fallback tiles...')
  250. for f in range(0, 6):
  251. if not os.path.exists(os.path.join(args.output, 'fallback')):
  252. os.makedirs(os.path.join(args.output, 'fallback'))
  253. if os.path.exists(os.path.join(args.output, faces[f])):
  254. face = Image.open(os.path.join(args.output, faces[f]))
  255. if face.mode in ('RGBA', 'LA'):
  256. background = Image.new(face.mode[:-1], face.size, colorTuple)
  257. background.paste(face, face.split()[-1])
  258. face = background
  259. face = face.resize([args.fallbackSize, args.fallbackSize], Image.ANTIALIAS)
  260. face.save(os.path.join(args.output, 'fallback', faceLetters[f] + extension), quality = args.quality)
  261. # Clean up temporary files
  262. if not args.debug:
  263. os.remove(os.path.join(args.output, 'cubic.pto'))
  264. for face in faces:
  265. if os.path.exists(os.path.join(args.output, face)):
  266. os.remove(os.path.join(args.output, face))
  267. # Generate preview (but not for partial panoramas)
  268. if haov < 360 or vaov < 180:
  269. genPreview = False
  270. if genPreview:
  271. # Generate SHT-hash preview
  272. shtHash = img2shtHash(np.array(Image.open(args.inputFile).resize((1024, 512))))
  273. if args.thumbnailSize > 0:
  274. # Create low-resolution base64-encoded equirectangular preview image
  275. img = Image.open(args.inputFile)
  276. img = img.resize((args.thumbnailSize, args.thumbnailSize // 2))
  277. buf = io.BytesIO()
  278. img.save(buf, format='JPEG', quality=75, optimize=True)
  279. equiPreview = bytes('data:image/jpeg;base64,', encoding='utf-8')
  280. equiPreview += base64.b64encode(buf.getvalue())
  281. equiPreview = equiPreview.decode()
  282. # Generate config file
  283. text = []
  284. text.append('{')
  285. text.append(' "hfov": ' + str(args.hfov)+ ',')
  286. if haov < 360:
  287. text.append(' "haov": ' + str(haov)+ ',')
  288. text.append(' "minYaw": ' + str(-haov/2+0)+ ',')
  289. text.append(' "yaw": ' + str(-haov/2+args.hfov/2)+ ',')
  290. text.append(' "maxYaw": ' + str(+haov/2+0)+ ',')
  291. if vaov < 180:
  292. text.append(' "vaov": ' + str(vaov)+ ',')
  293. text.append(' "vOffset": ' + str(args.vOffset)+ ',')
  294. text.append(' "minPitch": ' + str(-vaov/2+args.vOffset)+ ',')
  295. text.append(' "pitch": ' + str( args.vOffset)+ ',')
  296. text.append(' "maxPitch": ' + str(+vaov/2+args.vOffset)+ ',')
  297. if colorTuple != (0, 0, 0):
  298. text.append(' "backgroundColor": "' + args.backgroundColor+ '",')
  299. if args.avoidbackground and (haov < 360 or vaov < 180):
  300. text.append(' "avoidShowingBackground": true,')
  301. if args.autoload:
  302. text.append(' "autoLoad": true,')
  303. text.append(' "type": "multires",')
  304. text.append(' "multiRes": {')
  305. if genPreview:
  306. text.append(' "shtHash": "' + shtHash + '",')
  307. if args.thumbnailSize > 0:
  308. text.append(' "equirectangularThumbnail": "' + equiPreview + '",')
  309. text.append(' "path": "/%l/%s%y_%x",')
  310. text.append(' "fallbackPath": "/fallback/%s",')
  311. text.append(' "extension": "' + extension[1:] + '",')
  312. text.append(' "tileResolution": ' + str(tileSize) + ',')
  313. text.append(' "maxLevel": ' + str(levels) + ',')
  314. text.append(' "cubeResolution": ' + str(cubeSize))
  315. text.append(' }')
  316. text.append('}')
  317. text = '\n'.join(text)
  318. with open(os.path.join(args.output, 'config.json'), 'w') as f:
  319. f.write(text)