示例#1
0
def data_augmentation_example(input_path, count):
    # load image to array
    image = img_to_array(load_img(input_path))

    # reshape to array rank 4
    image = image.reshape((1, ) + image.shape)

    # let's create infinite flow of images
    train_datagen = ImageDataGenerator(rotation_range=45,
                                       width_shift_range=0.2,
                                       height_shift_range=0.2,
                                       shear_range=0.2,
                                       zoom_range=0.25,
                                       horizontal_flip=True,
                                       fill_mode='nearest')
    images_flow = train_datagen.flow(image, batch_size=1)

    plt.figure(figsize=(9, 9))
    for idx, new_images in enumerate(images_flow):
        if idx < count:
            plt.subplot(330 + 1 + idx)
            new_image = array_to_img(new_images[0], scale=True)
            plt.imshow(new_image)
            plt.axis('off')
        else:
            plt.show()
            break
示例#2
0
def extract_features(file):
    model = VGG16()
    model = Model(inputs=model.inputs, outputs=model.layers[-2].output)
    image = load_img(file, target_size=(224, 224))
    image = img_to_array(image)
    image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
    image = preprocess_input(image)
    feature = model.predict(image, verbose=0)
    return feature
示例#3
0
def grad_cam(input_model, image, category_index, layer_name, nb_classes):
    # nb_classes = 2
    target_layer = lambda x: target_category_loss(x, category_index, nb_classes
                                                  )
    x = Lambda(target_layer, output_shape=target_category_loss_output_shape)(
        input_model.output)
    model = Model(inputs=input_model.input, outputs=x)
    model.summary()
    loss = K.sum(model.output)
    # for l in model.layers:
    #     if l.name == layer_name:
    #         print('Layer Name',l.name)
    #         print('Layer output',l[0].output)
    conv_output = [l for l in model.layers if l.name == layer_name][0].output
    # co = [l for l in model.layers if l.name is layer_name]
    # print(co)
    # conv_output=layer_name
    grads = normalize(_compute_gradients(loss, [conv_output])[0])
    gradient_function = K.function([model.input], [conv_output, grads])

    output, grads_val = gradient_function([image])
    output, grads_val = output[0, :], grads_val[0, :, :, :]

    weights = np.mean(grads_val, axis=(0, 1))
    cam = np.ones(output.shape[0:2], dtype=np.float32)

    for i, w in enumerate(weights):
        cam += w * output[:, :, i]

    scale_w, scale_h = 4, 1
    cam = cv2.resize(cam, (image.shape[2] * scale_w, image.shape[3] * scale_h))
    cam = np.maximum(cam, 0)
    heatmap = cam / np.max(cam)

    # #Return to BGR [0..255] from the preprocessed image
    # image = image[0, :]
    # image -= np.min(image)
    # image = np.minimum(image, 255)

    reshaped_image = image.reshape(image.shape[3], image.shape[2], -1)
    reshaped_image = cv2.resize(reshaped_image,
                                dsize=(image.shape[2] * scale_w,
                                       image.shape[3] * scale_h),
                                interpolation=cv2.INTER_CUBIC)
    reshaped_image = reshaped_image.reshape(image.shape[3] * scale_h,
                                            image.shape[2] * scale_w, -1)

    cam = cv2.applyColorMap(np.uint8(255 * heatmap), cv2.COLORMAP_HOT)
    print(reshaped_image.shape)
    print(cam.shape)
    cam = np.float32(cam) + np.float32(reshaped_image)
    # cam = 255 * cam / np.max(cam)
    return np.uint8(cam), heatmap
示例#4
0
def extract_features(filename):
	model = tensorflow.keras.models.load_model('/Users/rishikoul/PycharmProjects/Vocalize_1.0/model_vgg16_restructured.h5')
	# load the photo
	image = tensorflow.keras.preprocessing.image.load_img(filename, target_size=(224, 224))
	# convert the image pixels to a numpy array
	image = tensorflow.keras.preprocessing.image.img_to_array(image)
	# reshape data for the model
	image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
	# prepare the image for the VGG model
	image = tensorflow.keras.applications.vgg16.preprocess_input(image)
	# get features
	feature = model.predict(image, verbose=0)
	return feature
def image_entree(image, model):
    #files = 'static/uploads/'
    #target = os.path.join(files, requete)
    #print (target)
    #image = load_img(target, target_size=shape)
    # convert the image pixels to a numpy array

    image = img_to_array(image)
    # reshape data for the model
    image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
    # prepare the image for the VGG model
    image = preprocess_input(image)  #fonction importer
    # predict the probability across all output classes
    feature = model.predict(image)
    #feature = np.array(feature[0])
    return feature[0]
def predict(image1):
    model = VGG16()
    image = load_img(image1, target_size=(224, 224))
    # convert the image pixels to a numpy array
    image = img_to_array(image)
    # reshape data for the model
    image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
    # prepare the image for the VGG model
    image = preprocess_input(image)
    # predict the probability across all output classes
    yhat = model.predict(image)
    # convert the probabilities to class labels
    label = decode_predictions(yhat)
    # retrieve the most likely result, e.g. highest probability
    label = label[0][0]
    return label
示例#7
0
  validation_datagen = ImageDataGenerator(
    rescale=1./255,
      horizontal_flip=True,
      rotation_range=2,
      preprocessing_function=preprocessing
      )
  validation_generator = validation_datagen.flow_from_directory(VALIDATION_DIR,
                                                              batch_size=50,
                                                              class_mode='categorical',
                                                              target_size=(100,100),
                                                              shuffle=True,
                                                    color_mode='grayscale')
  validation_generator.shuffle = False
  validation_generator.index_array = None
  model = CNN_model_with_256_neurons(7)
  model.compile(optimizer = 'adam', loss = 'categorical_crossentropy',metrics = ['accuracy'])
  history = model.fit(train_generator,epochs=10,batch_size=50,shuffle=True)
  test_loss,test_acc=model.evaluate(validation_generator)
  sum_acc=sum_acc+test_acc
avg_acc=sum_acc/10
print(avg_acc)

image = cv2.imread('/content/happily-surprised.jpg',0)
cv2_imshow(image)
image = preprocessing(image)
image = np.array(image)
cv2_imshow(image)
image = image.reshape(1,100,100,1)
print('The emotion in the given figure is ' + emotion[np.argmax(model.predict(image))])

示例#8
0
from tensorflow.keras.models import load_model

model.save('Model_Resnet50.hdf5')

y_pred = model.predict(test_set)

y_pred

import numpy as np
y_pred = np.argmax(y_pred, axis=1)

y_pred

from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image

model=load_model('Model_Resnet50.hdf5')

img=image.load_img('/content/drive/MyDrive/cricket/Test/bat/frame15980.jpg',target_size=(224,224))
plt.imshow(img)

image = image.img_to_array(img)

image = image/255.  

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

a=np.argmax(model.predict(image),axis=1)
a