def tensorflow_test(): pb_file = "DenseNet169.pb" with tf.Session() as sess: with gfile.FastGFile(pb_file, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) x_tensor, y_tensor = tf.import_graph_def( graph_def=graph_def, name="", return_elements=[u"input_1:0", u"fc1000/Softmax:0"]) img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) for i in range(warm_up): y = sess.run(y_tensor, feed_dict={x_tensor: x}) t0 = time.time() for i in range(step): y = sess.run(y_tensor, feed_dict={x_tensor: x}) t1 = time.time() print "y.shape = ", y.shape print('Predicted:', decode_predictions(y, top=3)[0]) print "tensorflow time repeat {}: {}".format(step, t1 - t0) exit()
def predict(): # initialize the data dictionary that will be returned from the # view data = {"success": False} # ensure an image was properly uploaded to our endpoint if flask.request.method == "POST": if flask.request.files.get("image"): # read the image in PIL format image = flask.request.files["image"].read() image = Image.open(io.BytesIO(image)) # preprocess the image and prepare it for classification image = prepare_image(image, target=(224, 224)) # classify the input image and then initialize the list # of predictions to return to the client preds = model.predict(image) results = decode_predictions(preds) data["predictions"] = [] # loop over the results and add them to the list of # returned predictions for (imagenetID, label, prob) in results[0]: r = {"label": label, "probability": float(prob)} data["predictions"].append(r) # indicate that the request was a success data["success"] = True # return the data dictionary as a JSON response return flask.jsonify(data)
def predict(image): model = DenseNet201() pred = model.predict(image) decoded_predictions = decode_predictions(pred, top=10) response = 'DenseNet201 predictions: ' + str(decoded_predictions[0][0:5]) print(response) np.argmax(pred[0]) return response
def image_text_similarity_extraction(model, im_path): similarity_feature_dict = {} embedding_vector = embedding_load( '../data/GoogleNews_vectors_negative_300d.txt') data_file = open('../data/gossipcop_news_data.txt', 'r', encoding='utf8') not_read_images = [] for news in data_file.readlines(): similarity_values = [] print(news) news_id = news.split('\t')[0] title = news.split('\t')[1].replace('\n', '').strip() title_embedding = text_embedding(title, embedding_vector) print("title", title) im_list = news.split('\t')[-1].replace('\n', '').strip().split(' ') for im in im_list: try: img = image.load_img(im_path + im, target_size=(224, 224)) except: not_read_images.append(im) continue x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) yhat = model.predict(x) print(im) labels = decode_predictions(yhat, top=10) print(labels) words = '' for label in labels[0]: word = label[1] #print(word) words = words + word.replace('_', ' ') + ' ' tags_embedding = text_embedding(words, embedding_vector) text_im_similarity = cosine(title_embedding, tags_embedding) similarity_values.append(text_im_similarity) if len(similarity_values) == 1: similarity_values.extend([0, 0, 0, 0]) elif len(similarity_values) == 2: similarity_values.extend([0, 0, 0]) elif len(similarity_values) == 3: similarity_values.extend([0, 0]) elif len(similarity_values) == 4: similarity_values.extend([0]) elif len(similarity_values) == 5: print(similarity_values) elif len(similarity_values) > 5: similarity_values = similarity_values[:5] else: continue similarity_feature_dict[news_id] = similarity_values np.save('gossipcop_image_text_similarity_feature.npy', similarity_feature_dict)
def upload(): if request.method == 'POST': # Get the file from post request f = request.files['file'] # Save the file to ./uploads basepath = os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads', secure_filename(f.filename)) f.save(file_path) # Make prediction preds = model_predict(file_path, model) pred_class = decode_predictions(preds, top=5) # ImageNet Decode result = str(pred_class[0][0][1]) # Convert to string return 'The model DenseNet121 predicts this image as : ' + result return None
def upload(): if request.method == 'POST': # Get the file from post request f = request.files['file'] # Save the file to ./uploads basepath = os.path.dirname(__file__) file_path = os.path.join( basepath, 'uploads', secure_filename(f.filename)) f.save(file_path) # Make prediction preds = model_predict(file_path, model) # Process your result for human # pred_class = preds.argmax(axis=-1) # Simple argmax pred_class = decode_predictions(preds, top=5) # ImageNet Decode result = str(pred_class[0][0][1]) # Convert to string return result return None
def tensorrt_test(): img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) x = np.transpose(x, (0, 3, 1, 2)) batch_x = np.tile(x, (trt_batch_size, 1, 1, 1)) with build_engine("DenseNet169.uff") as engine: inputs, outputs, bindings, stream = common.allocate_buffers(engine) with engine.create_execution_context() as context: # np.copyto(inputs[0].host, x.ravel()) np.copyto(inputs[0].host, batch_x.ravel()) [output] = common.do_inference(context, bindings=bindings, inputs=inputs, outputs=outputs, stream=stream, batch_size=trt_batch_size) for i in range(warm_up): [output] = common.do_inference(context, bindings=bindings, inputs=inputs, outputs=outputs, stream=stream, batch_size=trt_batch_size) t0 = time.time() for i in range(step): [output] = common.do_inference(context, bindings=bindings, inputs=inputs, outputs=outputs, stream=stream, batch_size=trt_batch_size) t1 = time.time() print 'Predicted:', decode_predictions(output.reshape( trt_batch_size, 1000), top=3) print "tensorrt time repeat {}: {}".format(step, t1 - t0)
def keras_test(): # model = DenseNet169(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None,classes=1000) # plot_model(model, show_shapes=True, to_file='DenseNet169.png') # model.save("DenseNet169.h5") model = load_model("DenseNet169.h5") img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) for i in range(warm_up): preds = model.predict(x) t0 = time.time() for i in range(step): preds = model.predict(x) t1 = time.time() # 将结果解码为元组列表 (class, description, probability) # (一个列表代表批次中的一个样本) print('Predicted:', decode_predictions(preds, top=3)[0]) print "keras time repeat {}: {}".format(step, t1 - t0)
from keras.applications.densenet import DenseNet201 from keras.preprocessing import image from keras.applications.densenet import preprocess_input, decode_predictions import numpy as np import os import sys data_dir = sys.argv[1] model = DenseNet201(weights='imagenet') for filename in os.listdir(data_dir): imgfile = data_dir + '/' + filename img = image.load_img(imgfile, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) print(filename + ' --- ' + str(decode_predictions(preds, top=5)[0]))
iteration_size = 1000 global_iterations = 0 # Run boundary attack to generate an adversarial example adversarial = attack(cat_img, label=cat_label, unpack=False, iterations=iteration_size, starting_point=dog_img, log_every_n_steps=10, verbose=True) global_iterations += iteration_size np.save('adversarial_image_{0}'.format(global_iterations), adversarial.image) for i in range(10): adversarial = attack(adversarial, unpack=False, iterations=iteration_size, verbose=True) global_iterations += iteration_size np.save('adversarial_image_{0}'.format(global_iterations), adversarial.image) # show results print(np.argmax(fmodel.predictions(adversarial.image))) print( fmodel.predictions(foolbox.utils.softmax( adversarial.image))[dog_label]) preds = kmodel.predict(adversarial.image.copy()) print("Top 5 predictions (adversarial: ", decode_predictions(preds, top=5))
# -*- coding: utf-8 -*- """ Version: 2019/07/11 Author: wangyi Desc: DenseNet169,官方的案例 """ from keras.applications.densenet import DenseNet169 from keras.preprocessing import image from keras.applications.densenet import preprocess_input, decode_predictions import numpy as np model = DenseNet169(weights='imagenet') img_path = 'elephant.jpg' # 模型的默认输入尺寸是224x224 img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) # 将结果解码为元组列表 (class, description, probability) # (一个列表代表批次中的一个样本) print('Predicted:', decode_predictions(preds, top=3)[0]) # Predicted: [(u'n02504013', u'Indian_elephant', 0.82658225), (u'n01871265', u'tusker', 0.1122357), (u'n02504458', u'African_elephant', 0.061040461)]
_iter = 1 """ Main """ if __name__ == '__main__': # load the model model = DenseNet201() # load an image from file image = load_img('mug.jpg', 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 for i in range(_iter): raw_input('{} iteration, press any key to perform...'.format(str(i))) yhat = model.predict(image) # return if not iter if not _iter: exit() # convert the probabilities to class labels label = decode_predictions(yhat) # retrieve the most likely result, e.g. highest probability label = label[0][0] # print the classification print('%s (%.2f%%)' % (label[1], label[2] * 100)) # done.
if __name__ == "__main__": if sys.argv[2] == 'summary': model.summary() exit(0) img_path = sys.argv[2] #img = image.load_img(img_path, target_size=(299, 299)) img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) print('Input image shape:', x.shape) preds = model.predict(x) print(decode_predictions(preds)) ######################################### print('--> Starting evalutation...') from keras.preprocessing.image import ImageDataGenerator from keras import metrics def in_top_k(y_true, y_pred): return metrics.top_k_categorical_accuracy(y_true, y_pred, k=5) val_datagen = ImageDataGenerator(preprocessing_function=preprocess_input) validation_generator = val_datagen.flow_from_directory( './imagenet-data/validation', target_size=(224, 224), #target_size=(299, 299), batch_size=10,
import numpy as np import os from collections import Counter from keras.applications.densenet import DenseNet121, preprocess_input, decode_predictions from keras.preprocessing.image import load_img, img_to_array if __name__ == "__main__": img_dir = "data/val/bees" images = [os.path.join(img_dir, name) for name in os.listdir(img_dir)] model = DenseNet121() img = [ img_to_array(load_img(name, target_size=(224, 224))) for name in images ] batch = np.stack(img, axis=0) batch = preprocess_input(batch) preds = model.predict(batch) result = decode_predictions(preds, top=1) print(Counter([x[0][1] for x in result]))
# pred_pos = base_model.predict(x_pos) # print("Un-poisoned image: {}".format(decode_predictions(pred, top=3)[0])) # print("Advserial image: {}".format(decode_predictions(pred_pos,top=3)[0])) ======= img_orginal = image.load_img(img_path) img = image.load_img(img_path, target_size=(224, 224)) x_org = image.img_to_array(img_orginal) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) pred = base_model.predict(x) x_pos = fast_signed_gradient(x, rand_other(pred)) x_pos = x_pos + x # x_pos = original_img_peturb(x_org,x_pos) # plt.imshow(x_org[:,:,::-1]) # plt.show() # plt.imshow(x_pos[:,:,::-1]) # plt.show() x_pos = preprocess_input(x_pos) pred_pos = base_model.predict(x_pos) print("Un-poisoned image: {}".format(decode_predictions(pred, top=3)[0])) print("Advserial image: {}".format(decode_predictions(pred_pos,top=3)[0])) >>>>>>> 77e389c18419f8d798c8a5ba1cda51450f3d6aac
def predict(bytes): image_data = read_and_prep_image(bytes) with graph.as_default(): preds = model.predict(image_data) return decode_predictions(preds, top=1)[0]
from keras.applications.densenet import DenseNet201 from keras.preprocessing import image from keras.applications.densenet import preprocess_input, decode_predictions from PIL import Image import numpy as np import os import time model = DenseNet201(weights='imagenet') images = os.listdir('resources') times = [] for img_path in images: img = image.load_img('resources/' + img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) start_time = time.time() preds = model.predict(x) times.append(time.time() - start_time) # decode the results into a list of tuples (class, description, probability) # (one such list for each sample in the batch) print('Predicted for ' + img_path + ": ", decode_predictions(preds, top=3)[0]) print("Average prediction time: %s seconds" % np.mean(times))
if ok: from skimage.transform import resize import numpy ximg224 = resize(ximg / 255, (224, 224, 3), anti_aliasing=True) ximg = ximg224[numpy.newaxis, :, :, :] ximg = ximg.astype(numpy.float32) print("new shape:", ximg.shape) ################################## # Let's compute the output. if ok: input_name = sess.get_inputs()[0].name res = sess.run(None, {input_name: ximg}) prob = res[0] print(prob.ravel()[:10]) # Too big to be displayed. ################################## # Let's get more comprehensive results. if ok: from keras.applications.densenet import decode_predictions decoded = decode_predictions(prob) import pandas df = pandas.DataFrame(decoded[0], columns=["class_id", "name", "P"]) print(df)
# -*- coding: utf-8 -*- """ Created on Sun Sep 29 16:43:43 2019 @author: Jianmu """ from keras.applications.densenet import DenseNet121, preprocess_input, decode_predictions from keras.preprocessing.image import load_img,img_to_array import numpy as np #%% model = DenseNet121() print(model.summary()) #%% target_size=(224,224) img_path = "C:/Users/14534/Desktop/5.jpg" image = load_img(img_path, target_size=target_size) image_data = img_to_array(image) #image_data = image_data.reshape((1,) + image_data.shape) image_data = np.expand_dims(image_data, axis=0) print(image_data.shape) image_data = preprocess_input(image_data) #%% prediction = model.predict(image_data) results = decode_predictions(prediction,top=3) print(results)