Example #1
0
    def predictMultipleImages(self,
                              sent_images_array,
                              result_count_per_image=2,
                              input_type="file"):
        """
                'predictMultipleImages()' function is used to predict more than one image by receiving the following arguments:
                    * input_type , the type of inputs contained in the parsed array. Acceptable values are "file", "array" and "stream"
                    * sent_images_array , an array of image file paths, image numpy array or image file stream
                    * result_count_per_image (optionally) , the number of predictions to be sent per image, which must be whole numbers between
                        1 and 1000. The default is 2.

                This function returns an array of dictionaries, with each dictionary containing 2 arrays namely 'prediction_results' and 'prediction_probabilities'. The 'prediction_results'
                contains possible objects classes arranged in descending of their percentage probabilities. The 'prediction_probabilities'
                contains the percentage probability of each object class. The position of each object class in the 'prediction_results'
                array corresponds with the positions of the percentage possibilities in the 'prediction_probabilities' array.


                :param input_type:
                :param sent_images_array:
                :param result_count_per_image:
                :return output_array:
                """

        output_array = []

        for image_input in sent_images_array:

            prediction_results = []
            prediction_probabilities = []
            if (self.__modelLoaded == False):
                raise ValueError(
                    "You must call the loadModel() function before making predictions."
                )

            else:

                if (self.__modelType == "squeezenet"):

                    from .imagenet_utils import preprocess_input, decode_predictions
                    if (input_type == "file"):
                        try:
                            image_to_predict = image.load_img(
                                image_input,
                                target_size=(self.__input_image_size,
                                             self.__input_image_size))
                            image_to_predict = image.img_to_array(
                                image_to_predict, data_format="channels_last")
                            image_to_predict = np.expand_dims(image_to_predict,
                                                              axis=0)

                            image_to_predict = preprocess_input(
                                image_to_predict)
                        except:
                            raise ValueError(
                                "You have set a path to an invalid image file."
                            )
                    elif (input_type == "array"):
                        try:
                            image_input = Image.fromarray(
                                np.uint8(image_input))
                            image_input = image_input.resize(
                                (self.__input_image_size,
                                 self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict,
                                                          dtype=np.float64)
                            image_to_predict = preprocess_input(
                                image_to_predict)
                        except:
                            raise ValueError(
                                "You have parsed in a wrong numpy array for the image"
                            )
                    elif (input_type == "stream"):
                        try:
                            image_input = Image.open(image_input)
                            image_input = image_input.resize(
                                (self.__input_image_size,
                                 self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict,
                                                          dtype=np.float64)
                            image_to_predict = preprocess_input(
                                image_to_predict)
                        except:
                            raise ValueError(
                                "You have parsed in a wrong stream for the image"
                            )

                    model = self.__model_collection[0]

                    prediction = model.predict(image_to_predict, steps=1)

                    try:
                        predictiondata = decode_predictions(
                            prediction, top=int(result_count_per_image))

                        for results in predictiondata:
                            countdown = 0
                            for result in results:
                                countdown += 1
                                prediction_results.append(str(result[1]))
                                prediction_probabilities.append(result[2] *
                                                                100)
                    except:
                        raise ValueError("An error occured! Try again.")

                    each_image_details = {}
                    each_image_details["predictions"] = prediction_results
                    each_image_details[
                        "percentage_probabilities"] = prediction_probabilities
                    output_array.append(each_image_details)

                elif (self.__modelType == "resnet"):

                    model = self.__model_collection[0]

                    from .imagenet_utils import preprocess_input, decode_predictions
                    if (input_type == "file"):
                        try:
                            image_to_predict = image.load_img(
                                image_input,
                                target_size=(self.__input_image_size,
                                             self.__input_image_size))
                            image_to_predict = image.img_to_array(
                                image_to_predict, data_format="channels_last")
                            image_to_predict = np.expand_dims(image_to_predict,
                                                              axis=0)

                            image_to_predict = preprocess_input(
                                image_to_predict)
                        except:
                            raise ValueError(
                                "You have set a path to an invalid image file."
                            )
                    elif (input_type == "array"):
                        try:
                            image_input = Image.fromarray(
                                np.uint8(image_input))
                            image_input = image_input.resize(
                                (self.__input_image_size,
                                 self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict,
                                                          dtype=np.float64)
                            image_to_predict = preprocess_input(
                                image_to_predict)
                        except:
                            raise ValueError(
                                "You have parsed in a wrong numpy array for the image"
                            )
                    elif (input_type == "stream"):
                        try:
                            image_input = Image.open(image_input)
                            image_input = image_input.resize(
                                (self.__input_image_size,
                                 self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict,
                                                          dtype=np.float64)
                            image_to_predict = preprocess_input(
                                image_to_predict)
                        except:
                            raise ValueError(
                                "You have parsed in a wrong stream for the image"
                            )

                    prediction = model.predict(x=image_to_predict, steps=1)

                    try:
                        predictiondata = decode_predictions(
                            prediction, top=int(result_count_per_image))

                        for results in predictiondata:
                            countdown = 0
                            for result in results:
                                countdown += 1
                                prediction_results.append(str(result[1]))
                                prediction_probabilities.append(result[2] *
                                                                100)
                    except:
                        raise ValueError("An error occured! Try again.")

                    each_image_details = {}
                    each_image_details["predictions"] = prediction_results
                    each_image_details[
                        "percentage_probabilities"] = prediction_probabilities
                    output_array.append(each_image_details)

                elif (self.__modelType == "densenet"):

                    model = self.__model_collection[0]

                    from .DenseNet.densenet import preprocess_input, decode_predictions
                    from .DenseNet.densenet import DenseNetImageNet121
                    if (input_type == "file"):
                        try:
                            image_to_predict = image.load_img(
                                image_input,
                                target_size=(self.__input_image_size,
                                             self.__input_image_size))
                            image_to_predict = image.img_to_array(
                                image_to_predict, data_format="channels_last")
                            image_to_predict = np.expand_dims(image_to_predict,
                                                              axis=0)

                            image_to_predict = preprocess_input(
                                image_to_predict)
                        except:
                            raise ValueError(
                                "You have set a path to an invalid image file."
                            )
                    elif (input_type == "array"):
                        try:
                            image_input = Image.fromarray(
                                np.uint8(image_input))
                            image_input = image_input.resize(
                                (self.__input_image_size,
                                 self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict,
                                                          dtype=np.float64)
                            image_to_predict = preprocess_input(
                                image_to_predict)
                        except:
                            raise ValueError(
                                "You have parsed in a wrong numpy array for the image"
                            )
                    elif (input_type == "stream"):
                        try:
                            image_input = Image.open(image_input)
                            image_input = image_input.resize(
                                (self.__input_image_size,
                                 self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict,
                                                          dtype=np.float64)
                            image_to_predict = preprocess_input(
                                image_to_predict)
                        except:
                            raise ValueError(
                                "You have parsed in a wrong stream for the image"
                            )

                    prediction = model.predict(x=image_to_predict, steps=1)

                    try:
                        predictiondata = decode_predictions(
                            prediction, top=int(result_count_per_image))

                        for results in predictiondata:
                            countdown = 0
                            for result in results:
                                countdown += 1
                                prediction_results.append(str(result[1]))
                                prediction_probabilities.append(result[2] *
                                                                100)
                    except:
                        raise ValueError("An error occured! Try again.")

                    each_image_details = {}
                    each_image_details["predictions"] = prediction_results
                    each_image_details[
                        "percentage_probabilities"] = prediction_probabilities
                    output_array.append(each_image_details)

                elif (self.__modelType == "inceptionv3"):

                    model = self.__model_collection[0]

                    from imageai.Prediction.InceptionV3.inceptionv3 import InceptionV3, preprocess_input, \
                        decode_predictions

                    if (input_type == "file"):
                        try:
                            image_to_predict = image.load_img(
                                image_input,
                                target_size=(self.__input_image_size,
                                             self.__input_image_size))
                            image_to_predict = image.img_to_array(
                                image_to_predict, data_format="channels_last")
                            image_to_predict = np.expand_dims(image_to_predict,
                                                              axis=0)

                            image_to_predict = preprocess_input(
                                image_to_predict)
                        except:
                            raise ValueError(
                                "You have set a path to an invalid image file."
                            )
                    elif (input_type == "array"):
                        try:
                            image_input = Image.fromarray(
                                np.uint8(image_input))
                            image_input = image_input.resize(
                                (self.__input_image_size,
                                 self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict,
                                                          dtype=np.float64)
                            image_to_predict = preprocess_input(
                                image_to_predict)
                        except:
                            raise ValueError(
                                "You have parsed in a wrong numpy array for the image"
                            )
                    elif (input_type == "stream"):
                        try:
                            image_input = Image.open(image_input)
                            image_input = image_input.resize(
                                (self.__input_image_size,
                                 self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict,
                                                          dtype=np.float64)
                            image_to_predict = preprocess_input(
                                image_to_predict)
                        except:
                            raise ValueError(
                                "You have parsed in a wrong stream for the image"
                            )

                    prediction = model.predict(x=image_to_predict, steps=1)

                    try:
                        predictiondata = decode_predictions(
                            prediction, top=int(result_count_per_image))

                        for results in predictiondata:
                            countdown = 0
                            for result in results:
                                countdown += 1
                                prediction_results.append(str(result[1]))
                                prediction_probabilities.append(result[2] *
                                                                100)
                    except:
                        raise ValueError("An error occured! Try again.")

                    each_image_details = {}
                    each_image_details["predictions"] = prediction_results
                    each_image_details[
                        "percentage_probabilities"] = prediction_probabilities
                    output_array.append(each_image_details)

        return output_array
Example #2
0
    def predictMultipleImages(self,
                              sent_images_array,
                              result_count_per_image=2):
        """
                'predictMultipleImages()' function is used to predict more than one image by receiving the following arguments:
                    * sent_images_array , an array of image file paths
                    * result_count_per_image (optionally) , the number of predictions to be sent per image, which must be whole numbers between
                        1 and 1000. The default is 2.

                This function returns an array of dictionaries, with each dictionary containing 2 arrays namely 'prediction_results' and 'prediction_probabilities'. The 'prediction_results'
                contains possible objects classes arranged in descending of their percentage probabilities. The 'prediction_probabilities'
                contains the percentage probability of each object class. The position of each object class in the 'prediction_results'
                array corresponds with the positions of the percentage possibilities in the 'prediction_probabilities' array.


                :param sent_images_array:
                :param result_count_per_image:
                :return output_array:
                """

        output_array = []

        for eachImage in sent_images_array:

            prediction_results = []
            prediction_probabilities = []
            if (self.__modelLoaded == False):
                raise ValueError(
                    "You must call the loadModel() function before making predictions."
                )

            else:

                if (self.__modelType == "squeezenet"):

                    try:
                        from .SqueezeNet.imagenet_utils import preprocess_input, decode_predictions
                        img = image.load_img(eachImage, target_size=(227, 227))
                        img = image.img_to_array(img,
                                                 data_format="channels_last")
                        img = np.expand_dims(img, axis=0)

                        img = preprocess_input(img,
                                               data_format="channels_last")
                    except:
                        raise ValueError(
                            "You have set a path to an invalid image file.")

                    model = self.__model_collection[0]

                    prediction = model.predict(img, steps=1)

                    try:
                        predictiondata = decode_predictions(
                            prediction, top=int(result_count_per_image))

                        for results in predictiondata:
                            countdown = 0
                            for result in results:
                                countdown += 1
                                prediction_results.append(str(result[1]))
                                prediction_probabilities.append(
                                    str(result[2] * 100))

                        each_image_details = {}
                        each_image_details["predictions"] = prediction_results
                        each_image_details[
                            "percentage_probabilities"] = prediction_probabilities
                        output_array.append(each_image_details)
                    except:
                        raise ValueError(
                            "You have set a wrong path to the JSON file")

                elif (self.__modelType == "resnet"):

                    model = self.__model_collection[0]

                    try:
                        from .ResNet.imagenet_utils import preprocess_input, decode_predictions
                        target_image = image.load_img(eachImage,
                                                      grayscale=False,
                                                      target_size=(224, 224))
                        target_image = image.img_to_array(
                            target_image, data_format="channels_last")
                        target_image = np.expand_dims(target_image, axis=0)

                        target_image = preprocess_input(
                            target_image, data_format="channels_last")
                    except:
                        raise ValueError(
                            "You have set a path to an invalid image file.")

                    prediction = model.predict(x=target_image, steps=1)

                    try:
                        predictiondata = decode_predictions(
                            prediction, top=int(result_count_per_image))

                        for results in predictiondata:
                            countdown = 0
                            for result in results:
                                countdown += 1
                                prediction_results.append(str(result[1]))
                                prediction_probabilities.append(
                                    str(result[2] * 100))
                        each_image_details = {}
                        each_image_details["predictions"] = prediction_results
                        each_image_details[
                            "percentage_probabilities"] = prediction_probabilities
                        output_array.append(each_image_details)
                    except:
                        raise ValueError(
                            "You have set a wrong path to the JSON file")

                elif (self.__modelType == "densenet"):

                    model = self.__model_collection[0]

                    try:
                        from .DenseNet.densenet import DenseNetImageNet121, preprocess_input, decode_predictions
                        from .DenseNet.densenet import DenseNetImageNet121
                        image_to_predict = image.load_img(eachImage,
                                                          grayscale=False,
                                                          target_size=(224,
                                                                       224))
                        image_to_predict = image.img_to_array(
                            image_to_predict, data_format="channels_last")
                        image_to_predict = np.expand_dims(image_to_predict,
                                                          axis=0)

                        image_to_predict = preprocess_input(
                            image_to_predict, data_format="channels_last")
                    except:
                        raise ValueError(
                            "You have set a path to an invalid image file.")

                    prediction = model.predict(x=image_to_predict, steps=1)

                    try:
                        predictiondata = decode_predictions(
                            prediction, top=int(result_count_per_image))

                        for results in predictiondata:
                            countdown = 0
                            for result in results:
                                countdown += 1
                                prediction_results.append(str(result[1]))
                                prediction_probabilities.append(
                                    str(result[2] * 100))

                        each_image_details = {}
                        each_image_details["predictions"] = prediction_results
                        each_image_details[
                            "percentage_probabilities"] = prediction_probabilities
                        output_array.append(each_image_details)
                    except:
                        raise ValueError(
                            "You have set a wrong path to the JSON file")

                elif (self.__modelType == "inceptionv3"):

                    model = self.__model_collection[0]

                    try:
                        from imageai.Prediction.InceptionV3.inceptionv3 import InceptionV3
                        from imageai.Prediction.InceptionV3.inceptionv3 import preprocess_input, decode_predictions

                        image_to_predict = image.load_img(eachImage,
                                                          grayscale=False,
                                                          target_size=(299,
                                                                       299))
                        image_to_predict = image.img_to_array(
                            image_to_predict, data_format="channels_last")
                        image_to_predict = np.expand_dims(image_to_predict,
                                                          axis=0)

                        image_to_predict = preprocess_input(image_to_predict)
                    except:
                        raise ValueError(
                            "You have set a path to an invalid image file.")

                    prediction = model.predict(x=image_to_predict, steps=1)

                    try:
                        predictiondata = decode_predictions(
                            prediction, top=int(result_count_per_image))

                        for results in predictiondata:
                            countdown = 0
                            for result in results:
                                countdown += 1
                                prediction_results.append(str(result[1]))
                                prediction_probabilities.append(
                                    str(result[2] * 100))

                        each_image_details = {}
                        each_image_details["predictions"] = prediction_results
                        each_image_details[
                            "percentage_probabilities"] = prediction_probabilities
                        output_array.append(each_image_details)
                    except:
                        raise ValueError(
                            "You have set a wrong path to the JSON file")

        return output_array
Example #3
0
    def predictMultipleImages(self, sent_images_array, result_count_per_image=2, input_type="file"):
        """
                'predictMultipleImages()' function is used to predict more than one image by receiving the following arguments:
                    * input_type , the type of inputs contained in the parsed array. Acceptable values are "file", "array" and "stream"
                    * sent_images_array , an array of image file paths, image numpy array or image file stream
                    * result_count_per_image (optionally) , the number of predictions to be sent per image, which must be whole numbers between
                        1 and 1000. The default is 2.

                This function returns an array of dictionaries, with each dictionary containing 2 arrays namely 'prediction_results' and 'prediction_probabilities'. The 'prediction_results'
                contains possible objects classes arranged in descending of their percentage probabilities. The 'prediction_probabilities'
                contains the percentage probability of each object class. The position of each object class in the 'prediction_results'
                array corresponds with the positions of the percentage possibilities in the 'prediction_probabilities' array.


                :param input_type:
                :param sent_images_array:
                :param result_count_per_image:
                :return output_array:
                """

        output_array = []

        for image_input in sent_images_array:

            prediction_results = []
            prediction_probabilities = []
            if (self.__modelLoaded == False):
                raise ValueError("You must call the loadModel() function before making predictions.")

            else:

                if (self.__modelType == "squeezenet"):

                    from .imagenet_utils import preprocess_input, decode_predictions
                    if (input_type == "file"):
                        try:
                            image_to_predict = image.load_img(image_input, target_size=(self.__input_image_size, self.__input_image_size))
                            image_to_predict = image.img_to_array(image_to_predict, data_format="channels_last")
                            image_to_predict = np.expand_dims(image_to_predict, axis=0)

                            image_to_predict = preprocess_input(image_to_predict)
                        except:
                            raise ValueError("You have set a path to an invalid image file.")
                    elif (input_type == "array"):
                        try:
                            image_input = Image.fromarray(np.uint8(image_input))
                            image_input = image_input.resize((self.__input_image_size, self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict, dtype=np.float64)
                            image_to_predict = preprocess_input(image_to_predict)
                        except:
                            raise ValueError("You have parsed in a wrong numpy array for the image")
                    elif (input_type == "stream"):
                        try:
                            image_input = Image.open(image_input)
                            image_input = image_input.resize((self.__input_image_size, self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict, dtype=np.float64)
                            image_to_predict = preprocess_input(image_to_predict)
                        except:
                            raise ValueError("You have parsed in a wrong stream for the image")

                    model = self.__model_collection[0]

                    prediction = model.predict(image_to_predict, steps=1)

                    try:
                        predictiondata = decode_predictions(prediction, top=int(result_count_per_image))

                        for results in predictiondata:
                            countdown = 0
                            for result in results:
                                countdown += 1
                                prediction_results.append(str(result[1]))
                                prediction_probabilities.append(str(result[2] * 100))
                    except:
                        raise ValueError("An error occured! Try again.")

                    each_image_details = {}
                    each_image_details["predictions"] = prediction_results
                    each_image_details["percentage_probabilities"] = prediction_probabilities
                    output_array.append(each_image_details)

                elif (self.__modelType == "resnet"):

                    model = self.__model_collection[0]

                    from .imagenet_utils import preprocess_input, decode_predictions
                    if (input_type == "file"):
                        try:
                            image_to_predict = image.load_img(image_input, target_size=(self.__input_image_size, self.__input_image_size))
                            image_to_predict = image.img_to_array(image_to_predict, data_format="channels_last")
                            image_to_predict = np.expand_dims(image_to_predict, axis=0)

                            image_to_predict = preprocess_input(image_to_predict)
                        except:
                            raise ValueError("You have set a path to an invalid image file.")
                    elif (input_type == "array"):
                        try:
                            image_input = Image.fromarray(np.uint8(image_input))
                            image_input = image_input.resize((self.__input_image_size, self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict, dtype=np.float64)
                            image_to_predict = preprocess_input(image_to_predict)
                        except:
                            raise ValueError("You have parsed in a wrong numpy array for the image")
                    elif (input_type == "stream"):
                        try:
                            image_input = Image.open(image_input)
                            image_input = image_input.resize((self.__input_image_size, self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict, dtype=np.float64)
                            image_to_predict = preprocess_input(image_to_predict)
                        except:
                            raise ValueError("You have parsed in a wrong stream for the image")

                    prediction = model.predict(x=image_to_predict, steps=1)

                    try:
                        predictiondata = decode_predictions(prediction, top=int(result_count_per_image))

                        for results in predictiondata:
                            countdown = 0
                            for result in results:
                                countdown += 1
                                prediction_results.append(str(result[1]))
                                prediction_probabilities.append(str(result[2] * 100))
                    except:
                        raise ValueError("An error occured! Try again.")

                    each_image_details = {}
                    each_image_details["predictions"] = prediction_results
                    each_image_details["percentage_probabilities"] = prediction_probabilities
                    output_array.append(each_image_details)

                elif (self.__modelType == "densenet"):

                    model = self.__model_collection[0]

                    from .DenseNet.densenet import preprocess_input, decode_predictions
                    from .DenseNet.densenet import DenseNetImageNet121
                    if (input_type == "file"):
                        try:
                            image_to_predict = image.load_img(image_input, target_size=(self.__input_image_size, self.__input_image_size))
                            image_to_predict = image.img_to_array(image_to_predict, data_format="channels_last")
                            image_to_predict = np.expand_dims(image_to_predict, axis=0)

                            image_to_predict = preprocess_input(image_to_predict)
                        except:
                            raise ValueError("You have set a path to an invalid image file.")
                    elif (input_type == "array"):
                        try:
                            image_input = Image.fromarray(np.uint8(image_input))
                            image_input = image_input.resize((self.__input_image_size, self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict, dtype=np.float64)
                            image_to_predict = preprocess_input(image_to_predict)
                        except:
                            raise ValueError("You have parsed in a wrong numpy array for the image")
                    elif (input_type == "stream"):
                        try:
                            image_input = Image.open(image_input)
                            image_input = image_input.resize((self.__input_image_size, self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict, dtype=np.float64)
                            image_to_predict = preprocess_input(image_to_predict)
                        except:
                            raise ValueError("You have parsed in a wrong stream for the image")

                    prediction = model.predict(x=image_to_predict, steps=1)

                    try:
                        predictiondata = decode_predictions(prediction, top=int(result_count_per_image))

                        for results in predictiondata:
                            countdown = 0
                            for result in results:
                                countdown += 1
                                prediction_results.append(str(result[1]))
                                prediction_probabilities.append(str(result[2] * 100))
                    except:
                        raise ValueError("An error occured! Try again.")

                    each_image_details = {}
                    each_image_details["predictions"] = prediction_results
                    each_image_details["percentage_probabilities"] = prediction_probabilities
                    output_array.append(each_image_details)

                elif (self.__modelType == "inceptionv3"):

                    model = self.__model_collection[0]

                    from imageai.Prediction.InceptionV3.inceptionv3 import InceptionV3, preprocess_input, \
                        decode_predictions

                    if (input_type == "file"):
                        try:
                            image_to_predict = image.load_img(image_input, target_size=(self.__input_image_size, self.__input_image_size))
                            image_to_predict = image.img_to_array(image_to_predict, data_format="channels_last")
                            image_to_predict = np.expand_dims(image_to_predict, axis=0)

                            image_to_predict = preprocess_input(image_to_predict)
                        except:
                            raise ValueError("You have set a path to an invalid image file.")
                    elif (input_type == "array"):
                        try:
                            image_input = Image.fromarray(np.uint8(image_input))
                            image_input = image_input.resize((self.__input_image_size, self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict, dtype=np.float64)
                            image_to_predict = preprocess_input(image_to_predict)
                        except:
                            raise ValueError("You have parsed in a wrong numpy array for the image")
                    elif (input_type == "stream"):
                        try:
                            image_input = Image.open(image_input)
                            image_input = image_input.resize((self.__input_image_size, self.__input_image_size))
                            image_input = np.expand_dims(image_input, axis=0)
                            image_to_predict = image_input.copy()
                            image_to_predict = np.asarray(image_to_predict, dtype=np.float64)
                            image_to_predict = preprocess_input(image_to_predict)
                        except:
                            raise ValueError("You have parsed in a wrong stream for the image")

                    prediction = model.predict(x=image_to_predict, steps=1)

                    try:
                        predictiondata = decode_predictions(prediction, top=int(result_count_per_image))

                        for results in predictiondata:
                            countdown = 0
                            for result in results:
                                countdown += 1
                                prediction_results.append(str(result[1]))
                                prediction_probabilities.append(str(result[2] * 100))
                    except:
                        raise ValueError("An error occured! Try again.")

                    each_image_details = {}
                    each_image_details["predictions"] = prediction_results
                    each_image_details["percentage_probabilities"] = prediction_probabilities
                    output_array.append(each_image_details)


        return output_array
Example #4
0
    def predictImage(self, image_path, result_count=5):
        """
        'predictImage()' function is used to predict a given image by receiving the following arguemants:
            * image_path , file path to the image
            * result_count (optionally) , the number of predictions to be sent which must be whole numbers between
                1 and 1000. The default is 5.

        This function returns 2 arrays namely 'result_prediction' and 'prediction_probabilities'. The 'result_prediction'
        contains possible objects classes arranged in descending of their percentage probabilities. The 'prediction_probabilities'
        contains the percentage probability of each object class. The position of each object class in the 'result_prediction'
        array corresponds with the positions of the percentage possibilities in the 'prediction_probabilities' array.


        :param image_path:
        :param result_count:
        :return result_prediction, prediction_probabilities:
        """
        result_prediction = []
        prediction_probabilities = []
        if (self.__modelLoaded == False):
            raise "You must call the loadModel() function before making predictions."

        else:

            if (self.__modelType == "squeezenet"):

                try:
                    from .SqueezeNet.imagenet_utils import preprocess_input, decode_predictions
                    img = image.load_img(image_path, target_size=(227, 227))
                    img = image.img_to_array(img, data_format="channels_last")
                    img = np.expand_dims(img, axis=0)

                    img = preprocess_input(img, data_format="channels_last")
                except:
                    raise "You have set a path to an invalid image file."

                model = self.__model_collection[0]

                prediction = model.predict(img, steps=1)

                try:
                    predictiondata = decode_predictions(
                        prediction,
                        top=int(result_count),
                        index_file_path=self.jsonPath)

                    for results in predictiondata:
                        countdown = 0
                        for result in results:
                            countdown += 1
                            result_prediction.append(str(result[1]))
                            prediction_probabilities.append(
                                str(result[2] * 100))
                except:
                    raise "You have set a wrong path to the JSON file"

                return result_prediction, prediction_probabilities
            elif (self.__modelType == "resnet"):

                model = self.__model_collection[0]

                try:
                    from .ResNet.imagenet_utils import preprocess_input, decode_predictions
                    target_image = image.load_img(image_path,
                                                  grayscale=False,
                                                  target_size=(224, 224))
                    target_image = image.img_to_array(
                        target_image, data_format="channels_last")
                    target_image = np.expand_dims(target_image, axis=0)

                    target_image = preprocess_input(
                        target_image, data_format="channels_last")
                except:
                    raise "You have set a path to an invalid image file."

                prediction = model.predict(x=target_image, steps=1)

                try:
                    predictiondata = decode_predictions(
                        prediction,
                        top=int(result_count),
                        index_file_path=self.jsonPath)

                    for results in predictiondata:
                        countdown = 0
                        for result in results:
                            countdown += 1
                            result_prediction.append(str(result[1]))
                            prediction_probabilities.append(
                                str(result[2] * 100))
                except:
                    raise "You have set a wrong path to the JSON file"

                return result_prediction, prediction_probabilities
            elif (self.__modelType == "densenet"):

                model = self.__model_collection[0]

                try:
                    from .DenseNet.densenet import DenseNetImageNet121, preprocess_input, decode_predictions
                    from .DenseNet.densenet import DenseNetImageNet121
                    image_to_predict = image.load_img(image_path,
                                                      grayscale=False,
                                                      target_size=(224, 224))
                    image_to_predict = image.img_to_array(
                        image_to_predict, data_format="channels_last")
                    image_to_predict = np.expand_dims(image_to_predict, axis=0)

                    image_to_predict = preprocess_input(
                        image_to_predict, data_format="channels_last")
                except:
                    raise "You have set a path to an invalid image file."

                prediction = model.predict(x=image_to_predict, steps=1)

                try:
                    predictiondata = decode_predictions(
                        prediction,
                        top=int(result_count),
                        index_file_path=self.jsonPath)

                    for results in predictiondata:
                        countdown = 0
                        for result in results:
                            countdown += 1
                            result_prediction.append(str(result[1]))
                            prediction_probabilities.append(
                                str(result[2] * 100))
                except:
                    raise "You have set a wrong path to the JSON file"

                return result_prediction, prediction_probabilities
            elif (self.__modelType == "inceptionv3"):

                model = self.__model_collection[0]

                try:
                    from imageai.Prediction.InceptionV3.inceptionv3 import InceptionV3
                    from imageai.Prediction.InceptionV3.inceptionv3 import preprocess_input, decode_predictions

                    image_to_predict = image.load_img(image_path,
                                                      grayscale=False,
                                                      target_size=(299, 299))
                    image_to_predict = image.img_to_array(
                        image_to_predict, data_format="channels_last")
                    image_to_predict = np.expand_dims(image_to_predict, axis=0)

                    image_to_predict = preprocess_input(image_to_predict)
                except:
                    raise "You have set a path to an invalid image file."

                prediction = model.predict(x=image_to_predict, steps=1)

                try:
                    predictiondata = decode_predictions(
                        prediction,
                        top=int(result_count),
                        index_file_path=self.jsonPath)

                    for results in predictiondata:
                        countdown = 0
                        for result in results:
                            countdown += 1
                            result_prediction.append(str(result[1]))
                            prediction_probabilities.append(
                                str(result[2] * 100))
                except:
                    raise "You have set a wrong path to the JSON file"

                return result_prediction, prediction_probabilities