Exemplo n.º 1
0
def predict(img_path, model):
    img = image.load_image(img_path, target_size=(224, 224))
    x = image.img_to_array(img)
    x = np.true_divide(x, 255)
    #x = preprocess_input(x)
    preds = model.predict(x)
    return preds
Exemplo n.º 2
0
def prediction(request):
    fileobj = request.FILES['image']
    fs = FileSystemStorage()
    fs.save(fileobj.name, fileobj)
    image = fileobj.name.split('.')[:1]
    testimage = '.' + fs.url(fileobj)

    img = image.load_image(testimage, target_size=(img_height, img_height))
    x = img_to_array(img)
    x = x // 225
    x = x.reshape(1, img_height, img_width, 3)
    with model_graph.as_default():
        with tf_Session.as_default():
            pred = model.predict(x)

    import numpy as np
    predictedlable = lableInfo[str(np.argmax(pred[0]))]

    context = {
        'file': image,
        'filedisplay': fs.url(fileobj),
        'predictedlable': predictedlable[1]
    }
    return render(request, 'index.html', context)
Exemplo n.º 3
0
test_set = test_datagen.flow_from_directory('dataset/test_set',
                                            target_size=(64, 64),
                                            batch_size=32,
                                            class_mode='binary')

classifier.fit_generator(training_set,
                         steps_per_epoch=8000,
                         epochs=25,
                         validation_data=test_set,
                         validation_steps=2000)

#Part 3 Prediction Step
import numpy as np
from keras.preprocessing import image

#Load Image
test_image = image.load_image('dataset/single_prediction/cat_or_dog_1.jpg',
                              target_size=(64, 64))
#Add new dimension to convert into 3D array
test_image = image.img_to_array(test_image)
#Add one dimension again as done during training
test_image = np.expand_dims(test_image, axis=0)
result = classifier.predict(test_image)
training_set.class_indices

if (result[0][0] == 1):
    prediction = 'dog'
else:
    prediction = 'cat'
                         steps_per_epoch=12000,
                         epochs=2,
                         validation_data=test_set,
                         validation_steps=200)

#Step per epoch actually depends on how many training images you have,
#more images mean more accuracy
#Epochs mean how many training you want
#Validation data mean the variabel where you input your test images
#Validation Steps mean how many validation you want

#-----------------------------------------------------
#Prediction or Testing the Result
import numpy as np
from keras.preprocessing import image

#input test Image
test_image = image.load_image('<Input your Test Image Directory Here',
                              target_size=(64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis=0)

result = classifier.predict(test_image)
training_set.class_indices
if result[0][0] == 1:
    prediction = '<Name your result here>'
else:
    prediction = '<Name your result here>'

#----------------------------------------------------
#Congratulations, you have created the CNN!
Exemplo n.º 5
0
import keras

vgg16Model = keras.applications.vgg16.VGG16()

vgg16Model.summary()

from keras.preprocessing.image import load_image,img_to_array
from keras.applications.vgg16 import preprocess_input,decode_predictions
import numpy as np

image = load_image('books.jpg',target_size=(224,224))

image = img_to_array(image)

image = image.reshape((1,image.shape[0],image.shape[1],image.shape[0]))

image = preprocess_input(image)

prediction = vgg16Model.predict(image)
decode_predictions(prediction)
Exemplo n.º 6
0
import os
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.layers import *
from keras.models import *
from keras.preprocessing import image

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

model = load_model(os.path.join(BASE_DIR, 'model.h5'))

img = image.load_image('image.jpeg', target_size=(224, 224))
img = image.image_to_array(img)
img = np.expand_dims(img, axis=0)
p = model.predict_classes(img)
print(p)
Exemplo n.º 7
0
        class_mode='binary')

test_set = test_datagen.flow_from_directory(
        'dataset/test_set',
        target_size=(64, 64),
        batch_size=32,
        class_mode='binary')

classifier.fit_generator(training_set,
                    steps_per_epoch=8000,
                    epochs=25,
                    validation_data=test_set,
                    validation_steps=2000)

