def fileUpload():
    target = os.path.join(UPLOAD_FOLDER, 'test_docs')
    if not os.path.isdir(target):
        os.mkdir(target)
    logger.info("welcome to upload`")
    file = request.files['file']
    filename = secure_filename(file.filename)
    destination = "/".join([target, filename])
    file.save(destination)
    session['uploadFilePath'] = destination
    execution_path = os.getcwd()
    dir = os.path.dirname(os.path.realpath(__file__))
    dir.replace("\\", "\\\\")
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setJsonPath(dir + r"\model_class.json")
    prediction.setModelPath(dir + r"\model_ex-085_acc-0.966261.h5")
    prediction.loadModel(num_objects=2)

    try:
        predictions, probabilities = prediction.predictImage(
            dir + r"\\test_docs\\" + filename, result_count=2)
    except:
        tf.keras.backend.clear_session()
        os.remove('test_docs\\' + filename)
        return "error"

    tf.keras.backend.clear_session()

    p1, p2 = zip(predictions, probabilities)

    result = p1[0]
    os.remove('test_docs\\' + filename)
    return result
Beispiel #2
0
def loadModel():
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath("model200.h5")
    prediction.setJsonPath("class1.json")
    prediction.loadModel(num_objects=12)
    return prediction
Beispiel #3
0
def ImageML():
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath("idenprof/models/idenprof_061-0.7933.h5")
    prediction.setJsonPath("idenprof/json/model_class.json")
    prediction.loadModel(num_objects=10)
    predictions, probabilities = prediction.predictImage("image.jpg",
                                                         result_count=3)
    for eachPrediction, eachProbability in zip(predictions, probabilities):
        print(eachPrediction, " : ", eachProbability)
Beispiel #4
0
def ImageClassifier(Image, ModelFile, JsonFile, Classes):
    execution_path = os.getcwd()  #get model path
    prediction = CustomImagePrediction(
    )  #create instance for the prediction model
    prediction.setModelTypeAsResNet()  #set classification model to ResNet
    prediction.setModelPath(ModelFile)  #loads best model trained
    prediction.setJsonPath(JsonFile)  #loads best model trained
    prediction.loadModel(num_objects=Classes)  #Loads best model trained
    predictions, probabilities = prediction.predictImage(
        Image, result_count=3)  #classify the image
    return predictions, probabilities
Beispiel #5
0
def classify_trash(images):
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath(os.path.join(execution_path, "model.h5"))
    prediction.setJsonPath(os.path.join(execution_path, "model_class.json"))
    prediction.loadModel(num_objects=6)
    trashTypes = set()
    for i in images:
        pre, prob = prediction.predictImage(i, input_type="array")
        trashTypes.add(pre[0])
    return trashTypes
Beispiel #6
0
def getOccupation(filename):
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath("preTrainedModels/idenprof.h5")
    prediction.setJsonPath("preTrainedModels/idenprof.json")
    prediction.loadModel(num_objects=10)

    predictions, probabilities = prediction.predictImage(filename,
                                                         result_count=1)

    return predictions[0]
def foo():
    a=[]
    prediction= CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath("model_ex-030_acc-0.996974.h5")
    prediction.setJsonPath("model_class2.json")
    prediction.loadModel(num_objects=13)
    predictions, probabilities = prediction.predictImage("images/image.jpg", result_count=3)
    for eachPrediction, eachProbability in zip(predictions, probabilities):
        #print(eachPrediction , " : " , eachProbability)
        a.append(eachPrediction)
    return jsonify({"Your image result is here and solution has been sent via a mail": a[0]})
def detect():
	prediction = CustomImagePrediction()
	prediction.setModelTypeAsResNet()
	prediction.setModelPath("model200.h5")
	prediction.setJsonPath("class1.json")
	prediction.loadModel(num_objects=12)
	predictions, probabilities = prediction.predictImage("C:/xampp/htdocs/tcs/temp.jpg", result_count=1)

	for eachPrediction, eachProbability in zip(predictions, probabilities):
		item = eachPrediction
	
	return item
Beispiel #9
0
def main(path_model, path_classes, path_image):
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath(path_model)
    prediction.setJsonPath(path_classes)
    prediction.loadModel(num_objects=10)

    predictions, probabilities = prediction.predictImage(path_image,
                                                         result_count=5)

    for eachPrediction, eachProbability in zip(predictions, probabilities):
        print(eachPrediction, " : ", eachProbability)
