Advertisement
deKaf

[Python] PSD processing for Substance Designer

Oct 22nd, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.10 KB | None | 0 0
  1. #parsing PSDs for use in Substance Designer network
  2. #finds masks, albedos, normals and exports out
  3.  
  4. #importing PSD Tools
  5. from psd_tools  import PSDImage
  6. #importing PSD imageops module fomr Pillow
  7. from PIL import Image
  8. import PIL.ImageOps
  9.  
  10. #for logging
  11. import time
  12. import logging,sys
  13. logging.basicConfig(stream = sys.stderr, level = logging.WARNING)
  14.  
  15.  
  16. #for file directory navigation
  17. from os import path
  18. from os import listdir
  19. from os import mkdir
  20.  
  21. #math
  22. import math
  23.  
  24.  
  25. class locations():
  26.     """Storing locations in this class"""
  27.    
  28.     def __init__(self,*args):
  29.         self.sourceImages = " "
  30.         self.exportImages= " "
  31.  
  32.     def sourceDirectory(self):
  33.         """Setting location for where PSDs are located"""
  34.  
  35.         sourceImages = ("c:\\Telltale\\ArtData\\Textures\\WalkingDead3\\PSDs\\")
  36.         #sourceImages = ("c:\\test\\PSDs\\")
  37.         allFiles = [f for f in listdir(sourceImages) if path.isfile(path.join(sourceImages,f))]
  38.  
  39.         return (sourceImages,allFiles)
  40.    
  41.     def exportDirectory(self):
  42.         """Setting location for where TGAs are located"""
  43.  
  44.         exportImages = ("c:\\Telltale\\ArtData\\Textures\\WalkingDead3\\")
  45.         #exportImages = ("c:\\test\\PSDs\\export\\")
  46.         if not path.exists(exportImages):
  47.             logging.info ("Can't find this path! Creating...")
  48.             mkdir (exportImages)
  49.         else:
  50.             logging.info ("Export path found...")
  51.  
  52.         return (exportImages)
  53.  
  54. class psdExport():
  55.  
  56.     def psdFiles(self):
  57.         """Return list of only PSDs defined in locations.sourceDirectory"""
  58.  
  59.         psdfiles =[]
  60.  
  61.         psdList = locations()
  62.         for fileExtensions in psdList.sourceDirectory():
  63.             for files in fileExtensions:
  64.                 if files.endswith(".psd"):
  65.                     psdfiles.append(files)
  66.  
  67.         return (psdfiles)
  68.  
  69.     def psdProcess(self,logFileName):
  70.         """Save out PSDs into seperate TGAs for SBS Designer to process"""
  71.  
  72.         listPSD=psdExport()
  73.         directory = locations()
  74.         log = open(logFileName, "a")
  75.  
  76.         PSDdir = directory.sourceDirectory()[0]
  77.         TGAdir = directory.exportDirectory()
  78.  
  79.         PSDs = listPSD.psdFiles()
  80.        
  81.        
  82.         fullPSDpath = [] ## I need to do this for PSD_tools
  83.         for p in PSDs:
  84.             p =  PSDdir + p
  85.             fullPSDpath.append(p)
  86.        
  87.  
  88.        
  89.         for item in fullPSDpath[:]:
  90.             print ("Processing {0}").format(item)
  91.             log.write(item + "\n")
  92.             psd = PSDImage.load(item)
  93.             exportName = path.basename(item)
  94.            
  95.             psdTime = time.clock()
  96.  
  97.             for group in psd.layers[:]:
  98.  
  99.                 # if group.name == "DIF":
  100.                 #   diffuse = group
  101.                 #   logging.info ("Found Diffuse.. exporting")
  102.                    
  103.                 #   try:
  104.  
  105.                 #       if diffuse.as_PIL().mode == "RGBA":
  106.                 #           log.write("Alpha layer in the PSD:" + (exportName))
  107.  
  108.                 #       diffuse.as_PIL().thumbnail(size,Image.BICUBIC)
  109.                 #       diffuse.as_PIL().save(TGAdir + exportName[:-4] + '.tga')
  110.                    
  111.                 #       diffuseSuccess = ("Successfully saved out diffuse!")
  112.                 #       logging.info (diffuseSuccess)
  113.                 #       log.write(diffuseSuccess + "\n")
  114.  
  115.                 #   except IOError as e:
  116.                 #       diffuseError = ("Couldn't save out diffuse, is it checked out in source control?")
  117.                 #       logging.info (diffuseError)
  118.                 #       log.write(diffuseError + "\n")
  119.                 #       pass
  120.                    
  121.                 # if group.name == "NRM":
  122.                 #   normal = group
  123.                 #   logging.info ("Found Normal Map.. exporting")
  124.                 #   size = (1024,1024)
  125.                 #   try:
  126.                 #       normal.as_PIL().thumbnail(size,Image.BICUBIC)
  127.                 #       normal.as_PIL().save(TGAdir + exportName[:-4] + '_nm.tga')
  128.                        
  129.                 #       normalSuccess = ("Successfully saved out normal map!")
  130.                 #       logging.info (normalSuccess)
  131.                 #       log.write(normalSuccess +"\n")
  132.  
  133.                 #   except IOError as e:
  134.                 #       normalError = ("Couldn't save out normal map, is it checked out in source control?")
  135.                 #       logging.info (normalError)
  136.                 #       log.write(normalError +"\n")
  137.                 #       pass
  138.  
  139.                 if group.name == "Masks":
  140.                     for layer in group.layers[:]:
  141.                         if layer.name == "mask":
  142.                             masks = layer
  143.                             logging.info ("Found Mask.. exporting")
  144.                             size = (1024,1024)
  145.                            
  146.                             try:
  147.                                 masks.as_PIL().thumbnail(size,Image.BICUBIC)
  148.                                 masks.as_PIL().save(TGAdir + exportName[:-4] + '_mask.tga')
  149.            
  150.                                 maskSuccess = ("Successfully saved out mask!")
  151.                                 logging.info (maskSuccess)
  152.                                 log.write(maskSuccess +"\n")
  153.  
  154.                             except IOError as e:
  155.                                 maskError = ("Couldn't save out mask, is it checked out in source control?")
  156.                                 logging.info (maskError)
  157.                                 log.write(maskError +"\n")
  158.                                 pass
  159.  
  160.  
  161.                 # if group.name == "DTL":
  162.                 #   for layer in group.layers[:]:
  163.                 #       if layer.name == "detail":
  164.                 #           size = (1024,1024) 
  165.                 #           detail = layer
  166.                 #           logging.info ("Found Detail Map.. exporting")
  167.                            
  168.                 #           try:
  169.                 #               detail.as_PIL().thumbnail(size,Image.BICUBIC)
  170.                 #               detail.as_PIL().save(TGAdir + exportName[:-4] + '_detail.tga')
  171.                                
  172.                 #               #Now opening and correcting the detail map
  173.                                
  174.                 #               detail = Image.open(TGAdir + exportName[:-4] + '_detail.tga')
  175.                 #               if detail.mode == 'RGBA':
  176.                 #                   detail = Image.merge('RGB', detail.split()[0:3])
  177.                 #               detail = PIL.ImageOps.invert(detail)
  178.                 #               detail.save(TGAdir + exportName[:-4]+ '_detail.tga')                       
  179.  
  180.                 #               detailSuccess = ("Successfully saved out detail map!")             
  181.                 #               logging.info (detailSuccess)
  182.                 #               log.write(detailSuccess +"\n")
  183.  
  184.                 #           except IOError as e:
  185.                 #               detailError = ("Couldn't save out detail map, is it checked out in source control?")
  186.                 #               logging.info (detailError)
  187.                 #               log.write(detailError +"\n")
  188.                 #               pass
  189.  
  190.  
  191.  
  192.             psdFinalTime = (time.clock()-psdTime)
  193.             log.write(("Time to export file: {0:.2f} seconds\n".format(psdFinalTime)))
  194.  
  195.  
  196.  
  197.  
  198. def startPSDexport():
  199.  
  200.     liststuff = psdExport()
  201.    
  202.     #just log things
  203.     logDir = ("C:\\Telltale\\")
  204.     logFileName = (str(time.strftime("%Y-%m-%d.%H.%M.%S")) + ".txt")
  205.     logFileName = path.join (logDir, logFileName)
  206.     log = open(logFileName,"a")
  207.    
  208.     fullTimer = time.clock()
  209.     print ('Outputting logging to {0}').format(logFileName)
  210.  
  211.     #run the batch process
  212.     liststuff.psdProcess(logFileName)
  213.  
  214.     totalTime = (time.clock()-fullTimer)
  215.  
  216.     log.write(("Time to export PSDs: {0:.2f} seconds\n".format(totalTime)))
  217.     log.close()
  218.  
  219.  
  220. #run batch process
  221. startPSDexport()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement