Beispiel #1
0
 def img_to_array(self, img, data_format=None, dtype=None):
     if data_format is None:
         data_format = backend.image_data_format()
     if 'dtype' in generic_utils.getargspec(image.img_to_array).args:
         if dtype is None:
             dtype = backend.floatx()
         return image.img_to_array(img, data_format=data_format, dtype=dtype)
     return image.img_to_array(img, data_format=data_format)
    def predict_one1(self, img_path):

        # assumption that model already loaded

        # Epoch 18/100
        #  - 46s - loss: 0.4270 - acc: 0.8118 - val_loss: 0.4171 - val_acc: 0.8092
        # Epoch 00018: val_loss improved from 0.64311 to 0.41714, saving model to ../../stage/models/default/builds/default-1544411418/default-improvement-18-0.417.hdf5
        # load ../../stage/models/default/builds/default-1544411418/default-improvement-18-0.417.hdf5

        # --> binary
        test_image = image.load_img(img_path, target_size=self.image_shape)
        test_image = image.img_to_array(test_image)
        test_image = np.expand_dims(test_image, axis=0)
        test_image = test_image * 1. / 255

        result = self.model.predict(test_image)
        # TODO: last minute hard-coded labels for imagenet tests
        class_indices = {'drunkard-n10037385': 0, 'not-drunk-n00007846': 1}

        #-- test code
        #print(result)
        #prediction = 'idk'
        #if result[0][0] >= 0.5:
        #    print('not')
        #    prediction = 'Not drunk'
        #else:
        #    print('drunk')
        #    prediciton = 'Drunk'
        #print(prediction)
        #---

        return 'likelyhood of being sober: ' + str(result[0][0])
Beispiel #3
0
    def get(self, resource_id):
        arr = [
            'taj.jpg', 'state.jpg', 'yos.jpg', 'waipio.jpg', 'owens.jpg',
            'sonoma.jpg'
        ]
        model = tf.keras.applications.inception_v3.InceptionV3(
            include_top=True,
            weights='imagenet',
            input_tensor=None,
            input_shape=None,
            pooling=None,
            classes=1000)
        # model = tf.keras.models.load_model('./inception.h5')
        for xi in arr:
            path = os.path.abspath('files/' + xi)
            img = image.load_img(path, target_size=(299, 299))
            x = image.img_to_array(img)
            x = np.expand_dims(x, axis=0)
            x = preprocess_input(x)

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

        return {'images': 'data'}
 def readData(self, path):
     dirs = os.listdir(path)
     dataImgPath = []
     metaData = []
     metaDataLabel = []
     temp = []
     for folder in dirs:
         if not folder.startswith("."):
             subFolder = path + folder
             subFolders = os.listdir(subFolder)
             if folder not in temp:
                 temp.append(folder)
             for img in subFolders:
                 if not img.startswith("."):
                     imgPath = subFolder + '/' + img
                     dataImgPath.append(imgPath)
     #load order will change label order
     temp = sorted(temp, key=int)
     print(temp)
     random.shuffle(dataImgPath)
     for path in dataImgPath:
         img = image.load_img(path)
         img = image.img_to_array(img)
         metaData.append(img)
         label = path.split("/")[2]
         for index in range(0, len(temp)):
             if label == temp[index]:
                 metaDataLabel.append(index)
     return metaData, metaDataLabel
def getImageTensor(image_path='./image.jpg', target_size=(150, 150)):
    img = load_img(image_path, target_size=target_size)
    img_tensor = image.img_to_array(img)
    img_tensor = np.expand_dims(
        img_tensor, axis=0)  # disisipkan searah sumbu x, axis=1 searah sumbu y
    img_tensor /= 255
    return img_tensor