Beispiel #10
0
    def ObjectDetect(self):
        execution_path = "C:\Tensorflow\models\Research\object_detection\Engine\customPrediction"
        print(execution_path)
        detector = ObjectDetection()
        detector.setModelTypeAsRetinaNet()
        detector.setModelPath(
            os.path.join(execution_path, "resnet50_coco_best_v2.0.1.h5"))
        detector.loadModel()
        detections1 = detector.detectCustomObjectsFromImage(
            input_image=os.path.join(execution_path, "trail1.jpg"),
            output_image_path=os.path.join(execution_path, "example3.jpg"))

        detector2 = ObjectDetection()
        detector2.setModelTypeAsYOLOv3()
        detector2.setModelPath(os.path.join(execution_path, "yolo.h5"))
        detector2.loadModel()
        detections2 = detector2.detectCustomObjectsFromImage(
            input_image=os.path.join(execution_path, "trail1.jpg"),
            output_image_path=os.path.join(execution_path, "example4.jpg"))

        detector3 = ObjectDetection()
        detector3.setModelTypeAsTinyYOLOv3()
        detector3.setModelPath(os.path.join(execution_path, "yolo-tiny.h5"))
        detector3.loadModel()
        detections3 = detector3.detectCustomObjectsFromImage(
            input_image=os.path.join(execution_path, "trail1.jpg"),
            output_image_path=os.path.join(execution_path, "example5.jpg"))

        prediction = CustomImagePrediction()
        prediction.setModelTypeAsResNet()
        prediction.setModelPath(
            os.path.join(execution_path, "model_ex-027_acc-0.843750.h5"))
        prediction.setJsonPath(os.path.join(execution_path,
                                            "model_class.json"))
        prediction.loadModel(num_objects=2)
        predictions, probabilities = prediction.predictImage(os.path.join(
            execution_path, "trail1.jpg"),
                                                             result_count=5)

        detections = detections1 + detections2 + detections3
        List = []
        for i in detections:
            List.append(i["name"])

        for eachPrediction, eachProbability in zip(predictions, probabilities):
            if eachProbability > 50:
                List.append(eachPrediction)
        """for eachObject in detections:
            print(eachObject["name"], " : ", eachObject["percentage_probability"])

        for eachPrediction, eachProbability in zip(predictions, probabilities):
            print(eachPrediction, " : ", eachProbability)"""
        return List
Beispiel #11
0
def match_tracks(detections, video_name, thresh=10, scale=4):
    matched = set()
    scores = dict()
    frame_num = 0
    cap = cv2.VideoCapture(video_name)

    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath("models/resnet_model.h5")
    prediction.setJsonPath("models/resnet_model_class.json")
    prediction.loadModel(num_objects=2)
    a = 0
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        if frame_num in detections:
            for ID in detections[frame_num]:
                if ID in matched:
                    continue
                try:
                    box = scaleROI(detections[frame_num][ID], scale)
                    img = frame[box[1]:box[3], box[0]:box[2]]

                    cv2.imwrite("temp.1.jpg", img)
                    predictions, probabilities = prediction.predictImage(
                        "temp.1.jpg", result_count=2)
                    boat_score = probabilities[0] if predictions[
                        0] == 'boat' else probabilities[1]
                    if boat_score >= 65:
                        a += 1
                        print(predictions, probabilities, a)
                        cv2.imshow("", img)
                        cv2.waitKey(1)
                        scores[ID] = scores[ID] + 1 if ID in scores else 1
                        if scores[ID] >= thresh:
                            matched.add(ID)
                except Exception as e:
                    pass
        frame_num += 1
    tracks = dict({-1: dict()})
    for frame_num in detections:
        for ID in detections[frame_num]:
            if ID not in tracks:
                tracks[ID] = dict()
            if ID in matched:
                tracks[-1][frame_num] = detections[frame_num][ID]
            else:
                if len(tracks[ID]) >= 3 * 20:
                    tracks[ID][frame_num] = detections[frame_num][ID]

    return tracks
Beispiel #12
0
def detect():
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath(os.path.join("model200.h5"))
    prediction.setJsonPath("class1.json")
    prediction.loadModel(num_objects=14)
    predictions, probabilities = prediction.predictImage(
        "UPLOAD_FOLDER/photo.jpg", result_count=1)

    # for eachPrediction, eachProbability in zip(predictions, probabilities):
    #     print(eachPrediction)
    #     item = eachPrediction
    item = database(predictions[0])
    return item
