Loading

almost finished

  1. import math
  2. import time
  3. import datetime
  4. import os
  5. from os import remove
  6. from PIL import Image
  7. from multiprocessing import Pool
  8. import multiprocessing
  9.  
  10. #starting message
  11. print("-"*79)
  12. print("Starting...")
  13.  
  14. #path definition
  15. diskPath = 'D:/OpenTTD_repositories/BRIX/scripts/' #"C:/Users/Pavel/Downloads/scripts/"#"E:/_BRIX/_BRIX-repository/scripts/"
  16. inputFolder = diskPath + "input/"
  17. outputFolder = diskPath + "output/"
  18.  
  19. os.makedirs(outputFolder, exist_ok = True)
  20.  
  21. #printing path just to check
  22. print("inputFolder is " + inputFolder)
  23. print("outputFolder is " + outputFolder)
  24.  
  25. #started time
  26. tt = time.time()
  27. startedTime = datetime.datetime.fromtimestamp(tt).strftime('%H:%M:%S')
  28.  
  29.  
  30.  
  31. #open palette image
  32. palette = Image.open(inputFolder + "openttd-palette-dos.png")
  33. print("Opening and loading palette: " + "openttd-palette-dos.png")  
  34.  
  35. p=[]
  36.  
  37. for b in range(0,palette.height):
  38.   for a in range(0, palette.width):
  39.     p.append(palette.getpixel((a,b)))
  40.    
  41. print('Palette loaded.')
  42.  
  43. # ----------------------------------------------------------------------------------------------------------------
  44. # ----------------------------------------------------------------------------------------------------------------
  45. # ----------------------------------------------------------------------------------------------------------------
  46.  
  47.  
  48. def rgb2palette(args):
  49.   input_image = args[0]
  50.   x_start = args[1]
  51.   x_end = args[2]
  52.  
  53.   #open input image
  54.   i = Image.open(inputFolder + input_image + ".png")
  55.   #i.show()
  56.   print("Opening: " + input_image + ".png")  
  57.  
  58.   #create new empty image for output
  59.   imageOutput = Image.new("RGBA", (i.width,i.height), color=(0,0,0,0))
  60.  
  61.   for y in range (0, i.height):
  62.     #timeStamp
  63.     ts = time.time()
  64.     timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
  65.     #print(timeStamp + " - " + input_image + " row {}".format(y))
  66.     for x in range (x_start, x_end):
  67.       #print(timeStamp + " - " + input_image + " row {}".format(x))
  68.       #defining winner variables
  69.       winnerDistance = 100000000
  70.       winnerID = 0
  71.      
  72.       #loading pixel from image and separating RGBA
  73.       pixelNumber = x + (y * i.width)
  74.       pix = i.getpixel((x,y))
  75.       pixRed = pix[0]
  76.       pixGreen = pix[1]
  77.       pixBlue = pix[2]
  78.       pixAlpha = pix[3]
  79.            
  80.       #check Alpha in pixel, and output alpha/color offset
  81.       if pixAlpha < 128:
  82.         finalAlpha = 0
  83.         colorOffset = 0
  84.       if pixAlpha >= 128 and pixAlpha < 178:
  85.         finalAlpha = 255
  86.         colorOffset = 1
  87.       if pixAlpha >= 178 and pixAlpha < 230:
  88.         finalAlpha = 255
  89.         colorOffset = 2
  90.       if pixAlpha >= 230:
  91.         finalAlpha = 255
  92.         colorOffset = 0
  93.      
  94.       #if alpha above 50%, do colour comparing to palette
  95.       if pixAlpha >= 128:
  96.         for z, (r1, g1, b1, ca) in enumerate(p):
  97.           #dr = pixRed - cr
  98.           #dg = pixGreen - cg
  99.           #db = pixBlue - cb
  100.           #distance = dr*dr + dg*dg + db*db
  101.           l1 = (r1*299 + g1*587 + b1*114) / 255000
  102.           l2 = (pixRed*299 + pixGreen*587 + pixBlue*114) / 255000
  103.           dL = l1-l2
  104.           dR = (r1-pixRed)/255
  105.           dG = (g1-pixGreen)/255
  106.           dB = (b1-pixBlue)/255
  107.           distance = (dR*dR*0.299 + dG*dG*0.587 + dB*dB*0.114)*0.75 + dL*dL
  108.          
  109.           if distance < winnerDistance:
  110.             winnerDistance = distance
  111.             winnerID = z
  112.    
  113.       #compare input RGB channels and output highest value
  114.       if pixRed >= pixGreen and pixRed >= pixBlue:
  115.         highestValue = pixRed
  116.       if pixGreen >= pixRed and pixGreen >= pixBlue:
  117.         highestValue = pixGreen
  118.       if pixBlue >= pixRed and pixBlue >= pixGreen:
  119.         highestValue = pixBlue    
  120.       # set color offset +/- based on colour value
  121.       if highestValue < 128:
  122.         negation = -1
  123.         colorOffset = colorOffset * negation
  124.       #print("colorOffset is ... " + str(colorOffset) )
  125.      
  126.       #final color changed by colorOffset
  127.       finalColor = p[winnerID - colorOffset]
  128.      
  129.       finalR = finalColor[0]
  130.       finalG = finalColor[1]
  131.       finalB = finalColor[2]
  132.       #finalAlpha taken from the if output above palette colour comparing
  133.      
  134.  
  135.       #put the final pixel into the output picture
  136.       imageOutput.putpixel((x,y),(finalR,finalG,finalB,finalAlpha))
  137.       #print("Pixel " + str(pixelNumber) + ": R= " + str(finalR) + ", G= " + str(finalG) + ", B= " + str(finalB) + ", A= "  + str(finalAlpha)   )
  138.      
  139.    
  140.   print('Saving picture to Output')
  141.   print(str(finalColor))
  142.   imageOutput.save(outputFolder + input_image[-5:] + "WTF_TESTING_8bpp.png") #assumes _#### frame number format (removes last 5 characters)
  143.  
  144.      
  145.  
  146.      
  147.      
  148. def run():
  149.   # ----------------------------------------------------------------------------------------------------------------
  150.   #VARIABLES
  151.   # ----------------------------------------------------------------------------------------------------------------
  152.   job_list = [
  153.       #'test0'
  154.       #'STATUE'
  155.       'BRIDGES_0000'
  156.       #'LAND_OUTPUT_0000'
  157.       ]
  158.   # ----------------------------------------------------------------------------------------------------------------
  159.   thread_count = 16
  160.   # ----------------------------------------------------------------------------------------------------------------
  161.   # ----------------------------------------------------------------------------------------------------------------
  162.   # ----------------------------------------------------------------------------------------------------------------
  163.  
  164.   for job in job_list:
  165.     all_jobs = []
  166.     job_chunks = []
  167.     queue = []
  168.  
  169.     extra = 0
  170.     chunk_image = Image.open(inputFolder + job + ".png")
  171.     chunk_average_size = math.floor(chunk_image.width/thread_count)
  172.     chunk_modulo_size = chunk_image.width % thread_count
  173.     for thread in range(0, thread_count):
  174.       start = chunk_average_size * thread
  175.       end = (chunk_average_size * (thread+1)) -1
  176.  
  177.       start += extra
  178.       if thread < chunk_modulo_size:  
  179.         extra += 1
  180.       end += extra
  181.  
  182.       start_and_end = [job, start, end]
  183.      
  184.       job_chunks.append(start_and_end)
  185.  
  186.       queue.append( [job, start, end] )
  187.       #print(str(queue))
  188.  
  189.     all_jobs.append(job_chunks)
  190.  
  191.     for a_job in all_jobs:
  192.       #print('-'*32)
  193.       thread_id = 0
  194.       for b_thread in a_job:
  195.         if thread_id == 0:
  196.           thread_id += 1
  197.           print('Job: ' + str(b_thread[0]))#
  198.           print(' '*10 + 'Start, ' + 'End')#
  199.           print('Thread ' + str(thread_id) + ': ' + str(b_thread[1]) + ', ' + str(b_thread[2]))#
  200.        
  201.        
  202.     print(queue)
  203.    
  204.     # ----------------------------------------------------------------------------------------------------------------
  205.     # PROCESS
  206.     # ----------------------------------------------------------------------------------------------------------------
  207.    
  208.     pool = multiprocessing.Pool(processes = thread_count)
  209.     pool.map(rgb2palette, queue)
  210.     pool.close()
  211.     pool.join()
  212.  
  213.    
  214.     #imageOutput.save(outputFolder + input_image[-5:] + "_8bpp.png") #assumes _#### frame number format (removes last 5 characters)
  215.     #print('SAVING IMAGE')
  216.  
  217.    
  218.     #finished time
  219.     tx = time.time()
  220.     finishedTime = datetime.datetime.fromtimestamp(tx).strftime('%H:%M:%S')
  221.    
  222.     print("Started:  " + startedTime)
  223.     print("Finished: " + finishedTime)
  224.    
  225.  
  226. #run()
  227.  
  228. if __name__ == '__main__':
  229.   #freeze_support()
  230.   run()

Comments