Пример #1
0
def Example():
    # image_path = args.data_path + '\\20190301074833_Wave1_2019Y03M01D_07h48m33s_3sec_nonhighpass.png'
    image_path = 'D:\\Onepredict_MK\\LG CNS\\20190417_LG_CNS_test_mode\\puppy.jpg'

    resnet = ResNet50(input_shape=(224, 224, 3), weights='imagenet', include_top=True)
    print(resnet.summary())

    activation_layer = resnet.get_layer('activation_48')
    model = Model(inputs=resnet.input, outputs=activation_layer.output)
    final_dense = resnet.get_layer('fc1000')
    weight = final_dense.get_weights()[0]

    img = image.load_img(image_path, target_size=(224, 224))
    img_input = preprocess_input(np.expand_dims(img, 0))
    fmaps = model.predict(img_input)[0]                     # fmaps.shape = (7, 7, 2048)

    probs = resnet.predict(img_input)                       # probs.shape = (1, 1000)
    class_names = decode_predictions(probs)
    class_name = class_names[0][0]
    pred = np.argmax(probs[0])                              # pred = 207

    w = weight[:, pred]                                     # w.shape = (2048,)
    cam = fmaps.dot(w)                                      # cam.shape = (7, 7)
    camp = ndimage.zoom(cam, (32, 32), order=1)

    plt.subplot(1, 2, 1)
    plt.imshow(img, alpha=0.8)
    plt.imshow(camp, cmap='jet', alpha=0.5)

    plt.subplot(1, 2, 2)
    plt.imshow(img)
    plt.title(class_name)
    plt.show()
def predict(img_local_path):
    model = SqueezeNet(weights='imagenet')
    img = image.load_img(img_local_path, target_size=(227, 227))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    preds = model.predict(x)
    result = decode_predictions(preds)
    return result
Пример #3
0
def train(img_path):
    K.clear_session()
    my_model = ResNet50(
        weights='./resnet50_weights_tf_dim_ordering_tf_kernels.h5')
    image_size = 224
    img = load_img(img_path, target_size=(image_size, image_size))
    img_array = np.array([img_to_array(img)])
    inpu = preprocess_input(img_array)
    preds = my_model.predict(inpu)
    deco = decode_predictions(preds)
    return deco
Пример #4
0
"""
@author: 代码医生工作室
@公众号:xiangyuejiqiren   (内有更多优秀文章及学习资料)
@来源: <深度学习之TensorFlow工程化项目实战>配套代码 (700+页)
@配套代码技术支持:bbs.aianaconda.com      (有问必答)
"""

from tensorflow.python.keras.applications.resnet50 import ResNet50
from tensorflow.python.keras.preprocessing import image
from tensorflow.python.keras.applications.resnet50 import preprocess_input, decode_predictions

import numpy as np
#6.7.10节 动态图
#tf.enable_eager_execution()						#启动动态图

model = ResNet50(weights='imagenet')
#model = ResNet50(weights='resnet50_weights_tf_dim_ordering_tf_kernels.h5')


img_path = 'hy.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)

preds = model.predict(x)
print('Predicted:', decode_predictions(preds, top=3)[0])

#6.7.10节 动态图
#preds = model(x)
#print('Predicted:', decode_predictions(preds.numpy(), top=3)[0])
with tf.Session() as sess:  #在session中运行
    sess.run(tf.global_variables_initializer())
    Reslayer = ResNet50(
        weights='resnet50_weights_tf_dim_ordering_tf_kernels.h5')
    logits = Reslayer(tensorimg)  #网络模型

    #Reslayer = ResNet50(weights='resnet50_weights_tf_dim_ordering_tf_kernels.h5',
    #                 input_tensor=tensorimg,input_shape = (224, 224, 3) )
    #logits = Reslayer.layers[-1].output
    #print(logits)

    img_path = './dog.jpg'
    img = image.load_img(img_path, target_size=(224, 224))
    logitsv = sess.run(logits, feed_dict={inputs: img})
    Pred = decode_predictions(logitsv, top=3)[0]
    print('Predicted:', Pred, len(logitsv[0]))

#可视化
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 8))
fig.sca(ax1)
ax1.imshow(img)
fig.sca(ax1)

barlist = ax2.bar(range(3), [i[2] for i in Pred])
barlist[0].set_color('g')

plt.sca(ax2)
plt.ylim([0, 1.1])
#plt.xticks(range(3),[i[1][:15] for i in Pred], rotation='vertical')
fig.subplots_adjust(bottom=0.2)
Пример #6
0
def predictNevaluate(model, target_size, cwd, categ_names, wnids_list):
    '''
    target_size is a tuple of image-dimensions expected from every model
    wnids_list is nested list with url's ending for each category, and the corresponding categ name.
    wnids_list and categ_names must have the same sequnce, and matters to confusion matrix computation.
    categ_names is list of categories. Their sequnce matters to confusion matrix computation.
    Returns a dataframe
    
    '''
# Create Confusion Matrix
    # Create dataframe full of zeros to store confusion matrix
    cm = pd.DataFrame(np.zeros((len(wnids_list)+1, len(wnids_list)+2)))
    # Create column-names for confusion matrix
    cm.columns = categ_names+['Other', 'Precision-Producer-Accur']  # Sorted categories
    # Create row-names for confusion matrix
    cm.index = categ_names+['Recall-User-Reliab']
        
    for i in range(len(wnids_list)):
        img_path = cwd +'/'+ wnids_list[i][0]
        print('\n\nImages from folder {}:'.format(wnids_list[i][0]))
        for root, subfolders, files in os.walk(img_path):
            for file in files:
                # load an image in PIL format
                img = image.load_img(img_path+'/'+file, target_size=target_size)
                x = image.img_to_array(img)
                x = np.expand_dims(x, axis=0)
                x = preprocess_input(x)
                
                preds = model.predict(x)
                # Top three predictions for every image
                imRes = decode_predictions(preds, top=3)[0]
                # decode the results into a list of tuples (class, description, probability)
                print('\nFile {} predicted:\n{}'.format(file, imRes))
                
            # Create confusion matrix
                # If name of predicted category is same as folder. Compare strings
                if imRes[0][1] == wnids_list[i][0]:
                    # Add 1 at value in cell with row same as folder name
                    whichRow = np.where(cm.index == wnids_list[i][0])
                    # and col as predicted-name. [col][row]
                    cm[imRes[0][1]][whichRow[0][0]] += 1
                    print('TRUE\n')
                # If is different from folder but is one of the five categories
                elif (imRes[0][1] in categ_names and imRes[0][1] != wnids_list[i][0]):
                    # Add 1 at value in cell with row same as folder name
                    whichRow = np.where(cm.index == wnids_list[i][0])
                    # and col as predicted-name.
                    cm[imRes[0][1]][whichRow[0][0]] += 1
                    print('FALSE\n')
                # If is none of the five categories
                elif imRes[0][1] not in categ_names:
                    # Add 1 at value in cell with row same as folder name
                    whichRow = np.where(cm.index == wnids_list[i][0])
                    # and column as classified name, here 'Others'.
                    cm['Other'][whichRow[0][0]] += 1
                    print('OTHER\n')
                        
# Compute Acc and Rel in Confusion Matrix
# Rel
    for categ in cm.columns[:-1]:  # For every (column) category (and 'other')
        cm[categ][-1] = sum(cm[categ][:-1])  # Compute Total sum of column and write to last row [col][row]
        if categ != 'Other':  #  Only for real categories, compute Rel and replace value in last row
            # rel = diagonal element / last row element
            rel = (cm[categ][categ_names.index(categ)] / cm[categ][-1])
            # assign rel-value to last row
            cm[categ][-1] = round(rel, 2)
# Acc
    for categ in cm.index[:-1]: # For every (row) category (Here we dont have 'other')
        whichRow = np.where(cm.index == categ) # row is where index == categ name
        rowValues = cm.iloc[whichRow[0][0]][:-1]  # select the whole row
        # Acc = diagonal element / sum of row
        acc = cm[categ][categ_names.index(categ)] / sum(rowValues)
        # assign acc-value to last column 
        cm[cm.columns[-1]][categ_names.index(categ)] = round(acc, 2)
# f1-score
    for categ in cm.index[:-1]: # For every (row) category (Here we dont have 'other')
        # Rel ^-1 (inverse)
        whichRow = np.where(cm.index == 'Recall-User-Reliab') # row is where index == Rel
        relValues = cm.iloc[whichRow[0][0]][:-2]  # select the whole row - rowValues
        invRelValues = [1/x for x in relValues]
        # Acc ^-1 (inverse)
        accValues = cm['Precision-Producer-Accur'][:-1]
        invAccValues = [1/x for x in accValues]
        # f1-score
        f1 = (len(invRelValues)+len(invAccValues)) / (sum(invRelValues)+sum(invAccValues))
        # Assign f1 to bottom right element
        cm.iloc[whichRow[0][0]][-1] = round(f1, 2)
    return cm
from tensorflow.python.keras.preprocessing import image
from tensorflow.python.keras.applications.resnet50 import ResNet50
from tensorflow.python.keras.applications.resnet50 import preprocess_input, decode_predictions

# Step 1: Preprocess data
img = image.load_img("./img/41cqodicvbl.jpg", target_size=(224, 224))

# Convert the image to a numpy array
img = image.img_to_array(img)

# Add a forth dimension since Keras expects a list of images
img = np.expand_dims(img, axis=0)

# Step 2: Load Pre-trained Model
model = ResNet50()

# Scale the input image to the range used in the trained network
img = preprocess_input(img)

# Run the image through the deep neural network to make a prediction
predictions = model.predict(img)

# Look up the names of the predicted classes. Index zero is the results for the first image.
predicted_classes = decode_predictions(predictions, top=3)

print("This is an image of:")

for imagenet_id, name, likelihood in predicted_classes[0]:
    print(" - {}: {:2f} likelihood".format(name, likelihood * 100))
Пример #8
0
#-*-encoding:utf-8-*-
import numpy as np
from tensorflow.python.keras.preprocessing import image
from tensorflow.python.keras.applications import resnet50
import warnings

warnings.filterwarnings("ignore")

img = image.load_img('dog.png')
# print(image.img_to_array(img).shape)
model = resnet50.ResNet50(weights='imagenet')

img = image.load_img('dog.png', target_size=(224, 224))
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)
print(img.shape)

img = resnet50.preprocess_input(img)

#模型预测
pred = model.predict(img)
n = 10
top_n = resnet50.decode_predictions(pred, n)
for i in top_n[0]:
    print(i)
Пример #9
0
# this classifier can be used with a bunch of different models
from tensorflow.python.keras.applications.resnet50 import ResNet50
from tensorflow.python.keras.preprocessing import image
from tensorflow.python.keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np

# ResNet50 keras model  can classify animals,
model = ResNet50()

img_path = '/home/vince/Desktop/honeybadger.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)

preds = model.predict(x)

print(decode_predictions(preds, top=4))