def test_custom_recognition_model_resnet():


    predictor = CustomImagePrediction()
    predictor.setModelTypeAsResNet()
    predictor.setModelPath(os.path.join(main_folder, "data-models", "idenprof_resnet.h5"))
    predictor.setJsonPath(model_json=os.path.join(main_folder, "data-json", "idenprof.json"))
    predictor.loadModel(num_objects=10)
    predictions, probabilities = predictor.predictImage(image_input=os.path.join(main_folder, main_folder, "data-images", "9.jpg"))

    assert isinstance(predictions, list)
    assert isinstance(probabilities, list)
    assert isinstance(predictions[0], str)
    assert isinstance(probabilities[0], str)
Beispiel #14
0
def agricheck():
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath(r"C:\Users\Kunal Jindal\PycharmProjects\agricure.tech\Files\model_ex-022_acc-0.966484.h5")
    prediction.setJsonPath(r"C:\Users\Kunal Jindal\PycharmProjects\agricure.tech\Files\model_class.json")
    prediction.loadModel(num_objects=18)
    for a, b, c in os.walk(r"C:\Users\Kunal Jindal\PycharmProjects\agricure.tech\static\upload"):
        imglist = a + r"\\" + c[0]
    predictions, probabilities = prediction.predictImage(imglist, result_count=1)
    os.remove(imglist)
    db = TinyDB(r"C:\Users\Kunal Jindal\PycharmProjects\agricure.tech\Files\db.json")
    User = Query()
    val = (db.search(User.code == predictions[0]))[0]
    outlist = {'code': predictions[0], 'plant': val["plant"], 'treatment': val["treatment"], 'disease': val["disease"]}
    return outlist
Beispiel #15
0
def init():
    #Prepare and load model
    global execution_path, prediction, graph, session
    execution_path = os.getcwd()
    session = tf.Session()
    graph = tf.get_default_graph()
    tf.keras.backend.set_session(session)
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath(
        execution_path +
        "/Train&Test/chest_xray/models/model_ex-003_acc-0.773026.h5")
    prediction.setJsonPath(execution_path +
                           "/Train&Test/chest_xray/json/model_class.json")
    prediction.loadModel(num_objects=2)
Beispiel #16
0
async def main(file_type: str, files: str):
    model = CustomImagePrediction()
    model.setModelTypeAsResNet()

    model.setModelPath(
        os.path.join(EXECUTION_PATH, 'data/images/models/kermit_finder.h5'))
    model.setJsonPath(
        os.path.join(EXECUTION_PATH, 'data/images/json/model_class.json'))
    model.loadModel(num_objects=2)  # number of objects on your trained model

    if file_type == 'image':
        for image in files.split(','):
            print(await predict_image(image_name=image, model=model))
    else:
        await predict_video(video_path=files, model=model)
Beispiel #17
0
def obj_prediction(img):
    execution_path = os.getcwd()

    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath(os.path.join(execution_path, "rat_model.h5"))
    prediction.setJsonPath(os.path.join(execution_path, "model_class.json"))
    prediction.loadModel(num_objects=2, prediction_speed="fastest")

    predictions, probabilities = prediction.predictImage(os.path.join(
        execution_path, img + ".png"),
                                                         result_count=2)

    max_prediction = ""
    max_probability = -1.00
    print("\n=================================")
    for eachPrediction, eachProbability in zip(predictions, probabilities):
        if (max_probability < float(eachProbability)):
            max_prediction = eachPrediction
            max_probability = float(eachProbability)

        print(eachPrediction + " : " + eachProbability)
    print("=================================\n")

    # create Image object with the input image
    image = Image.open(img + ".png")

    # initialise the drawing context with the image object as background
    draw = ImageDraw.Draw(image)

    # create font object with the font file and specify desired size
    font = ImageFont.truetype("Roboto-Black.ttf", size=size, encoding="unic")
    colour = "rgb(255, 255, 255)"

    # draw the message on the background
    draw.rectangle(((0, 0), (1500, 160)),
                   outline="rgb(0, 0, 0)",
                   fill="rgb(0, 0, 0)")
    draw.text((x, y),
              max_prediction + ": " + str(max_probability),
              fill=colour,
              font=font)

    # save the edited image
    image.save(img + "_pro.png")
    print("Generated " + img_name + "_pro.png")
Beispiel #18
0
def predict_oil_quality(request):
    try:

        filename = 'model_ex-003_acc-0.677249.h5'
        request_image = request.FILES['photo']
        #request_image = request.data['photo']

        path = request_image.file.name
        print("path: " + path)
        
       # test_image = image.load_img(request_image, target_size=(64, 64, 3))
        #test_image = image.img_to_array(test_image)
        #test_image = np.expand_dims(test_image, axis = 0)
        
        execution_path = os.getcwd()

        prediction = CustomImagePrediction()
        prediction.setModelTypeAsResNet()
        prediction.setModelPath(filename)
        prediction.setJsonPath("model_class.json")
        prediction.loadModel(num_objects=3)
        
       # predictions, probabilities = prediction.predictImage(os.path.join(execution_path, request_image), result_count=3)
        predictions, probabilities = prediction.predictImage(path, result_count=3)

        result = 0
        result_text = ''

        for eachPrediction, eachProbability in zip(predictions, probabilities):
            if(eachProbability > result):
                result = eachProbability
                result_text = eachPrediction

        if(result_text == 'good_oil'):
            result_text = 'GOOD'
        elif(result_text == 'bad_oil'):
            result_text = 'BAD'
        else:
            result_text = 'NO OIL'


        return Response(data=result_text, status=200)
    except Exception as e:
        print(e)
        return Response(status=400)
Beispiel #19
0
    def modelPredict(model_path='data/models/model_ex-001_acc-0.500000.h5',
                     class_path='data/json/model_class.json',
                     pic_path='a.jpg',
                     classNum=2,
                     resNum=5):
        '''

        模型预测部分
        prediction_speed[模型加载的速度]:fast faster fastest
        '''
        prediction = CustomImagePrediction()
        prediction.setModelTypeAsResNet()
        prediction.setModelPath(model_path)
        prediction.setJsonPath(class_path)
        prediction.loadModel(num_objects=classNum, prediction_speed='fastest')
        prediction, probabilities = prediction.predictImage(
            pic_path, result_count=resNum)
        for eachPrediction, eachProbability in zip(predictions, probabilities):
            print(eachPrediction + " : " + str(eachProbability))
Beispiel #20
0
def run_Image_AI(filename="empty"):
    execution_path = os.getcwd()

    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath("model_ex-092_acc-0.959971.h5")
    prediction.setJsonPath("model_class.json")
    prediction.loadModel(num_objects=7)

    predictions, probabilities = prediction.predictImage(filename,
                                                         result_count=7)
    count = 0
    finPred = ""
    finProb = 0.0
    for eachPrediction, eachProbability in zip(predictions, probabilities):
        finPred = eachPrediction
        finProb = eachProbability
        break

    return finPred
Beispiel #21
0
def test_custom_recognition_model_resnet_multi():
    predictor = CustomImagePrediction()
    predictor.setModelTypeAsResNet()
    predictor.setModelPath(
        os.path.join(main_folder, "data-models", "idenprof_resnet.h5"))
    predictor.setJsonPath(
        model_json=os.path.join(main_folder, "data-json", "idenprof.json"))
    predictor.loadModel(num_objects=10)
    images_to_image_array()
    result_array = predictor.predictMultipleImages(
        sent_images_array=all_images_array)

    assert isinstance(result_array, list)
    for result in result_array:
        assert "predictions" in result
        assert "percentage_probabilities" in result
        assert isinstance(result["predictions"], list)
        assert isinstance(result["percentage_probabilities"], list)
        assert isinstance(result["predictions"][0], str)
        assert isinstance(result["percentage_probabilities"][0], str)
def analisisFunction(file_path):
    n = 0
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath("assets/models/model_061-0.7933.h5")
    prediction.setJsonPath("assets/json/model_class.json")
    prediction.loadModel(num_objects=10)

    predictions, probabilities = prediction.predictImage(file_path,
                                                         result_count=3)
    encabezado = "RESULTADOS:", file_path
    Lb1.insert(n, encabezado)
    for eachPrediction, eachProbability in zip(predictions, probabilities):
        n += 1
        pro = round(float(eachProbability), 2)
        line = eachPrediction, pro, " %"
        print(line)
        Lb1.insert(n, line)

    Lb1.insert(n + 1, " ")
