Advertisement
Guest User

Untitled

a guest
May 20th, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.65 KB | None | 0 0
  1. import math
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import itertools
  5. import random
  6. import scipy.misc
  7.  
  8. from PIL import Image
  9. from operator import add, itemgetter
  10. from skimage.draw import (line, polygon, circle,
  11. circle_perimeter,
  12. ellipse, ellipse_perimeter,
  13. bezier_curve, set_color, rectangle)
  14.  
  15. TYPE = 0 # 0 elipse, 1 square, 2 else
  16. LEN = 1 #length
  17. HEI = 2 #height
  18. CEN = 3 #center
  19. COL = 4 #color
  20. TRA = 5 #transparency
  21. ZIN = 6 #z index
  22. PIX = 7 #pixel coordinates
  23.  
  24.  
  25. def new_color(cf, cb, t):
  26. cf1 = [x * t for x in cf]
  27. cb1 = [x * (1 - t) for x in cb]
  28. return list(map(add, cf1, cb1))
  29.  
  30.  
  31. def get_poligon(f):
  32. cx, cy = f[CEN]
  33. l = f[LEN]
  34. h = f[HEI]
  35. p1 = [cx - l, cx - l, cx + l, cx + l]
  36. p2 = [cy - h, cy + h, cy + h, cy - h]
  37. return p1, p2
  38.  
  39. def get_random_figures(POP, maxl=120, maxh=120, c=(500, 500), ftype=None):
  40. FIGS = []
  41. types = None
  42. if ftype is not None:
  43. if ftype == 1:
  44. types = np.ones(POP)
  45. elif ftype == 0:
  46. types = np.zeros(POP)
  47. else:
  48. types = np.random.randint(2, size=POP)
  49. lengths = np.random.randint(low=1, high=maxl, size=POP)
  50. heights = np.random.randint(low=1, high=maxh, size=POP)
  51. ycenters = np.random.randint(c[0], size=POP)
  52. xcenters = np.random.randint(c[1], size=POP)
  53. centers = np.column_stack((ycenters, xcenters))
  54. colors = np.random.uniform(size=(POP, 3))
  55. transps = np.random.uniform(size=(POP))
  56. zs = np.random.uniform(size=(POP))
  57.  
  58. for i in range(POP):
  59. FIGS.append([types[i], lengths[i], heights[i], centers[i], colors[i], transps[i], zs[i], None])
  60. return FIGS
  61.  
  62.  
  63. def generate_image(figures, size, front_pixels, transp=False):
  64. image = np.zeros((size[0], size[1], 3), dtype=np.double)
  65. figures = sorted(figures, key=itemgetter(ZIN))
  66. for i in range(len(figures)):
  67. rr = 0
  68. cc = 0
  69. f = figures[i]
  70. if f[TYPE] == 0:
  71. rr, cc = ellipse(f[CEN][0], f[CEN][1], f[LEN] / 2, f[HEI] / 2, image.shape)
  72. elif f[TYPE] == 1:
  73. p1, p2 = get_poligon(f)
  74. rr, cc = polygon(p1, p2, image.shape)
  75. if transp:
  76. image[rr, cc] = [new_color(f[COL], x, f[TRA]) for x in image[rr, cc]]
  77. else:
  78. image[rr, cc] = f[TRA] * f[COL]
  79. figures[i][PIX] = (rr, cc)
  80. front_pixels[rr, cc] = i
  81. return image, front_pixels
  82.  
  83. def figure_fitness(figure, img, im):
  84. rr, cc = figure[PIX]
  85. score = 0
  86. no_problem = False
  87. clr = [figure[TRA] * x for x in figure[COL]]
  88.  
  89. for r, c in zip(rr, cc):
  90. score += sum(abs(im[r][c] - clr))
  91.  
  92. return score / max(1, len(rr))
  93.  
  94.  
  95.  
  96. def get_children(parents, count):
  97. children = []
  98. for i in range(count):
  99. p1, p2 = random.choice(parents), random.choice(parents)
  100. chance = np.random.randint(2,size=8)
  101. child = []
  102. for p in zip(p1, p2, chance):
  103. child.append(p[p[2]])
  104. children.append(child)
  105. return children
  106.  
  107. def cross_over(men, women):
  108. aphrodites = []
  109. for x, y in zip(men, women):
  110. x1, y1 = [], []
  111. chance = np.random.randint(2,size=8)
  112. for z in zip(x, y, chance):
  113. x1.append(z[z[2]])
  114. y1.append(z[1 - z[2]])
  115. aphrodites.append(x1)
  116. aphrodites.append(y1)
  117. return aphrodites
  118.  
  119. def mutate_ind(f, chance, maxes):
  120. for i in range(1, len(f) - 1):
  121. if random.random() < chance[i]:
  122. f[i] = random.random() * maxes[i]
  123. if i == CEN:
  124. f[CEN] = np.random.uniform(size=2) * maxes[CEN]
  125. if i == COL:
  126. f[COL] = np.random.uniform(size=3) * maxes[COL]
  127. return f
  128.  
  129. def mutate_pop(humans, chance=None, maxes=[0, 100, 100, np.array([500, 500]), np.array([1, 1, 1]), 1, 1, 0]):
  130. mutants = []
  131. if chance is None:
  132. chance = np.random.uniform(size=8)
  133. chance *= 0.07
  134. for h in humans:
  135. mutants.append(mutate_ind(h.copy(), chance, maxes))
  136. return mutants
  137.  
  138.  
  139.  
  140. fig, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(10, 6))
  141.  
  142.  
  143. #im = Image.open("mona_lisa.png")
  144. im = Image.open("windcl.png")
  145. im=np.asarray(im)
  146. imgsize = (im.shape[0], im.shape[1])
  147.  
  148. population = 45
  149. MAX_GEN = 50
  150. ATTEMPTS = 1
  151. MAX_DIM = 0.5
  152.  
  153. front_pixels = np.zeros((im.shape[0], im.shape[1]))
  154. maxes = [0, imgsize[0] * MAX_DIM, imgsize[1] * MAX_DIM, np.array([im.shape[0], im.shape[1]]), np.array([1, 1, 1]), 1, 1, 0]
  155.  
  156.  
  157. def visible_figs(figures, front_pixels):
  158. goodfigs = []
  159. print(np.unique(front_pixels.flat))
  160. for idx in np.unique(front_pixels.flat):
  161. goodfigs.append(figures[int(idx)])
  162. return goodfigs
  163.  
  164. for a in range(ATTEMPTS):
  165. figs = get_random_figures(population, maxh=imgsize[0] * MAX_DIM, maxl=imgsize[1] * MAX_DIM, c=imgsize, ftype=1)
  166. img, front_pixels = generate_image(figs, imgsize, front_pixels)
  167. for g in range(MAX_GEN):
  168.  
  169. figs1 = []
  170. cnt = 0
  171.  
  172. for f in figs:
  173. fit = figure_fitness(f, img, im)
  174. cnt += 1
  175. figs1.append((f, fit))
  176.  
  177. print('cnt: ' + str(cnt) + ' fitness: ' + str(sum([x[1] for x in figs1])))
  178. figs1 = sorted(figs1, key=itemgetter(1))
  179. figs1 = list(zip(*figs1))[0]
  180. mid = len(figs1)//2
  181. quart = mid // 2
  182. fst, snd, trd, fth = figs1[:quart], figs1[quart:mid], figs1[mid:mid+quart], figs1[mid+quart:]
  183.  
  184. newborns = get_children(fst, (population - cnt)//2)
  185. newborns += get_children(fth, (population - cnt)//2)
  186. newborns = mutate_pop(newborns, maxes=maxes)
  187. boomers = cross_over(fst, snd)
  188. doomers = mutate_pop(trd, maxes=maxes)
  189.  
  190. figs = []
  191. figs += fst
  192. figs += newborns
  193. figs += boomers
  194. figs += doomers
  195. print(len(figs))
  196. img, front_pixels = generate_image(figs, imgsize, front_pixels)
  197. figs = visible_figs(figs, front_pixels)
  198. front_pixels = np.zeros((im.shape[0], im.shape[1]))
  199. scipy.misc.imsave('outfile{}.png'.format(g), img)
  200. #ax1.imshow(img)
  201. #ax2.imshow(im)
  202.  
  203. #plt.show()
  204.  
  205. #scipy.misc.imsave('outfile{}.png'.format(a), img)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement