SHARE
TWEET

Untitled

a guest Jun 27th, 2019 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. LETTER_IMAGES_FOLDER = "datasets"
  2. MODEL_FILENAME = "fonts_model.hdf5"
  3. MODEL_LABELS_FILENAME = "model_labels.dat"
  4.  
  5.  
  6. data = pd.read_csv('annotations.csv')
  7.  
  8. paths = list(data['Path'].values)
  9. Y = list(data['Font'].values)
  10.  
  11. encoder = LabelEncoder()
  12. encoder.fit(Y)
  13. Y = encoder.transform(Y)
  14. Y = np_utils.to_categorical(Y)
  15.  
  16. data = []
  17.  
  18. # loop over the input images
  19. for image_file in paths:
  20.     # Load the image and convert it to grayscale
  21.     image = cv2.imread(image_file)
  22.     image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  23.  
  24.     # Add a third channel dimension to the image to make Keras happy
  25.     image = np.expand_dims(image, axis=2)
  26.  
  27.     # Add the letter image and it's label to our training data
  28.     data.append(image)
  29.  
  30. data = np.array(data, dtype="float") / 255.0
  31.  
  32. train_x, test_x, train_y, test_y = model_selection.train_test_split(data,Y,test_size = 0.1, random_state = 0)
  33.  
  34.  
  35. # Save the mapping from labels to one-hot encodings.
  36. # We'll need this later when we use the model to decode what it's predictions mean
  37. with open(MODEL_LABELS_FILENAME, "wb") as f:
  38.     pickle.dump(encoder, f)
  39.  
  40. # Build the neural network!
  41. model = Sequential()
  42.  
  43. # First convolutional layer with max pooling
  44. model.add(Conv2D(20, (5, 5), padding="same", input_shape=(100, 100, 1), activation="relu"))
  45. model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
  46.  
  47. # Second convolutional layer with max pooling
  48. model.add(Conv2D(50, (5, 5), padding="same", activation="relu"))
  49. model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
  50. model.add(Flatten())
  51. model.add(Dense(500, activation="relu"))
  52. print (len(encoder.classes_))
  53. model.add(Dense(len(encoder.classes_), activation="softmax"))
  54.  
  55. # Ask Keras to build the TensorFlow model behind the scenes
  56. model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
  57.  
  58. # Train the neural network
  59. model.fit(train_x, train_y, validation_data=(test_x, test_y), batch_size=32, epochs=2, verbose=1)
  60.  
  61. # Save the trained model to disk
  62. model.save(MODEL_FILENAME)
  63.      
  64. predictions = model.predict(letter_image)
  65. print (predictions) # this has the length of 1
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top