Beispiel #23
0
class Model(object):
    def __init__(self):
        self.prediction = CustomImagePrediction()
        self.prediction.setModelTypeAsResNet()
        self.prediction.setModelPath(
            "datasets/models/model_ex-062_acc-0.916385.h5")
        self.prediction.setJsonPath("datasets/json/model_class.json")
        self.prediction.loadModel(num_objects=2)
        self.webcam = Webcam()

    def predict(self, frame):
        pred, prob = self.prediction.predictImage(detect(frame)[1],
                                                  input_type="array",
                                                  result_count=2)

        if prob[0] < 80:
            cv2.rectangle(frame, (0, 0), (50, 50), (0, 255, 0), -1)
        else:
            cv2.rectangle(frame, (0, 0), (50, 50), (0, 0, 255), -1)

        return frame
    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.")
Beispiel #25
0
def face_recognition(imageName):
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath(
        "./quickstart/recognition/face_recognition/model_ex-030_acc-1.000000.h5"
    )
    prediction.setJsonPath(
        "./quickstart/recognition/face_recognition/model_class.json")
    prediction.loadModel(num_objects=3)

    predictions, probabilities = prediction.predictImage(imageName,
                                                         result_count=3)

    person = ''
    max = '0'
    for eachPrediction, eachProbability in zip(predictions, probabilities):
        if eachProbability > max:
            max = eachProbability
            person = eachPrediction

    if max >= '80':
        return "It's " + person + "!"
    else:
        return "Didn't recognise anyone"
Beispiel #26
0
from imageai.Prediction.Custom import CustomImagePrediction
import os
import os.path

execution_path = os.getcwd()

prediction = CustomImagePrediction()
prediction.setModelTypeAsResNet()
prediction.setModelPath(
    '{path}/traineddata/model_ex-032_acc-0.765625.h5'.format(
        path=execution_path))
prediction.setJsonPath(
    '{path}/traineddata/model_class.json'.format(path=execution_path))
prediction.loadModel(num_objects=2)  # number of trained objects


def predict(img):
    predictions, probabilities = prediction.predictImage(img, result_count=1)

    for eachPrediction, eachProbability in zip(predictions, probabilities):
        print(str(eachPrediction) + " : " + str(eachProbability))
    return {'status': 'ok'}
from imageai.Prediction.Custom import CustomImagePrediction
import os

execution_path = os.getcwd()

prediction = CustomImagePrediction()
prediction.setModelTypeAsResNet()
prediction.setModelPath(os.path.join(execution_path, "resnet_model_ex-020_acc-0.651714.h5"))
prediction.setJsonPath(os.path.join(execution_path, "model_class.json"))
prediction.loadModel(num_objects=10)

predictions, probabilities = prediction.predictImage(os.path.join(execution_path, "4.jpg"), result_count=5)

