def predict(image_path, model_path, topk=1, gpu=True):
    ''' Predict the class (or classes) of an image using a trained deep            learning model.
    '''
    model, Mapping_class_idx, epochs_old = load_checkpoint(checkpoint_import)
    #device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    if gpu == True:
        device = torch.device("cuda")
    else:
        device = torch.device("cpu")
    model.to(device)
    ####
    Mapping_idx_class = {v: k for k, v in Mapping_class_idx.items()}
    ###
    # Get the image form the file and transform it and covert it to a pytorch tensor of shape [1,3,224,224]
    np_image = torch.from_numpy(functions.process_image(image_path))
    np_image = np_image[:, :, :, None]
    np_image = np.transpose(np_image, [3, 0, 1, 2])
    np_image = np_image.float()
    np.image = np_image.to(device)
    #turn off drop outs
    with torch.no_grad():
        model.eval()
        log_probs = model.forward(np_image.to(device))
        probs = torch.exp(log_probs)
        top_p, top_index = probs.topk(
            topk,
            dim=1)  # gets the top probabilities and the indices of those probs
        top_index = top_index.to("cpu").numpy()
        top_class = [Mapping_idx_class.get(key) for key in top_index[0]
                     ]  # gets the classes based on the indices

    return (top_p.to("cpu").numpy()[0], top_class)
Ejemplo n.º 2
0
def mosaics():
    time_start = time()
    avg_dic = fn.average_pixel_dic(path)
    time_end = time()
    timing = time_end - time_start
    print('average_pixel_dic time:', timing)
    image_arr_working = fn.process_image(imageArray, avg_dic, 100, path)
    new_final_image = Image.fromarray(image_arr_working)
    new_final_image.show()
Ejemplo n.º 3
0
def main():
    # user inputs from command line
    in_arg = get_input_args()
    # load model checkpoint
    model_checkpoint = load_checkpoint(in_arg.checkpoint)
    # load and process unseen image data
    new_image = process_image(in_arg.image_path)
    # predict on unseen image data
    probs, classes = predict(new_image, model_checkpoint, in_arg.topk,
                             in_arg.gpu)
    # get labels
    get_labels(probs, classes, model_checkpoint)
Ejemplo n.º 4
0
def get_results():
    uploaded_image = session.get('uploaded_image', None)
    # alpha = request.form["sliderGlare"]
    inputs = jsonify(request.form).response[0]
    inputs_dict = json.loads(inputs)
    message = inputs_dict

    processed_image, perc_wrinkle = fn.process_image(
        uploaded_image,
        threshold_1=int(inputs_dict.get("background", 20)),
        resize=None,
        alpha=int(inputs_dict.get('alpha', 60)),
        beta=int(inputs_dict.get('beta', 0)))
    message3 = "Percent Wrinkled: %s " % perc_wrinkle

    fn.plot_wrinkle_class(processed_image, uploaded_image)

    im = uploaded_image.split('/')[-1].split('.')[0] + '_wrinkle.png'
    f = os.path.join(app.config['RESULTS_FOLDER'], im)
    return render_template('results.html', display_image=f, message3=message)
Ejemplo n.º 5
0
    topk = args.topk

    with open(args.category_names, 'r') as f:
        cat_to_name = json.load(f)

    # rebuild the model from checkpoint
    model_2, optimizer_2 = functions.load_checkpoint(checkpoint_path)
    print('load finished!')
    #print(model_2)

    # open an image for prediction
    im = Image.open(pre_img_path)
    #plt.imshow(im)
    # process the image to tensor
    im_ts = functions.process_image(im)
    #helper.imshow(im_ts)
    print("finish image process")

    # predict image
    probs, classes, index = functions.predict(im_ts, model_2, topk)
    print(
        f"top {topk:.0f} probabilities are: {list(map(lambda x:round(x, 4), probs)) }"
    )
    print(f"top {topk:.0f} classes are: {classes}")
    print(f"top {topk:.0f} class index are: {index}")

    # get flower name
    classes_name = functions.idx_to_name(index, cat_to_name)
    print(f"top {topk:.0f} class names are: {classes_name}")
pa = parser.parse_args()
checkpoint = pa.checkpoint
device = pa.device
input_image = pa.input_image
top_k = pa.top_k
category_names = pa.category_names

#check input
print("The input variables are:\n", pa)

#LOAD CHECKPOINT
my_model, optimizer = functions.load_checkpoint(checkpoint)
print('\nCheckpoint Loaded')

#PROCESS IMAGE
test = functions.process_image(input_image)
print("\nImage processed")

#depending on cpu/gpu usage
if torch.cuda.is_available() and device == 'gpu':
    device = 'cuda'
    my_model.to(device)

#PREDICT CATEGORY NAME
with open(category_names, 'r') as f:
    cat_to_name = json.load(f)

probs, classes, names = functions.predict(test, my_model, device, top_k,
                                          cat_to_name)
