Esempio n. 1
0
 def Standard(path, size):
     img = image.load_img(path, target_size=(size, size))
     x = image.img_to_array(img)
     x /= 255.0
     x -= 0.5
     x *= 2.0
     return x
Esempio n. 2
0
def show_image(path):
    """Print an image to the notebook

    #Arguments
     path: location of image
    """
    show_array(img_to_array(load_img(path)))
Esempio n. 3
0
def load_img_array(fname, grayscale=False, target_size=None, data_format='channels_last'):
    """Loads and image file and returns an array."""
    img = load_img(fname,
                   grayscale=grayscale,
                   target_size=target_size)
    x = img_to_array(img, data_format=data_format)
    return x
Esempio n. 4
0
 def ZeroCenter(path, size, BGRTranspose=False):
     img = image.load_img(path, target_size=(size, size))
     x = image.img_to_array(img)
     if BGRTranspose == True:
         x = x[..., ::-1]
     x[..., 0] -= 103.939
     x[..., 1] -= 116.779
     x[..., 2] -= 123.68
     return x
Esempio n. 5
0
def Run(self, img_path, model_name):

    # config variables
    weights = 'imagenet'
    include_top = 0
    train_path = 'jpg'
    classfier_file = 'output/flowers_17/' + model_name + '/classifier.cpickle'

    # create the pretrained models
    # check for pretrained weight usage or not
    # check for top layers to be included or not
    if model_name == "vgg16":
        from vgg16 import VGG16, preprocess_input
        base_model = VGG16(weights=weights)
        model = Model(inputs=base_model.input,
                      outputs=base_model.get_layer('fc1').output)
        image_size = (224, 224)
    elif model_name == "vgg19":
        from vgg19 import VGG19, preprocess_input
        base_model = VGG19(weights=weights)
        model = Model(inputs=base_model.input,
                      outputs=base_model.get_layer('fc1').output)
        image_size = (224, 224)
    elif model_name == "resnet50":
        from resnet50 import ResNet50, preprocess_input
        base_model = ResNet50(weights=weights)
        model = Model(inputs=base_model.input,
                      outputs=base_model.get_layer('avg_pool').output)
        image_size = (224, 224)
    elif model_name == "inceptionv3":
        from inception_v3 import InceptionV3, preprocess_input
        base_model = InceptionV3(weights=weights)
        model = Model(inputs=base_model.input,
                      outputs=base_model.get_layer('mixed9').output)
        image_size = (299, 299)
    elif model_name == "xception":
        from xception import Xception, preprocess_input
        base_model = Xception(weights=weights)
        model = Model(inputs=base_model.input,
                      outputs=base_model.get_layer('avg_pool').output)
        image_size = (299, 299)
    else:
        base_model = None

    img = image.load_img(img_path, target_size=image_size)
    img_array = image.img_to_array(img)
    img_array = np.expand_dims(img_array, axis=0)
    img_array = preprocess_input(img_array)
    feature = model.predict(img_array)
    feature = feature.flatten()
    with open(classfier_file, 'rb') as f:
        model2 = pickle.load(f)

    pred = model2.predict(feature)
    prob = model2.predict_proba(np.atleast_2d(feature))[0]

    return pred, prob[0]
def detect():
    if request.method == "GET":
        return render_template("object.html")

    if request.method == "POST":
        path = request.form["path"]
        img = image.load_img(path, target_size=(299, 299))

        xy = image.img_to_array(img)
        xy = np.expand_dims(xy, axis=0)
        xy = preprocess_input(xy)

        preds = model.predict(xy)
        preds = decode_predictions(preds, top=3)[0]
        acc = []
        classes = []
        for x in preds:
            acc.append(x[2])
            classes.append(x[1])
        return render_template("object.html",
                               preds=acc,
                               classes=json.dumps(classes),
                               img=path)
def infer_mode(data):
    class_indices = pickle.load(open(CLASS_INDEX_FILE, 'rb'))
    img = image.load_img(data, target_size=IMG_TGT_SIZE)
    inp_data = image.img_to_array(img)
    inp_data = np.expand_dims(inp_data, axis=0)
    model = False
    result = -1
    if os.path.isfile(MODEL_SAVE_FILE):
        model = load_model(MODEL_SAVE_FILE)
    elif os.path.isfile(MODEL_CKPT_FILE):
        model = load_model(MODEL_CKPT_FILE)

    if model:
        predictions = model.predict(inp_data, verbose=1)
        prediction = predictions[0]
        logging.info("Prediction: %s", prediction)
        for classname in class_indices:
            logging.info("Prediction that sample is an '%s': %g", classname,
                         prediction[class_indices[classname]])
        result = prediction
    else:
        logging.error("Error: cannot load tranied model")

    return result
Esempio n. 8
0
model = InceptionV3(weights='imagenet')
for i in range(0, 5000):
    for j in range(0, 5000):
        print("Here-1")
        all_users = db.child("User").get()
        #print("Here-2")
        #user = db.child("User").get()
        try:
            #print(user.val())
            for user in all_users.each():
                key = user.key()
                img_from_firebase = str(user.val())
                imgByte = img_from_firebase.encode()
                with open('D:\\abcd.png', 'wb') as fh:
                    fh.write(base64.decodebytes(imgByte))
                img = image.load_img('D:\\abcd.png', target_size=(299, 299))
                print("Here7")
                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=5)[0])
                resList = decode_predictions(preds, top=5)[0]

                resNewList = []

                for tmpTup in resList:
                    tmpTup = tmpTup[1]
                    resNewList.append((tmpTup))
                db.child("Result").child(key).set(str(resNewList))
Esempio n. 9
0
 def Identity(path, size):
     img = image.load_img(path, target_size=(size, size))
     x = image.img_to_array(img)
     return x
Esempio n. 10
0
    labels.append(21)

# In[5]:

# encode the labels using LabelEncoder
targetNames = np.unique(labels)
le = LabelEncoder()
le_labels = le.fit_transform(labels)

# In[11]:

# loop over all the labels in the folder
for label in train_labels:
    cur_path = train_path + "/" + label
    for image_path in glob.glob(cur_path):
        img = image.load_img(image_path, target_size=image_size)
        x = image.img_to_array(img)
        x = np.expand_dims(x, axis=0)
        x = preprocess_input(x)
        print(label + " complete")
        sys.stdout.flush()
        feature = model.predict(x)
        flat = feature.flatten()
        features.append(flat)

for img_file in enchinacea_imgfiles:
    img = image.load_img(img_file, target_size=image_size)
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    print(img_file + " complete")
Esempio n. 11
0
            if include_top:
                maxpool = model.get_layer(name='avg_pool')
                shape = maxpool.output_shape[1:]
                dense = model.get_layer(name='fc1000')
                layer_utils.convert_dense_weights_data_format(
                    dense, shape, 'channels_first')

            if K.backend() == 'tensorflow':
                warnings.warn('You are using the TensorFlow backend, yet you '
                              'are using the Theano '
                              'image data format convention '
                              '(`image_data_format="channels_first"`). '
                              'For best performance, set '
                              '`image_data_format="channels_last"` in '
                              'your Keras config '
                              'at ~/.keras/keras.json.')
    return model


if __name__ == '__main__':
    model = ResNet50(include_top=True, weights='imagenet')

    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)
    print('Input image shape:', x.shape)

    preds = model.predict(x)
    print('Predicted:', decode_predictions(preds))
def plots_idx(img_dir, filenames, idx, titles=None):
    plots([image.load_img(img_dir + filenames[i]) for i in idx], titles=titles)