def visualize_predicttion(classifier, n_cases):

  # Loop through images
  for i in range(0,n_cases):

    # Set path for test images
    path = random.choice([test_LR_dir, test_RL_dir])
    #path = 'data/RandomLRR.jpg'

    # Get pictures
    random_img = random.choice(os.listdir(path))
    img_path = os.path.join(path, random_img)
    img = image.load_img(img_path, target_size=(img_width, img_height))
    img_tensor = image.img_to_array(img)    # Image data encoded as integers in the 0-255 range
    img_tensor /= 255.                      # Normalize to [0,1] for matplotlib application

    # Extract feature
    features = conv_base.predict(img_tensor.reshape(1, img_width, img_height, img_channel))

    # Make prediction
    try:
      prediction = classifier.predict(features)
    except:
      prediction = classifier.predict(features.reshape(1, 7*7*512))

    # Show image with prediction
    plt.title(random_img)
    plt.imshow(img_tensor)
    plt.show()

    # Write prediction
    if prediction < 0.5:
      print('LR')
    else:
      print('RL')
Beispiel #7
0
def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            return redirect(request.url)
        if file and allowed_file(file.filename):
            base_path = path.abspath(path.dirname(__file__))
            upload_path = path.join(base_path, 'static/planttest/test/')
            filename = upload_path + secure_filename(file.filename)
            file.save(filename)
            try:
                test_datagen = ImageDataGenerator(rescale=1. / 255)
                img = image.load_img(file, target_size=(224, 224))
                array_img = image.img_to_array(img, dtype='float32')
                test_generator = test_datagen.flow(array_img.reshape(
                    1, 224, 224, 3),
                                                   batch_size=1)
                pred = modelPlant.predict_generator(test_generator)
                result = decode_predictions_ill(pred)
                return json.dumps(result)
            except:
                result = {'error': 'predict error...'}
                return json.dumps(result)
    return render_template('index.html')
 def predict(self, mode, sample_image):
     test_image = image.load_img(sample_image, target_size=(154, 154))
     test_image = image.img_to_array(test_image)
     test_image = np.expand_dims(test_image, axis=0)
     result = self.FruitModel.predict(test_image)
     result = np.argmax(result)
     #k.clear_session()
     return result
def show_pictures(path):
    random_img = random.choice(os.listdir(path))
    img_path = os.path.join(path, random_img)

    img = image.load_img(img_path, target_size=(img_width, img_height))
    img_tensor = image.img_to_array(img)  # Image data encoded as integers in the 0–255 range
    img_tensor /= 255.                    # Normalize to [0,1] for plt.imshow application
    plt.imshow(img_tensor)
    plt.show()
Beispiel #10
0
def get_vector(img_path):
    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)

    result = model.predict(x)
    result[result < 1e-4] = 0
    return result.flatten()
def showImage(image_path='./image.jpg', target_size=(150, 150)):
    img = load_img(image_path, target_size=target_size)
    img_tensor = image.img_to_array(img)
    img_tensor = np.expand_dims(
        img_tensor, axis=0)  # disisipkan searah sumbu x, axis=1 searah sumbu y
    img_tensor /= 255
    plt.imshow(img_tensor[0])
    plt.show()
    plt.close()
def newImage():
    name = input("Name of file: ")
    random_pic = image.load_img(name, target_size=(64, 64))
    random_pic = image.img_to_array(random_pic)
    random_pic = np.expand_dims(random_pic, axis=0)
    result = model.predict(random_pic)
    if result[0][0] >= 0.5:
        print("dog")
    else:
        print("cat")
Beispiel #13
0
def load_image(img_path, show=False):

    img = image.load_img(img_path, target_size=(64, 64))
    img_tensor = image.img_to_array(img)  # (height, width, channels)
    img_tensor = np.expand_dims(
        img_tensor, axis=0
    )  # (1, height, width, channels), add a dimension because the model expects this shape: (batch_size, height, width, channels)
    img_tensor /= 255.  # imshow expects values in the range [0, 1]

    return img_tensor