print(
    '\nPredictions made. Here they are, together with their corresponding probability:\n'
parser = argparse.ArgumentParser(
    description='''Make a flower prediction from a PyTorch checkpoint''',
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)

parser.add_argument('image_path',
                    default=None,
                    help='path to image for prediction')
parser.add_argument('checkpoint',
                    default=None,
                    help='path to PyTorch checkpoint for loading a model')
parser.add_argument('--top_k',
                    default=1,
                    type=int,
                    help='return top K most likely classes')
parser.add_argument('--category_names',
                    default=None,
                    help='json file mapping of categories to real names')
parser.add_argument('--gpu', action='store_true', help='predict on a GPU')

# Get the args
args = parser.parse_args()

# Load up a model checkpoint
model, checkpoint = functions.load_checkpoint(args.checkpoint, args.gpu)

# Preprocess a image to be used for the prediction in the model
image = functions.process_image(args.image_path, model)

# Make a prediction
functions.predict(args.image_path, model, args.gpu, args.top_k,
                  args.category_names)
Ejemplo n.º 8
0
import preparser as parser
from functions import process_image, hydrate, cat_to_name

if __name__ == '__main__':
    arg = parser.parser.parse_args()
    print(arg)
    image = process_image(arg.input)
    network = hydrate(arg.checkpoint)
    names = cat_to_name(arg.category_names)
    prediction = network.predict(image, arg.gpu, arg.top_k, names)
    print(prediction)
Ejemplo n.º 9
0
image = results.image_path
top_k = results.topk
gpu_mode = results.gpu
cat_names = results.cat_name_dir
with open(cat_names, 'r') as f:
    cat_to_name = json.load(f)

# Establish model template
pre_tr_model = results.pretrained_model
model = getattr(models,pre_tr_model)(pretrained=True)

# Load model
loaded_model = load_checkpoint(model, save_dir, gpu_mode)

# Preprocess image - assumes jpeg format
processed_image = process_image(image)

if gpu_mode == True:
    processed_image = processed_image.to('cuda')
else:
    pass

# Carry out prediction
probs, classes = predict(processed_image, loaded_model, top_k, gpu_mode)

# Print probabilities and predicted classes
print(probs)
print(classes) 

names = []
for i in classes:
                    dest='top_k',
                    help='The number of predictions returned.')

results = parser.parse_args()

image = results.image_path
gpu_mode = results.gpu
category_names = results.cat_to_name
pretrained_model = results.arch
top_k = results.top_k

with open(category_names, 'r') as f:
    cat_to_name = json.load(f)

model = getattr(models, pretrained_model)(pretrained=True)
model_loaded = load_checkpoint(model, checkpoint_path)

image_processed = process_image(image)

probs, classes = predict(image_processed, model_loaded, top_k)

print(probs)
print(classes)

names = []
for i in classes:
    names += [cat_to_name[i]]
final_percent = round(probs[0] * 100, 4)
print("This flower is predicted to be a {} with a probability of {}% ".format(
    names[0], final_percent))
#Load inputs
inputs = inputs()
print(inputs)

#Assign inputs to variables // Not prompting user for a) saving directory and b) pre-trained model
data_dir = inputs.data_dir
learning_rate = inputs.learning_rate
hidden_layer1 = inputs.hidden_layer1
hidden_layer2 = inputs.hidden_layer2
dropout_prob1 = inputs.dropout_prob1
dropout_prob2 = inputs.dropout_prob2
image_path = inputs.image_path
top_k = inputs.top_k
use_gpu = inputs.gpu

#image processing and predicting

model, optimizer, criterion = load_checkpoint('checkpoint_part2.pth',
                                              hidden_layer1, hidden_layer2,
                                              dropout_prob1, dropout_prob2)

tensor_image = process_image(image_path)

top_probs, top_labels, top_flowers = predict(tensor_image, model, cat_to_name,
                                             top_k)

for i in range(0, top_k):
    print(
        "Likelihood #{}, with probability {:.4%}, is that this flower is a {} that can be seen in folder with label {}"
        .format(i + 1, top_probs[i], top_flowers[i], top_labels[i]))
Ejemplo n.º 12
0
import functions
import torch
import numpy as np
import json
import argparse
import sys

if __name__ == '__main__':
    # Creating parser for training
    Arguments = sys.argv[1:]
    Parser = functions.ArgumentParsers('predict')
    ParsedArguments = Parser.parse_args(Arguments)

    # Processing Image
    ProcessedImage = functions.process_image(ParsedArguments.path_to_image)

    # Loading Model
    LoadedModel = functions.Load(ParsedArguments.checkpoint_path)

    # Predicting
    Probs, Classes = functions.predict(ProcessedImage,
                                       LoadedModel,
                                       topk=ParsedArguments.top_k)

    # Mapping the classes to names
    FlowerNames = []
    if ParsedArguments.category_name != None:
        try:
            with open('cat_to_name.json', 'r') as f:
                cat_to_name = json.load(f)
            for Class in Classes:
Ejemplo n.º 13
0
    st.write(
        "=========================================================================================================="
    )

uploaded_file = st.file_uploader("Choose an image...",
                                 type=["png", "jpg", "jpeg"])
if uploaded_file is not None:
    image = Image.open(uploaded_file)
    st.image(image, caption='Uploaded Image', use_column_width=True)
    st.write("")
    st.write("Classifying...")

    torch_prediction, tf_prediction_1, tf_prediction_2 = f.make_predictions(
        image, torch_model, tf_model_1, tf_model_2)

    torch_label, tf_label_1, tf_label_2 = f.get_label_from_predictions(
        torch_prediction), f.get_label_from_predictions(
            tf_prediction_1), f.get_label_from_predictions(tf_prediction_2)

    st.markdown(f"PyTorch thinks... **{torch_label}**")
    st.markdown(f"Tensorflow mimicing PyTorch thinks... **{tf_label_1}**")
    st.markdown(f"Tensorflow thinks... **{tf_label_2}**")
    st.write("------------")
    st.write("Creating plots....")

    st.write(
        f.plot_comparisons(
            f.process_image(image)[0], torch_prediction, tf_prediction_1,
            tf_prediction_2))