from keras.preprocessing import image
single_pred = image.load_image('dataset/single_prediction/cat_or_dog_1.jpq', grey_scale = False, target_size = (64, 64))
single_pred = image.img_to_array(single_pred)
result = classifier.predict(single_pred, batch_size = 1)
if result[0][0]==1:
    pred = 'cat'
else:
    pred = 'dog'

from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import DropOut
Exemplo n.º 8
0
validation_generator = validation_datagen.flow_from_directory(
    '/tmp/validation-horse-or-human',
    target_size=(300, 300),
    batch_size=128,
    class_mode='binary')

history = model.fit_generator(train_generator,
                              steps_per_epoch=8,
                              epochs=15,
                              verbose=1,
                              validation_data=validation_generator,
                              validation_steps=8)

uploaded = files.upload()

for fn in uploaded.keys():
    path = '/content/' + fn
    img = image.load_image(path, target_size=(300, 300))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)

    images = np.vstack([x])
    classes = model.predict(images, batch_size=10)
    print(classes[0])

    if classes[0] > 0.5:
        print(fn + 'is a human')
    else:
        print(fn + 'is a horse')
Exemplo n.º 9
0
        
    print("duration:",datetime.now()-t0)
    plt.plot(losses)
    plt.show()
    
    newing = x.reshape(*batch_shape)
    final_img = unpreprocess(newing)
    
    plt.imshow(scale_img(final_img[0]))
    plt.show()    
    
if __name__=='main': 
    
    path='download.jpg'
    
    img = image.load_image(path)
    
    x = image.img_to_array(img)
    
    x = np.expand_dims(x,axis=0)
    
    x = preprocess_input(x)
    
    batch_shape = x.shape
    shape = x.shape[1:]
    
    vgg = VGG16_AvgPool(shape)
    
    symbolic_conv_outputs = [
        layer.get_output_at(1) for layer in vgg.layers \
        if layer.name.endswith('conv1')
"""## Part 3 - Training the CNN

### Compiling the CNN
"""

cnn.compile(optimizer='adam', loss='binary_cross_entropy', metrics='accuracy')

"""### Training the CNN on the Training set and evaluating it on the Test set"""

cnn.fit(x=training_set,
        validation_data=test_set, # no transformation was applied, only feature scaling
        epochs=25)

"""## Part 4 - Making a single prediction"""

test_image = image.load_image(path='dataset/single_prediction/cat_or_dog_1.jpg'
                              image_size=(64,64))
test_image = image.img_to_array(img=test_image) # convert to numpy array
test_image = np.expand_dims(a=test_image, axis=0) # extra dimension corresponding to the batch

result = cnn.predict(x=test_image)

training_set.class_indices # which indices corresponds to which classes # currently: 0 - cat, 1 - dog

if result[0][0] == 1: # result[<batch dimension>][<first prediction>]
  prediction = 'dog'
else:
  prediction = 'cat'

print(prediction)
Exemplo n.º 11
0
                                   zoom_range=0.2,
                                   horizontal_flip=True)
# Generating images for the Test set
test_datagen = ImageDataGenerator(rescale=1. / 255)
# Creating the Training set
training_set = train_datagen.flow_from_directory('dataset/training_set',
                                                 target_size=(64, 64),
                                                 batch_size=32,
                                                 class_mode='binary')
# Creating the Test set
test_set = test_datagen.flow_from_directory('dataset/test_set',
                                            target_size=(64, 64),
                                            batch_size=32,
                                            class_mode='binary')
classifier.fit_generator(training_set,
                         samples_per_epoch=8000,
                         nb_epoch=25,
                         validation_data=test_set,
                         nb_val_samples=2000)
#4. Making new prediction
import numpy as np
from keras.preprocessing import image
test_image = image.load_image('samples.jpg', target_size=(160, 160))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis=0)
result = classifier.predict(test_image)
if (result[0][0] == 1):
    print("Yes")
else:
    print("NO")