Beispiel #14
0
def load_image(img_path, show=True):
    img_original = image.load_img(img_path)
    img = image.load_img(img_path, target_size=(64, 64))
    img_tensor = image.img_to_array(img)
    img_tensor = np.expand_dims(img_tensor, axis=0)
    img_tensor /= 255.
    if show:
        plt.imshow(img_original)
        plt.axis('off')
        plt.show()
    return img_tensor
 def inference_label(self, model, img_path, IMSIZE, label):
     img = image.load_img(img_path, target_size=(IMSIZE, IMSIZE))
     x = image.img_to_array(img)
     x = np.expand_dims(x, axis=0)
     x = self.normalization(x)
     predict_result = model.predict(x)
     print(predict_result[0])
     index = np.where(predict_result[0] == np.max(predict_result[0]))
     row_number = index[0][0]
     print(label[row_number])
     print(row_number)
     return row_number
def preprocessing(path, X, y):
    img_list = os.listdir(path)
    for img_name in img_list:
        img_path = path + '/' + img_name
        img = image.load_img(img_path,
                             color_mode="grayscale",
                             target_size=(150, 150))
        img_tensor = image.img_to_array(img)
        X.append(img_tensor)
        if path.split("/")[-1] == "NORMAL":
            y.append([0])
        else:
            y.append([1])
Beispiel #17
0
def predict_image(path, model):
    #  loading image
    img1 = image.load_img(path, target_size=(224, 224))

    #  image convert to array
    img = image.img_to_array(img1)
    img = np.expand_dims(img, axis=0)

    #  preprocessing image
    img = preprocess_input(img)
    pred = model.predict(img)
    print(pred)
    return pred
def predict(filepath):
    #read image
    #img = cv2.imread(filepath)
    #resize image
    #img_resize = cv2.resize(img, (224,224))

    img = image.load_img(filepath, target_size=(224, 224))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    preds = loaded_model.predict(x)
    preds = decode_predictions(preds, top=3)[0]
    os.remove(filepath)
    return preds
 def predict(self, video_name) -> float:
     img = 0
     try:
         img = image.load_img(self.base_path + '/Test_Data_Raw/real/' +
                              video_name + '.jpg',
                              target_size=(480, 270))
     except:
         img = image.load_img(self.base_path + '/Test_Data_Raw/spoof/' +
                              video_name + '.jpg',
                              target_size=(480, 270))
     finally:
         img = image.img_to_array(img)
         img = np.expand_dims(img, axis=0)
         return self.model.predict(img)[0][0]
Beispiel #20
0
def getImagesInArray(train_dataframe):
    images =[]
    labels = []
    # images = list(train_dataframe['Path'].apply(load_img))
    # labels = list(train_dataframe['Label'])
    for i, data in tqdm(train_dataframe.iterrows()):
        img = load_img(data['Path'], target_size=(224, 224))
        x = image.img_to_array(img)
        x = np.expand_dims(x, axis=0)
        x = preprocess_input(x)
        images.append(x)
        labels.append(data['Label'])
    images = np.concatenate(images, axis=0)
    return {'images': images, 'labels': labels}
Beispiel #21
0
def upload(request):
    latest = UploadImage.objects.last()
    # print("Latest Image",latest.predict_image.url)
    # filename=latest.predict_image.url

    # File path
    filename = os.path.join(BASE_DIR + "/" + latest.predict_image.url)
    file_path = os.path.join(BASE_DIR, 'models/modelMultipleClass2.h5')

    #  CNN prediction
    model = load_model(file_path)
    img = image.load_img(filename, target_size=(150, 150))
    img = image.img_to_array(img)
    img = np.expand_dims(img, axis=0)
    result = model.predict(img)
    predicted_class_indices = np.argmax(result, axis=1)

    probabilities = model.predict_proba(img)

    if predicted_class_indices[0] == 0:
        lass_name = "Apple"
        prediction = "Frogeye_Spot"
    elif predicted_class_indices[0] == 1:
        class_name = "Apple"
        prediction = "Healthy"
    elif predicted_class_indices[0] == 2:
        class_name = "Tomato"
        prediction = "Leaf_Mold"
    elif predicted_class_indices[0] == 3:
        class_name = "Tomato"
        prediction = "Healthy"

    form = AddPred(request.POST, request.FILES, instance=latest)

    if form.is_valid():
        updatePred = form.save(commit=False)
        updatePred.prediction = prediction
        updatePred.save()

    form = AddPred(instance=latest)
    # # form.save()

    context_dict = {
        'imagePath': latest,
        'class': class_name,
        'prediction': prediction,
        'form': form,
    }
    return render(request, 'result.html', context_dict)
