Guest User

Untitled

a guest
Oct 6th, 2017
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.54 KB | None | 0 0
  1. import PIL
  2. import PIL.Image
  3. import PIL.ImageFont
  4. import PIL.ImageOps
  5. import PIL.ImageDraw
  6. import pandas as pd
  7. import numpy as np
  8. import os,cv2
  9. import matplotlib.pyplot as plt
  10. import keras
  11. import sklearn
  12. from sklearn import preprocessing
  13. from sklearn.utils import shuffle
  14. from sklearn.cross_validation import train_test_split
  15. from keras import backend as K
  16. K.set_image_dim_ordering('th')
  17. from keras.utils import np_utils
  18. from keras.models import Sequential
  19. from keras.layers.core import Dense, Dropout, Activation, Flatten
  20. from keras.layers.convolutional import Convolution2D, MaxPooling2D
  21. from keras.optimizers import SGD,RMSprop,adam
  22. import scipy
  23. from skimage import io
  24. %matplotlib inline
  25.  
  26. #img_rows=64
  27. #img_cols=64
  28. num_channel=1
  29. num_epoch=10
  30.  
  31. labels =[]
  32.  
  33. image=[]
  34.  
  35. for i in range (50000):
  36. img = cv2.imread("E:/data/pic/%s.png"%('{0:06}'.format(i)))
  37. img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  38. #img_resize=cv2.resize(img,(180,670))
  39. image.append(img)
  40.  
  41.  
  42. img_data = np.array(image)
  43. img_data = img_data.astype('float32')
  44. img_data /= 255
  45. print (img_data.shape)
  46.  
  47. if num_channel==1:
  48. if K.image_dim_ordering()=='th':
  49. img_data= np.expand_dims(img_data, axis=1)
  50. print (img_data.shape)
  51. else:
  52. img_data= np.expand_dims(img_data, axis=4)
  53. print (img_data.shape)
  54.  
  55. else:
  56. if K.image_dim_ordering()=='th':
  57. img_data=np.rollaxis(img_data,3,1)
  58. print (img_data.shape)
  59.  
  60. #%%
  61.  
  62.  
  63. # Assigning Labels
  64.  
  65. # Define the number of classes
  66. num_classes = 5
  67.  
  68. num_of_samples = img_data.shape[0]
  69. labels = np.ones((num_of_samples,),dtype='int64')
  70. for i in range (50000):
  71. with open('E:/data/font/%s.meta'%('{0:06}'.format(i)), 'r') as f:
  72. temp = f.readline()
  73. first_line = temp.strip()
  74. if(first_line=='Alegreya-Regular'):
  75.  
  76. labels[i] = 0
  77.  
  78. elif(first_line=='Alegreya-Bold'):
  79.  
  80. labels[i] = 1
  81.  
  82. elif(first_line=='basic_sans_serif'):
  83.  
  84. labels[i] = 2
  85.  
  86. elif(first_line=='bold_sans_serif'):
  87.  
  88. labels[i] = 3
  89.  
  90. elif(first_line=='ChargerMoSp'):
  91.  
  92. labels[i] = 4
  93.  
  94.  
  95. names = ['Alegreya-Regular','Alegreya-Bold','basic_sans_serif','bold_sans_serif','ChargerMoSp']
  96.  
  97. # convert class labels to on-hot encoding
  98. Y = np_utils.to_categorical(labels, num_classes)
  99. #Shuffle the dataset
  100. x,y = shuffle(img_data,Y, random_state=2)
  101. # Split the dataset
  102. X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2)
  103.  
  104. model = Sequential()
  105. model.add(Convolution2D(16, kernel_size=(5, 5), strides=(1, 1),activation='relu',input_shape=(1,180,670)))
  106. model.add(Convolution2D(16, kernel_size=(5, 5), strides=(1, 1),activation='relu'))
  107. keras.layers.normalization.BatchNormalization(axis=-1, momentum=0.9, epsilon=0.001, center=True,scale=False, beta_initializer='zeros',gamma_initializer='ones', moving_mean_initializer='zeros',moving_variance_initializer='ones',beta_regularizer=None, gamma_regularizer=None,beta_constraint=None, gamma_constraint=None)
  108. model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
  109. model.add(Convolution2D(16, (5, 5), activation='relu'))
  110. model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
  111. keras.layers.normalization.BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True,scale=False, beta_initializer='zeros',gamma_initializer='ones', moving_mean_initializer='zeros',moving_variance_initializer='ones',beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None)
  112. model.add(Convolution2D(16, (3, 3), activation='relu'))
  113. keras.layers.normalization.BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True,scale=False, beta_initializer='zeros',gamma_initializer='ones', moving_mean_initializer='zeros',moving_variance_initializer='ones',beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None)
  114. model.add(MaxPooling2D(pool_size=(2, 2)))
  115. model.add(Convolution2D(32, (3, 3), activation='relu'))
  116. model.add(MaxPooling2D(pool_size=(2, 2)))
  117. model.add(Dropout(0.5))
  118. model.add(Flatten())
  119. model.add(Dense(64, activation='relu'))
  120. model.add(Dropout(0.5))
  121. model.add(Dense(num_classes, activation='softmax'))
  122.  
  123. #sgd = SGD(lr=learning_rate, decay=decay, momentum=0.9, nesterov=False)
  124. model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=False),metrics=['accuracy'])
  125.  
  126. # Viewing model_configuration
  127.  
  128. model.summary()
  129. model.get_config()
  130. model.layers[0].get_config()
  131. model.layers[0].input_shape
  132. model.layers[0].output_shape
  133. model.layers[0].get_weights()
  134. np.shape(model.layers[0].get_weights()[0])
  135. model.layers[0].trainable
  136.  
  137. # Training
  138. hist = model.fit(X_train, y_train, batch_size=16, nb_epoch=num_epoch, verbose=1, validation_data=(X_test, y_test))
  139.  
  140. #hist = model.fit(X_train, y_train, batch_size=32, nb_epoch=20,verbose=1, validation_split=0.2)
  141. # visualizing losses and accuracy
  142. train_loss=hist.history['loss']
  143. val_loss=hist.history['val_loss']
  144. train_acc=hist.history['acc']
  145. val_acc=hist.history['val_acc']
  146. xc=range(num_epoch)
  147.  
  148. score = model.evaluate(X_test, y_test, verbose=0)
  149. print('Test Loss:', score[0])
  150. print('Test accuracy:', score[1])
  151.  
  152. test_image = X_test[0:1]
  153. print (test_image.shape)
  154.  
  155. print(model.predict(test_image))
  156. print(model.predict_classes(test_image))
  157. print(y_test[0:1])
  158. # Testing a new image
  159. test_image = cv2.imread('C:/Users/Parvin.E/Desktop/data2/pic/000085.png')
  160. test_image=cv2.cvtColor(test_image, cv2.COLOR_BGR2GRAY)
  161. #test_image=cv2.resize(test_image,(64,64))
  162. test_image = np.array(test_image)
  163. test_image = test_image.astype('float32')
  164. test_image /= 255
  165. print (test_image.shape)
  166.  
  167. if num_channel==1:
  168. if K.image_dim_ordering()=='th':
  169. test_image= np.expand_dims(test_image, axis=0)
  170. test_image= np.expand_dims(test_image, axis=0)
  171. print (test_image.shape)
  172. else:
  173. test_image= np.expand_dims(test_image, axis=3)
  174. test_image= np.expand_dims(test_image, axis=0)
  175. print (test_image.shape)
  176.  
  177. else:
  178. if K.image_dim_ordering()=='th':
  179. test_image=np.rollaxis(test_image,2,0)
  180. test_image= np.expand_dims(test_image, axis=0)
  181. print (test_image.shape)
  182. else:
  183. test_image= np.expand_dims(test_image, axis=0)
  184. print (test_image.shape)
  185. # Predicting the test image
  186. print((model.predict(test_image)))
  187. print(model.predict_classes(test_image))
Add Comment
Please, Sign In to add comment