for eachPrediction, eachProbability in zip(predictions, probabilities):
    print(eachPrediction + " : " + eachProbability)
    def detect_image(self, image):
        from imageai.Prediction.Custom import CustomImagePrediction
        execution_path = os.getcwd()
        prediction = CustomImagePrediction()
        prediction.setModelTypeAsResNet()
        prediction.setModelPath(
            os.path.join(execution_path,
                         "cone_color_keras/model_ex-100_acc-1.000000.h5"))
        prediction.setJsonPath(
            os.path.join(execution_path, "cone_color_keras/model_class_json"))
        prediction.loadModel(num_objects=3)
        start = timer()

        if self.model_image_size != (None, None):
            assert self.model_image_size[
                0] % 32 == 0, 'Multiples of 32 required'
            assert self.model_image_size[
                1] % 32 == 0, 'Multiples of 32 required'
            boxed_image = letterbox_image(
                image,
                tuple(reversed(self.model_image_size)))  #letterbox()标准化尺寸??
        else:
            new_image_size = (image.width - (image.width % 32),
                              image.height - (image.height % 32))
            boxed_image = letterbox_image(image, new_image_size)
        image_data = np.array(boxed_image, dtype='float32')

        print(image_data.shape)
        image_data /= 255.
        image_data = np.expand_dims(image_data, 0)  # Add batch dimension.

        out_boxes, out_scores, out_classes = self.sess.run(
            [self.boxes, self.scores, self.classes],
            feed_dict={
                self.yolo_model.input: image_data,
                self.input_image_shape: [image.size[1], image.size[0]],
                K.learning_phase(): 0
            })

        print('Found {} boxes for {}'.format(len(out_boxes), 'img'))

        font = ImageFont.truetype(font='font/FiraMono-Medium.otf',
                                  size=np.floor(3e-2 * image.size[1] +
                                                0.5).astype('int32'))
        thickness = (image.size[0] + image.size[1]) // 300

        for i, c in reversed(list(enumerate(out_classes))):
            predicted_class = self.class_names[c]
            global Class
            Class = c
            box = out_boxes[i]
            score = out_scores[i]

            #label = '{} {:.2f}'.format(predicted_class, score)
            draw = ImageDraw.Draw(image)
            #label_size = draw.textsize(label, font)

            top, left, bottom, right = box
            top = max(0, np.floor(top + 0.5).astype('int32'))
            left = max(0, np.floor(left + 0.5).astype('int32'))
            bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))
            right = min(image.size[0], np.floor(right + 0.5).astype('int32'))
            #print(label, (left, top), (right, bottom))

            image_to_detect_color = np.array(image)
            image_to_detect_color = image_to_detect_color[left:right,
                                                          top:bottom]
            predictions, probabilities = prediction.predictImage(
                image_to_detect_color, result_count=3)
            label = '{} {:.2f}'.format('blue cone', probabilities)
            label_size = draw.textsize(label, font)
            print(label, (left, top), (right, bottom))

            #calculate distance to the cones
            global locX, locY
            locX = round((left + right) / 2)
            locY = round(top + (bottom - top) * 0.8)

            if top - label_size[1] >= 0:
                text_origin = np.array([left, top - label_size[1]])
            else:
                text_origin = np.array([left, top + 1])

            # My kingdom for a good redistributable image drawing library.
            for i in range(thickness):
                draw.ellipse(
                    ((left + right) / 2, (top + (bottom - top) * 0.8), 5, 5),
                    fill=self.colors[c])
                draw.rectangle([left + i, top + i, right - i, bottom - i],
                               outline=self.colors[c])
            draw.rectangle(
                [tuple(text_origin),
                 tuple(text_origin + label_size)],
                fill=self.colors[c])

            #draw.text(text_origin, label, fill=(0, 0, 0), font=font)
            if predictions == 0:
                label = '{} {:.2f}'.format('blue cone', probabilities)
                draw.text(text_origin, label, fill=(0, 0, 0), font=font)
            elif predictions == 1:
                label = '{} {:.2f}'.format('red cone', probabilities)
                draw.text(text_origin, label, fill=(0, 0, 0), font=font)
            else:
                label = '{} {:.2f}'.format('yellow cone', probabilities)
                draw.text(text_origin, label, fill=(0, 0, 0), font=font)
            del draw

        end = timer()
        print(end - start)
        #import cv2
        #cv2.imshow("detected",image)
        return image
Beispiel #29
0
from imageai.Prediction.Custom import CustomImagePrediction
import os

execution_path = os.getcwd()

predictor = CustomImagePrediction()
predictor.setModelTypeAsResNet()
predictor.setModelPath(
    model_path=os.path.join(execution_path, "idenprof_resnet.h5")
)  # Download the model via this link https://github.com/OlafenwaMoses/ImageAI/releases/tag/models-v3
predictor.setJsonPath(model_json=os.path.join(execution_path, "idenprof.json"))
predictor.loadModel(num_objects=10)
predictor.save_model_to_tensorflow(
    new_model_folder=os.path.join(execution_path, "tensorflow_model"),
    new_model_name="idenprof_resnet_tensorflow.pb")
Beispiel #30
0
from imageai.Prediction.Custom import CustomImagePrediction
from imageai.Detection import ObjectDetection
# import os
import pprint

# execution_path = os.getcwd()  # gets the path of where the python file and model file are at

# DETECTION TO OUTPUT THE PREDICTION IN CONSOLE
prediction = CustomImagePrediction()

prediction.setModelTypeAsResNet(
)  # sets the model type of prediction as ResNet - one we used
prediction.setModelPath("idenprof_061-0.7933.h5"
                        )  # sets model path of prediction to the ai model file
prediction.setJsonPath(
    "idenprof_model_class.json")  # sets the path of json file
prediction.loadModel(num_objects=10)

# DETECTION TO CREATE NEW IMAGES ON FOUND ITEMS
detector = ObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath("resnet50_coco_best_v2.0.1.h5")
detector.loadModel()
detections, path = detector.detectObjectsFromImage(
    input_image="image.jpg",  # takes in the input image
    output_image_path="newimage.jpg",  # creates a new image
    # creates new images from the each object
    extract_detected_objects=True)

# DETECTION TO DRAW BOXES AROUND IN A NEW IMAGE
lidl_detector = ObjectDetection()
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()