1
0

tile2bytes.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. from PIL import Image
  2. def rgb_to_hsl(r, g, b):
  3. r = float(r)
  4. g = float(g)
  5. b = float(b)
  6. high = max(r, g, b)
  7. low = min(r, g, b)
  8. h, s, v = ((high + low) / 2,)*3
  9. return v
  10. #img: image to process
  11. #x: starting x position
  12. #y: starting y position
  13. #idx: index of pattern table, corresponding to index of tiles
  14. def createPattern(img, x, y, idx):
  15. tile = []
  16. for a in range(8):
  17. tileLine = []
  18. for b in range(8):
  19. pixel = px[x*8+b, y*8+a]
  20. tileLine.append(pixel)
  21. tile.append(tileLine)
  22. colorList = []
  23. lumlist = []
  24. for a in range(8):
  25. for b in range(8):
  26. if tile[a][b] not in colorList:
  27. colorList.append(tile[a][b])
  28. if len(colorList) > 4:
  29. print("tile ", idx, " has more than 4 colors")
  30. #order color list from dark to light
  31. colorList.sort(key=lambda x: rgb_to_hsl(x[0], x[1], x[2]) )
  32. print(".dw 0b", end = '')
  33. for a in range(8):
  34. for b in range(8):
  35. if colorList.index(tile[a][b]) == 0:
  36. print("00", end = '')
  37. if colorList.index(tile[a][b]) == 1:
  38. print("01", end = '')
  39. if colorList.index(tile[a][b]) == 2:
  40. print("10", end = '')
  41. if colorList.index(tile[a][b]) == 3:
  42. print("11", end = '')
  43. if (a+1) % 2 == 0 and a != 7:
  44. print()
  45. print(".dw 0b", end = '')
  46. print(" ; tile ", idx)
  47. im = Image.open('tiles.png')
  48. width, height = im.size
  49. px = im.load()
  50. #print(px[0,0])
  51. print("Width:", width, "px")
  52. print("Height:", height, "px")
  53. if (width%8 != 0):
  54. print("Width not dividable by 8")
  55. exit(1)
  56. if (height%8 != 0):
  57. print("Height not dividable by 8")
  58. exit(1)
  59. htiles = int(width / 8)
  60. vtiles = int(height / 8)
  61. tiles = htiles * vtiles
  62. print("Horizontal tiles:", htiles)
  63. print("Vertical tiles:", vtiles)
  64. print("Total number of tiles:", tiles)
  65. print("Index of tiles:")
  66. tile_i = 0
  67. for y in range(vtiles):
  68. for x in range(htiles):
  69. print (str(tile_i) + "\t", end = '')
  70. tile_i = tile_i + 1
  71. #function: create pattern of tile
  72. print()
  73. print()
  74. print()
  75. tile_i = 0
  76. for y in range(vtiles):
  77. for x in range(htiles):
  78. createPattern(px, x, y, tile_i)
  79. tile_i = tile_i + 1
  80. #createPattern(px, 0, 0, 0)