Guest User

Untitled

a guest
Feb 23rd, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. train_datagen = ImageDataGenerator(rescale=1. / 255)
  2.  
  3. train_generator = train_datagen.flow_from_directory(
  4. train_data_dir,
  5. target_size=(img_width, img_height),
  6. batch_size=batch_size,
  7. color_mode='rgb',
  8. class_mode=None)
  9.  
  10.  
  11. validation_generator = test_datagen.flow_from_directory(
  12. validation_data_dir,
  13. target_size=(img_width, img_height),
  14. batch_size=batch_size,
  15. color_mode='rgb',
  16. class_mode=None)
  17.  
  18. input_img = Input(batch_shape=(None, img_width, img_width, 3))
  19.  
  20. #Encoder model
  21.  
  22. x = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
  23. x = MaxPooling2D((2, 2), padding='same')(x)
  24. x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
  25. x = MaxPooling2D((2, 2), padding='same')(x)
  26. x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
  27. encoded = MaxPooling2D((2, 2), padding='same')(x)
  28.  
  29. #decoder model
  30.  
  31. x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
  32. x = UpSampling2D((2, 2))(x)
  33. x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
  34. x = UpSampling2D((2, 2))(x)
  35. x = Conv2D(16, (3, 3), activation='relu')(x)
  36. x = UpSampling2D((2, 2))(x)
  37. decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)
  38.  
  39. autoencoder = Model(input_img, decoded)
  40. autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
  41. autoencoder.summary()
  42.  
  43.  
  44. autoencoder.fit_generator(
  45. fixed_generator(train_generator),
  46. steps_per_epoch=nb_train_samples // batch_size,
  47. epochs=nb_epoch,
  48. validation_data=fixed_generator(validation_generator),
  49. validation_steps=nb_validation_samples // batch_size)
  50.  
  51. autoencoder.save_weights('anomaly-detection.h5')
  52.  
  53. #Getting a random image for prediction
  54.  
  55. im = cv2.resize(cv2.imread(filePath), (224, 224, 3))
  56. im = im * 1. / 255
  57. test_image[0, :, :, :] = im;
  58.  
  59. dec = autoencoder.predict(test_image) # Decoded image
  60. test_image = img[0]
  61. dec = dec[0]
  62. test_image = (test_image * 255).astype('uint8')
  63. dec = (dec * 255).astype('uint8')
  64. mse_value = mse(dec, test_image)
  65.  
  66. if mse_value > 2.74 : #Experimental threshold based on few iterations
  67. print('Image has an anomaly inside')
Add Comment
Please, Sign In to add comment