Beispiel #22
0
def pred_model(imgsrc):
    model = tf.keras.applications.inception_v3.InceptionV3(include_top=True,
                                                           weights='imagenet',
                                                           input_tensor=None,
                                                           input_shape=None,
                                                           pooling=None,
                                                           classes=1000)
    img = image.load_img(imgsrc, target_size=(299, 299))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)

    preds = model.predict(x)
    # print(preds)
    print('Predicted:', decode_predictions(preds, top=5)[0])
Beispiel #23
0
def getPredictLabel(item, paramExtract, imgC):
    objExtract = paramExtract.copy()
    if "http" in str(item) or "https" in str(item):
        url = item
        response = requests.get(url)
        test_image = Image.open(BytesIO(response.content))
    elif not "http" in str(item) or not "https" in str(item):
        photoPath = str(item)
        checKBackSlash = re.search("(\\\\)", photoPath)
        if checKBackSlash == True:
            photoPath = re.sub("(\\\\)", "/", photoPath)

        test_image = Image.open(photoPath)
        img = cv2.imread(photoPath)
        img = cv2.resize(img, (384, 400), 3)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        test_image = Image.fromarray(img)

    test_image = test_image.resize((128, 128))
    test_image = image_utils.img_to_array(test_image) / 255
    test_image = np.expand_dims(test_image, axis=0)

    result = model.predict_proba(test_image)
    verifyColorFromImage = getColorFromImageTest(imgC, objExtract)
    predictedLabel = 'Unknown'

    if result[0][4] > 0.8:
        predictedLabel = 'Pizza'
    elif result[0][0] == np.max(result) and result[0][0] > 0.7:
        predictedLabel = 'Apple'
    elif result[0][2] == np.max(result) and result[0][2] > 0.7:
        predictedLabel = 'French Fries'
    elif verifyColorFromImage[0] < 2 and verifyColorFromImage[
            3] > 95 and result[0][1] > 0.5:
        predictedLabel = 'Banana'
    elif verifyColorFromImage[0] >= 2 and verifyColorFromImage[
            0] <= 60 and verifyColorFromImage[1] > verifyColorFromImage[2]:
        predictedLabel = 'Rice with Dhal'
    elif verifyColorFromImage[0] >= 2 and verifyColorFromImage[
            2] > verifyColorFromImage[1] and verifyColorFromImage[2] > 1:
        predictedLabel = 'Idly'
    elif result[0][6] == np.max(result) and result[0][6] > 0.7:
        predictedLabel = 'Samosa'

    return predictedLabel
Beispiel #24
0
def test_image(path,output):
    test_image = image.load_img(imagePath, target_size = (224, 224))
    test_image = image.img_to_array(test_image)
    test_image = np.expand_dims(test_image, axis = 0)
    result = loaded_model.predict(test_image)

    confidence = ["{:.10f}".format(r) for r in result[0]]
    if output: print("Confidence: ", result)

    if (result[0][0] == result[0][1]):
        if output: print("Thyroid Type: Unknown. Unable to classify this image.")
        return "Unknown", confidence
    elif (np.argmax(result, axis = 1) == 0):
        if output: print("Thyroid Type: Benign")
        return "Benign", confidence
    else:
        if output: print("Thyroid Type: Malignant")
        return "Malignant", confidence
Beispiel #25
0
 def getPredictions(self, model, test_dir):
     # Obtains predictions from a test directory
     count = 0
     imageFormat = '.png'
     fileList = [
         os.path.join(test_dir, f) for f in os.listdir(test_dir)
         if f.endswith(imageFormat)
     ]
     for imagename in fileList:
         img = image.load_img(imagename,
                              target_size=(img_width, img_height),
                              color_mode="grayscale")
         img = image.img_to_array(img)
         img = img / 255
         img = np.expand_dims(img, axis=0)
         classes = model.predict_classes(img)
         count = count + 1
         print(classes)
    def __getitem__(self, index):
        """Generate one batch of data"""
        # selects indices of data for next batch
        indexes = self.indexes[index * self.batch_size:(index + 1) *
                               self.batch_size]

        # select data and load images
        labels = np.array([self.labels[k] for k in indexes])
        images = [
            image.img_to_array(
                image.load_img(self.images_paths[k], target_size=(224, 224)))
            for k in indexes
        ]
        # preprocess and augment data
        if self.augment:
            images = self.augmentor(images)
        images = np.array([preprocess_input(img) for img in images])
        return images, labels
Beispiel #27
0
    def get_ops(self):
        images = []
        ops = []

        for i, j in zip(self.path, self.path_list):

            for k in j:
                img = image.load_img(os.path.join(i, k),
                                     target_size=(299, 299))
                x = image.img_to_array(img)
                #x = np.expand_dims(x, axis = 0)
                x = preprocess_input(x)

                images.append(x)
        print('get_images', np.array(images).shape)
        features = self.model.predict(np.array(images))
        ops.append(np.squeeze(np.array(decode_predictions(features, top=1))))

        return ops
Beispiel #28
0
def classify(img_path, fig=None, rows=1, cols=1, i=1):
    img = image.load_img(img_path,
                         target_size=(img_height, img_width),
                         color_mode="grayscale")

    imgArray = np.expand_dims(image.img_to_array(img), 0)
    datagen.standardize(imgArray)

    predict = model.predict(imgArray)
    predict_classes = model.predict_classes(imgArray)
    result = [classes[i] for i in predict_classes]

    print(
        f'{img_path} --> predict: {predict}  predict_classes: {predict_classes}  class: {result}'
    )

    if fig is not None:
        fig.add_subplot(rows, cols, i, title=result)
        plt.imshow(img, cmap='gray', vmin=0, vmax=255)
def loadImages(start, stop, csvFile):
    """
    Carica le immagini prendendo il nome dal file csv e restituisce il dataset contenente le immagini
    :param start: indice di partenza del csv
    :param stop: indice di fine del csv
    :param csvFile: file csv contenente le labels
    :return: dataset contenente stop-start immagini
    """
    dataset = []

    for i in tqdm(range(start, stop)):
        # print(DATASET_PATH + "/" + csvLabels.loc[i]["image_id"])
        # print(csvFile.loc[i]["image_id"])
        img = image.load_img(DATASET_PATH + "/" + csvFile.loc[i]["image_id"],
                             target_size=IMAGE_DIMS)
        img = image.img_to_array(img)
        img = img / 255
        dataset.append(img)

    return dataset
Beispiel #30
0
    def predict_one3(self, img_path):
        #--- categorical
        # ../../stage/models/insta-cog/builds/insta-cog-1544592705/insta-cog
        # ../../stage/models/insta-cog/split_data/train
        #  - 49s - loss: 0.8492 - acc: 0.6170 - val_loss: 0.8661 - val_acc: 0.6020
        # Epoch 00193: val_loss improved from 0.88596 to 0.86613, saving model to ../../stage/models/insta-cog/builds/insta-cog-1544592705/insta-cog-improvement-193-0.866.hdf5
        #---
        class_list = ['drunkselfie', 'soberselfie', 'stonedselfie']

        test_image = image.load_img(img_path, target_size=self.image_shape)
        test_image = image.img_to_array(test_image)
        test_image = np.expand_dims(test_image, axis=0)
        test_image = test_image * 1. / 255

        predicted_vector = self.model.predict(
            test_image)  #Vector with the prob of each class
        #print(predicted_vector)
        #print(class_list[np.argmax(predicted_vector)]) #Prints ellement with highest prob

        return class_list[0] + ': ' + str(predicted_vector[0][0]) + ', ' \
             + class_list[1] + ': ' + str(predicted_vector[0][1]) + ', ' \
             + class_list[2] + ': ' + str(predicted_vector[0][2])