Ejemplo n.º 1
0
def image_pred(image):
    execution_path = os.getcwd()

    prediction = CustomImagePrediction()
    prediction.setModelTypeAsSqueezeNet()
    prediction.setModelPath(
        os.path.join(execution_path, "model_ex-020_acc-0.992188.h5"))
    prediction.setJsonPath(os.path.join(execution_path, "model_class.json"))
    prediction.loadModel(num_objects=2)

    f = io.BytesIO(image)
    predictions, probabilities = prediction.predictImage(f, result_count=2)

    out = ("", 0)
    for eachPrediction, eachProbability in zip(predictions, probabilities):
        print(eachPrediction, " : ", eachProbability)
    if probabilities[0] > 90:
        return predictions[0]
    return predictions[1]
    def loadPrediction(self, prediction_speed='normal', num_objects=10):
        if self.__modelloaded == False:
            if self.__modelType == "":
                raise ValueError(
                    "You must set a valid model type before loading the model."
                )
                if self.__jsonPath == "":
                    raise ValueError(
                        "You must set a valid json path before loading the model."
                    )
            elif self.__modelType == "resnet":
                prediction = CustomImagePrediction()
                prediction.setModelTypeAsResNet()

            elif self.__modelType == "squeezenet":
                prediction = CustomImagePrediction()
                prediction.setModelTypeAsSqueezeNet()

            elif self.__modelType == "densenet":
                prediction = CustomImagePrediction()
                prediction.setModelTypeAsDenseNet()

            elif self.__modelType == "inceptionv3":
                prediction = CustomImagePrediction()
                prediction.setModelTypeAsInceptionV3()

            elif self.__modelType == "vgg":
                prediction = CustomImagePrediction()
                prediction.setModelTypeAsVgg()

            prediction.setModelPath(self.modelPath)
            prediction.setJsonPath(self.__jsonPath)
            prediction.loadModel(prediction_speed, num_objects)
            self.__prediction_collection.append(prediction)
            self.__modelloaded = True
        else:
            raise ValueError(
                "You must set a valid model type before loading the model.")
from imageai.Prediction.Custom import CustomImagePrediction
import os
import argparse

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the input image")

args = vars(ap.parse_args())
execution_path = os.getcwd()
#resnet_model_ex-020_acc-0.651714.h5
prediction = CustomImagePrediction()
prediction.setModelTypeAsSqueezeNet()
prediction.setModelPath(
    os.path.join(execution_path, "CNN_models/model_ex-100_acc-0.817708.h5"))
prediction.setJsonPath(
    os.path.join(execution_path,
                 "ImageAI_Custom_CNN/vehicles/json/model_class.json"))
prediction.loadModel(num_objects=3)

predictions, probabilities = prediction.predictImage(os.path.join(
    execution_path, args["image"]),
                                                     result_count=2)

for eachPrediction, eachProbability in zip(predictions, probabilities):
    if (eachPrediction == "truck"):
        eachPrediction == "car"
    print(eachPrediction, " : ", eachProbability)
class Predict_Image:

    # other model to be trained
    def __init__(self,
                 Threshold=20,
                 modelName="DenseNet",
                 CustomModelName=None,
                 CustomModelJsonFilePath=None):
        global Model_dir_Path, Web_app_dir
        Model_dir_Path = os.path.dirname(os.path.realpath(__file__))
        Web_app_dir = os.path.dirname(os.path.realpath(__file__ + "../../.."))
        self.Threshold = Threshold
        print("Here ....3\n")
        if CustomModelName is None:
            print("Here ....4\n")
            self.prediction = ImagePrediction()
        else:
            self.prediction = CustomImagePrediction()

        if modelName in "ResNet":
            print("Here ....5\n")
            self.prediction.setModelTypeAsResNet()
            if CustomModelName is None:
                self.prediction.setModelPath(
                    Model_dir_Path +
                    "/Models/resnet50_weights_tf_dim_ordering_tf_kernels.h5")
            else:
                self.prediction.setModelPath(Model_dir_Path + "/Models/" +
                                             CustomModelName)
                self.prediction.setJsonPath(Model_dir_Path + "/Models/" +
                                            CustomModelJsonFilePath)

        elif modelName in "SqueezeNet":
            print("Here ....5\n")
            self.prediction.setModelTypeAsSqueezeNet()
            if CustomModelName is None:
                self.prediction.setModelPath(
                    Model_dir_Path +
                    "/Models/squeezenet_weights_tf_dim_ordering_tf_kernels.h5")
            else:
                self.prediction.setModelPath(Model_dir_Path + "/Models/" +
                                             CustomModelName)
                self.prediction.setJsonPath(Model_dir_Path + "/Models/" +
                                            CustomModelJsonFilePath)

        elif modelName in "InceptionV3":
            print("Here ....6\n")
            self.prediction.setModelTypeAsInceptionV3()
            if CustomModelName is None:
                self.prediction.setModelPath(
                    Model_dir_Path +
                    "/Models/inception_v3_weights_tf_dim_ordering_tf_kernels.h5"
                )
            else:
                self.prediction.setModelPath(Model_dir_Path + "/Models/" +
                                             CustomModelName)
                self.prediction.setJsonPath(Model_dir_Path + "/Models/" +
                                            CustomModelJsonFilePath)

        elif modelName in "DenseNet":
            print("Here ....7\n")
            self.prediction.setModelTypeAsDenseNet()
            if CustomModelName is None:
                print("Here ....7.3\n")
                print("value of Model Dir is" + Model_dir_Path +
                      "/Models/DenseNet-BC-121-32.h5" + "\n")
                self.prediction.setModelPath(Model_dir_Path +
                                             "/Models/DenseNet-BC-121-32.h5")
            else:
                print("Here ....8\n")
                self.prediction.setModelPath(Model_dir_Path + "/Models/" +
                                             CustomModelName)
                self.prediction.setJsonPath(Model_dir_Path + "/Models/" +
                                            CustomModelJsonFilePath)
        self.prediction.loadModel()

    def get_classes_from_image(self, url):
        save_Image = ImageSave()
        self.name = os.path.basename(url)

        if "local://" in url:
            pass
        else:
            save_Image.save_Image_from_url(url, self.name)

        predictions, probabilities = self.prediction.predictImage(
            Web_app_dir + "/static/images/retrieved_images/" + self.name,
            result_count=10)
        result_set = []
        for eachPrediction, eachProbability in zip(predictions, probabilities):
            if eachProbability > self.Threshold:
                result_set.append({
                    'Entity': eachPrediction,
                    'confidence': round(eachProbability, 2)
                })
                print(eachPrediction, eachProbability)
        return result_set

    def setModel(self, modelName):
        if modelName in "ResNet":
            self.prediction.setModelTypeAsResNet()
            self.prediction.setModelPath(
                Model_dir_Path +
                "/Models/resnet50_weights_tf_dim_ordering_tf_kernels.h5")
        elif modelName in "SqueezeNet":
            self.prediction.setModelTypeAsSqueezeNet()
            self.prediction.setModelPath(
                Model_dir_Path +
                "/Models/squeezenet_weights_tf_dim_ordering_tf_kernels.h5")

        elif modelName in "InceptionV3":
            self.prediction.setModelTypeAsInceptionV3()
            self.prediction.setModelPath(
                Model_dir_Path +
                "/Models/inception_v3_weights_tf_dim_ordering_tf_kernels.h5")
        elif modelName in "DenseNet":
            self.prediction.setModelTypeAsDenseNet()
            self.prediction.setModelPath(Model_dir_Path +
                                         "/Models/DenseNet-BC-121-32.h5")
        self.prediction.loadModel()