Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.63 KB | None | 0 0
  1. import keras
  2. from keras.datasets import mnist
  3. from keras.models import Sequential
  4. from keras.layers import Dense, Dropout, Flatten, Activation, Reshape
  5. from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D
  6. import numpy as np
  7. import pandas as pd
  8. from collections import OrderedDict
  9. import itertools
  10. import matplotlib.pyplot as plt
  11. import matplotlib.patches as patches
  12. import random
  13. from sklearn.model_selection import train_test_split
  14. from sklearn.preprocessing import OneHotEncoder
  15. import math
  16. from math import sqrt
  17. from keras.models import Model, load_model
  18.  
  19. def create_blank_image(size):
  20. data = np.ndarray(shape=(size, size))
  21. for i in range(0, size):
  22. for j in range(0, size):
  23. data[[i], [j]] = 0
  24. #print(data)
  25.  
  26. return data
  27.  
  28. def circle_randomizer():
  29. number_of_circles = random.randint(4,10)
  30. intensity = np.ndarray(shape=(128, 128))
  31. #print(number_of_circles)
  32. radius_list = []
  33.  
  34.  
  35. for i in range(number_of_circles):
  36. radius_list.append(random.uniform(8, 10))
  37. #print(radius_list)
  38.  
  39. center_coords = np.zeros((2,1))
  40. center_coords[[0],[0]] = random.uniform(0,size)
  41. center_coords[[1],[0]] = random.uniform(0,size)
  42.  
  43. for i in range(number_of_circles):
  44. #temp_array = np.ndarray(shape=(2,1))
  45. #temp_array[[0],[0]] = random.uniform(0,size)
  46. #temp_array[[1],[0]] = random.uniform(0,size)
  47.  
  48. if i > 0:
  49. j = 0
  50. #print(i,j)
  51. while j in range(i):
  52. #print(i,j)
  53. #print(center_coords)
  54. temp_array = np.ndarray(shape=(2,1))
  55. temp_array[[0],[0]] = random.uniform(0,size)
  56. temp_array[[1],[0]] = random.uniform(0,size)
  57. #while sqrt((center_coords[[0],[i]] - center_coords[[0],[j]])**2 + (center_coords[[1],[i]] - center_coords[[1],[j]])**2) < radius_list[i] + radius_list[j]:
  58. while sqrt((temp_array[[0],[0]] - center_coords[[0],[j]])**2 + (temp_array[[1],[0]] - center_coords[[1],[j]])**2) < radius_list[i] + radius_list[j]:
  59. temp_array[[0],[0]] = random.uniform(0,size)
  60. temp_array[[1],[0]] = random.uniform(0,size)
  61. j = 0
  62. center_coords = np.concatenate((center_coords,temp_array), axis = 1)
  63. j = j + 1
  64. #print('loop ran ' + str(j) + ' times')
  65.  
  66. return radius_list, center_coords
  67.  
  68. def image_creator(centers, radii, img_data, size):
  69. x = np.arange(1, size, 1)
  70. y = np.arange(1, size, 1)
  71.  
  72. for c in range(len(centers)):
  73. x0 = centers[[c],[0]]
  74. y0 = centers[[c],[1]]
  75. radius = radii[c]
  76. for i in range(0, size-1):
  77. for j in range(0, size-1):
  78. height2 = radius**2 - (x[i]-x0)**2 - (y[j]-y0)**2
  79. if height2 >= 0:
  80. img_data[[i], [j]] = sqrt(radius**2 - (x[i]-x0)**2 - (y[j]-y0)**2)
  81.  
  82. return img_data
  83.  
  84. def make_ellipses(size, radii, center_coords):
  85. # idea: use a random number generator to create a random rotation of the x,y axes for the ellipse
  86.  
  87. # size is the length of a side of the square
  88. # length is the length of the ellipse
  89. # defined as equal to the radius of the circle later
  90.  
  91. my_label = np.ndarray(shape=(size, size))
  92. x = np.arange(1, size, 1)
  93. y = np.arange(1, size, 1)
  94.  
  95. # inefficiently zero the array
  96. for i in range(0, size):
  97. for j in range(0, size):
  98. my_label[[i], [j]] = 0
  99. # print(my_label)
  100. for c in range(len(center_coords)):
  101. x0 = center_coords[[c],[0]]
  102. y0 = center_coords[[c],[1]]
  103. #theta = random.uniform(0, 6.28318)
  104. theta = 0.775
  105.  
  106. for i in range(0, size - 1):
  107. for j in range(0, size - 1):
  108. xprime = (x[i] - x0) * math.cos(theta) + (y[j] - y0) * math.sin(theta)
  109. yprime = -(x[i] - x0) * math.sin(theta) + (y[j] - y0) * math.cos(theta)
  110. height2 = (0.5 * radii[c]) ** 2 - 0.25 * xprime ** 2 - yprime ** 2
  111. if height2 >= 0:
  112. my_label[[i], [j]] = sqrt((0.5 * radii[c]) ** 2 - 0.25 * xprime ** 2 - yprime ** 2)
  113.  
  114. return my_label
  115.  
  116. size = 128
  117. radii, centers = circle_randomizer()
  118. #print(radii)
  119. #print(centers)
  120.  
  121. #Make labels and samples consistent with rest of code
  122. N = 100
  123. circle_images = []
  124. ellipse_images = []
  125. coords = []
  126. for sample in range(0, N):
  127. blank_image = create_blank_image(size)
  128. radii, centers = circle_randomizer()
  129. temp_image = image_creator(centers, radii, blank_image, size)
  130. circle_images.append(temp_image)
  131. temp_output = make_ellipses(size, radii, centers)
  132. ellipse_images.append(temp_output)
  133. coords.append(centers)
  134. #print(labels)
  135. #print(samples[0][40])
  136.  
  137. filenames = []
  138. for i in range(0,N):
  139. np.save('ellipses_' + str(i) + '.npy', ellipse_images[i])
  140. filenames.append('ellipses_' + str(i) + '.npy')
  141. np.save('circles_' + str(i) + '.npy', circle_images[i])
  142. circles_stack = np.stack(circle_images,axis=0)
  143. ellipses_stack = np.stack(ellipse_images,axis=0)
  144. np.save('ellipses_stack.npy', ellipses_stack)
  145. np.save('circles_stack.npy', circles_stack)
  146.  
  147. # load training images and corresponding "labels"
  148. # training samples
  149. training_images_path = 'circles_stack.npy'
  150. labels_path = 'ellipses_stack.npy'
  151.  
  152. X = np.load(training_images_path,'r')/20.
  153. y = np.load(labels_path,'r')/20.
  154.  
  155. # Preprocessing for training images
  156. def preprocessing_X(image_data, image_size):
  157. image_data = image_data.reshape(image_data.shape[0], image_size[0], image_size[1], 1)
  158. image_data = image_data.astype('float32')
  159. image_data = (image_data - np.amin(image_data))/(np.amax(image_data) - np.amin(image_data))
  160. return image_data
  161.  
  162.  
  163. # preprocessing for "labels" (ground truth)
  164. def preprocessing_Y(image_data, image_size):
  165. n_images = 0
  166. label = np.array([])
  167. for idx in range(image_data.shape[0]):
  168. img = image_data[idx,:,:]
  169. n, m = img.shape
  170. img = np.array(OneHotEncoder(n_values=nb_classes).fit_transform(img.reshape(-1,1)).todense())
  171. img = img.reshape(n, m, nb_classes)
  172. label = np.append(label, img)
  173. n_images += 1
  174. label_4D = label.reshape(n_images, image_size[0], image_size[1], nb_classes)
  175. return label_4D
  176.  
  177. # Split into train/test and make the shapes of tensors compatible with tensorflow format
  178. nb_classes = 10
  179. target_size = (128, 128)
  180.  
  181. #Below line randomizes which images are picked for train/test sets. ~20% will go to test.
  182. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)
  183. X_train = preprocessing_X(X_train, target_size)
  184. X_test = preprocessing_X(X_test, target_size)
  185. y_train = preprocessing_Y(y_train, target_size)
  186. y_test = preprocessing_Y(y_test, target_size)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement