Advertisement
Guest User

Untitled

a guest
May 20th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.34 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. import os
  8.  
  9. from PIL import Image
  10. from operator import add, itemgetter
  11. from skimage.draw import (line, polygon, circle,
  12. circle_perimeter,
  13. ellipse, ellipse_perimeter,
  14. bezier_curve, set_color, rectangle)
  15.  
  16. TYPE = 0 # 0 elipse, 1 square, 2 else
  17. LEN = 1 #length
  18. HEI = 2 #height
  19. CEN = 3 #center
  20. COL = 4 #color
  21. TRA = 5 #transparency
  22. ZIN = 6 #z index
  23. PIX = 7 #pixel coordinates
  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, 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. #actual transparency
  76. if transp:
  77. image[rr, cc] = [new_color(f[COL], x, f[TRA]) for x in image[rr, cc]]
  78. else:
  79. image[rr, cc] = f[TRA] * f[COL]#[f[TRA] * x for x in f[COL]]
  80. figures[i][PIX] = (rr, cc)
  81. return image
  82.  
  83. def figure_fitness(img, im):
  84. score = 0
  85. no_problem = False
  86.  
  87. N, M = img.shape[0], img.shape[1]
  88. for i in range(N):
  89. for j in range(M):
  90. score += sum(abs(img[i][j] - im[i][j]))
  91. if score != 0:
  92. return score
  93. return -1
  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(ind1, ind2):
  108. rez1, rez2 = [], []
  109. chance = np.random.randint(2,size=len(ind2[0]))
  110. for z in zip(ind1[0], ind2[0], chance):
  111. rez1.append(z[z[2]])
  112. rez2.append(z[1 - z[2]])
  113. bks = ind1[1], ind2[1]
  114. return (rez1, bks[1 - chance[0]]), (rez2, bks[chance[0]])
  115.  
  116. def mutate_ind(f, chance, maxes):
  117. for i in range(1, len(f) - 1):
  118. if random.random() < chance[i]:
  119. f[i] = random.random() * maxes[i]
  120. if i == CEN:
  121. f[CEN] = np.random.uniform(size=2) * maxes[CEN]
  122. if i == COL:
  123. f[COL] = np.random.uniform(size=3) * maxes[COL]
  124. return f
  125.  
  126. def mutate_figs(humans, chance=None, maxes=[0, 100, 100, np.array([500, 500]), np.array([1, 1, 1]), 1, 1, 0]):
  127. mutants = []
  128. if chance is None:
  129. chance = np.random.uniform(size=8)
  130. chance *= 0.03
  131. for h in humans:
  132. mutants.append(mutate_ind(h.copy(), chance, maxes))
  133. return mutants
  134.  
  135. def mutate_img(indiv, maxes, chances=None, backchance = 0.05):
  136. bak = indiv[1].copy()
  137. if random.random() < backchance:
  138. bak[COL] = np.random.uniform(size=3) * maxes[COL]
  139. return (mutate_figs(indiv[0], maxes=maxes), bak)
  140.  
  141.  
  142. fig, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(10, 6))
  143.  
  144. im = Image.open("windcl.png")
  145. im=np.asarray(im)
  146. imgsize = (im.shape[0], im.shape[1])
  147.  
  148. figs_num = 15
  149. POP_SIZE = 50
  150.  
  151.  
  152.  
  153.  
  154. maxes = [0, imgsize[0]/2, imgsize[1]/2, np.array([im.shape[0], im.shape[1]]), np.array([1, 1, 1]), 1, 1, 0]
  155.  
  156. MAX_GEN = 25
  157. ATTEMPTS = 1
  158.  
  159. for a in range(ATTEMPTS):
  160. dirname = 'attempt{}'.format(a)
  161. if not os.path.exists(dirname):
  162. os.makedirs(dirname)
  163.  
  164. individuals = []
  165. for i in range(POP_SIZE):
  166. figs = get_random_figures(figs_num, maxh=imgsize[0]/2, maxl=imgsize[1]/2, c=imgsize, ftype=1)
  167. background =[1, im.shape[0], im.shape[1], [im.shape[0]/2, im.shape[1]/2], figs[0][COL], 1, 0, None]
  168. individuals.append((figs, background))
  169. for g in range(MAX_GEN):
  170.  
  171. inds = []
  172. cnt = 0
  173. fit_imgs = []
  174. for ind in individuals:
  175. img = generate_image(ind[0] + [ind[1]], imgsize)
  176. fit = figure_fitness(img, im)
  177. if fit != 0:
  178. cnt += 1
  179. fit_imgs.append((ind, fit))
  180.  
  181. fit_imgs = sorted(fit_imgs, key=itemgetter(1))
  182. print(str(g) + ' : ' +str(cnt) + '[' + str(fit_imgs[0][1]) + ']')
  183.  
  184. pop = list(zip(*fit_imgs))[0]
  185. mid = len(pop)//2
  186. quart = mid // 2
  187. fst, snd, trd, fth = pop[:quart], pop[quart:mid], pop[mid:mid+quart], pop[mid+quart:]
  188.  
  189. elites = []
  190. for s, t in zip(fst, snd):
  191. #img = generate_image(fst[0][0] + [fst[0][1]], imgsize)
  192. #print(str(g) + ' : ' +str(cnt) + '[' + str(figure_fitness(img, im)) + ']')
  193. i1, i2 = cross_over(s, t)
  194. #img = generate_image(fst[0][0] + [fst[0][1]], imgsize)
  195. #print(str(g) + ' : ' +str(cnt) + '[' + str(figure_fitness(img, im)) + ']')
  196. elites.append(i1)
  197. elites.append(mutate_img(i2, maxes))
  198.  
  199. #img = generate_image(fst[0][0] + [fst[0][1]], imgsize)
  200. #print(str(g) + ' : ' +str(cnt) + '[' + str(figure_fitness(img, im)) + ']')
  201. boomers = []
  202. for s, t in zip(snd, trd):
  203. i1, i2 = cross_over(s, t)
  204. boomers.append(mutate_img(i1, maxes))
  205. #boomers.append(mutate_img(i2, maxes))
  206.  
  207. individuals = []
  208. individuals += fst
  209. individuals += elites
  210. #individuals += newborns
  211. individuals += boomers
  212. #figs += doomers
  213.  
  214.  
  215. img = generate_image(fst[0][0] + [fst[0][1]], imgsize)
  216. scipy.misc.imsave(dirname + '/outfile{}.png'.format(g), img)
  217. #print(str(g) + ' : ' +str(cnt) + '[' + str(figure_fitness(img, im)) + ']')
  218. #ax1.imshow(img)
  219. #ax2.imshow(im)
  220.  
  221. #plt.show()
  222.  
  223. #scipy.misc.imsave('outfile{}.png'.format(a), img)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement