コード例 #1
0
def loadModel():
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath("model200.h5")
    prediction.setJsonPath("class1.json")
    prediction.loadModel(num_objects=12)
    return prediction
コード例 #2
0
	def __init__(self, image_path, model_path, output_path):
		self.avgColor = []
		self.pcaColors = []

		self.detector = ObjectDetection()
		self.detector.setModelTypeAsYOLOv3()
		self.detector.setModelPath(model_path + "yolo.h5")
		self.detector.loadModel(detection_speed="flash")

		self.prediction = CustomImagePrediction()
		self.prediction.setModelTypeAsResNet()
		#self.prediction.setModelPath(model_path + "model_ex-012_acc-0.988819.h5")
		self.prediction.setModelPath(model_path + "model_ex-043_acc-0.996787.h5")
		self.prediction.setJsonPath(model_path + "model_class.json")
		self.prediction.loadModel(num_objects=2)

		now = time.localtime()
		self.frame_folder = str(now.tm_year) + str(now.tm_mon) + str(now.tm_mday)
		self.image_path = image_path
		self.output_path = output_path + "detection/" + self.frame_folder + "/"

		if os.path.exists(image_path) is False:
			os.mkdir(image_path)

		if os.path.exists(output_path) is False:
			os.mkdir(output_path)

		if os.path.exists(os.path.join(output_path, 'detection')) is False:
			os.mkdir(os.path.join(output_path, 'detection'))

		if os.path.exists(os.path.join(output_path, 'processed')) is False:
			os.mkdir(os.path.join(output_path, 'processed'))

		self.create_output_folder()
コード例 #3
0
ファイル: model.py プロジェクト: JGehl99/SmileFinder
 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()
コード例 #4
0
def getModel():
    global prediction
    if prediction is not None:
        return prediction
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet50()
    prediction.setModelPath("model.h5")
    prediction.setJsonPath("styles.json")
    prediction.loadModel(num_objects=25)
    return prediction
コード例 #5
0
def run_predict():
    predictor = CustomImagePrediction()
    predictor.setModelPath(model_path="trafficnet_resnet_model_ex-055_acc-0.913750.h5")
    predictor.setJsonPath(model_json="model_class.json")
    predictor.loadFullModel(num_objects=4)

    predictions, probabilities = predictor.predictImage(image_input="", result_count=4) #PATH FOR IMAGE
    for prediction, probability in zip(predictions, probabilities):
        print(prediction, " : ", probability)
コード例 #6
0
def run_predict():
    predictor = CustomImagePrediction()
    predictor.setModelPath(model_path="trafficnetmodelacc-0.893750.h5")
    predictor.setJsonPath(model_json="model_class.json")
    predictor.loadFullModel(num_objects=4)

    predictions, probabilities = predictor.predictImage(image_input="images/dense.jpg", result_count=4)
    for prediction, probability in zip(predictions, probabilities):
        print(prediction, " : ", probability)
コード例 #7
0
 def detect_move_from_webcam(
     self,
     model_file_name=None,
     config_file_name="model_class.json",
     webcam_index=0,
     sensibility=80,
 ):
     # Instantiate the CustomImagePrediction object that will predict our moves
     predictor = CustomImagePrediction()
     # Set the model type of the neural network (it must be the same of the training)
     self._set_proper_model_type(self.model_type, predictor)
     if not model_file_name:
         # If model file name is not set, ask user to choose which model must be used
         model_file_name = self._get_model_file_name(self.dataset_name)
     # Set path to the trained model file
     predictor.setModelPath(
         os.path.join(self.base_path, self.dataset_name, "models",
                      model_file_name))
     # Set path to the json file that contains our classes and their labels
     predictor.setJsonPath(
         os.path.join(self.base_path, self.dataset_name, "json",
                      config_file_name))
     # Load the trained model and set it to use "class_number" classes
     predictor.loadModel(num_objects=self.class_number)
     # Context manager that help us to activate/deactivate our webcam
     with opencv_video_capture(webcam_index) as cap:
         # Run until user press "q" key
         while True:
             # Acquire a frame from webcam
             _, frame = cap.read()
             # Do a prediction on that frame
             predictions, probabilities = predictor.predictImage(
                 frame, result_count=3, input_type="array")
             # Get a tuple (class_predicted, probability) that contains the best
             # prediction
             best_prediction = max(zip(predictions, probabilities),
                                   key=lambda x: x[1])
             # If probability of the best prediction is >= of the min sensibility
             # required, it writes a label with predicted class name and probability
             # over the frame
             if best_prediction[1] >= sensibility:
                 cv2.putText(
                     frame,
                     f"{best_prediction[0]} ({round(best_prediction[1], 2)})",
                     (10, 30),
                     cv2.FONT_HERSHEY_SIMPLEX,
                     1,
                     (255, 255, 255),
                     2,
                     cv2.LINE_AA,
                 )
             # Display the acquired frame on a dedicated window
             cv2.imshow("Move predictor", frame)
             # Break cycle if user press "q" key
             if cv2.waitKey(1) & 0xFF == ord("q"):
                 break
コード例 #8
0
def run_predict():
    predictor = CustomImagePrediction()
    predictor.setModelPath(model_path="action_net_ex-060_acc-0.745313.h5")
    predictor.setJsonPath(model_json="model_class.json")
    predictor.loadFullModel(num_objects=16)

    predictions, probabilities = predictor.predictImage(
        image_input="images/5.jpg", result_count=4)
    for prediction, probability in zip(predictions, probabilities):
        print(prediction, " : ", probability)
コード例 #9
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)
コード例 #10
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)
コード例 #11
0
def test_custom_recognition_full_model_resnet():

    predictor = CustomImagePrediction()
    predictor.setModelPath(os.path.join(main_folder, "data-models", "idenprof_full_resnet_ex-001_acc-0.119792.h5"))
    predictor.setJsonPath(model_json=os.path.join(main_folder, "data-json", "idenprof.json"))
    predictor.loadFullModel(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)
コード例 #12
0
ファイル: color_Re.py プロジェクト: windbrothers/code
class Color(object):
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath("./model_data/best_color.h5")
    prediction.setJsonPath("./model_data/color_class.json")
    prediction.loadModel(num_objects=2)

    def color_API(path):
        name = []
        pro = []
        predictions, probabilities = Color.prediction.predictImage(
            path, result_count=2)
        for eachPrediction, eachProbability in zip(predictions, probabilities):
            print(eachPrediction, ':', eachProbability)
            name.append(eachPrediction)
            pro.append(eachProbability)
        if (pro[0] > pro[1]):
            Name = name[0]
        else:
            Name = name[1]

    #    print(Name)
        if (Name == '0'):
            return 0
        else:
            return 1
コード例 #13
0
ファイル: model_test.py プロジェクト: eperezn/vaico_works
    def __init__(self,
                 yolo_weigths='../../models_h5/yolo.h5',
                 model_weigths='../../models_h5/model_ex-055_acc-0.996250.h5',
                 model_json='../../models_h5/model_class.json'):
        self.detector = ObjectDetection()
        self.detector.setModelTypeAsYOLOv3()
        self.detector.setModelPath(yolo_weigths)
        self.detector.loadModel()

        self.classifier = CustomImagePrediction()
        self.classifier.setModelTypeAsResNet()
        self.classifier.setModelPath(model_weigths)
        self.classifier.setJsonPath(model_json)
        self.classifier.loadModel(num_objects=2)

        self.current_detection = []
コード例 #14
0
class Color(object):
    prediction = CustomImagePrediction()
    prediction.setModelTypeAsResNet()
    prediction.setModelPath("./model_data/best_color.h5")
    prediction.setJsonPath("./model_data/color_class.json")
    prediction.loadModel(num_objects=2)

    def color_API(path):
        #            name=[]
        #            pro=[]
        #            predictions, probabilities = Color.prediction.predictImage(path, result_count=2)
        #            for eachPrediction, eachProbability in zip(predictions, probabilities):
        #                    print(eachPrediction,':',eachProbability)
        #                    name.append(eachPrediction)
        #                    pro.append(eachProbability)
        #            if(pro[0]>pro[1]):
        #                    Name=name[0]
        #            else:
        #                    Name=name[1]
        #        #    print(Name)
        #            if(Name=='0'):
        #                return 0
        #            else:
        #                return 1
        i = 1
        for fileName in fileList:
            #遍历文件夹中所有文件
            name = []
            pro = []
            n = len(fileList)
            print('本次需要检测', n, '张照片')
            k = n - i
            start = timer()
            print('还剩', k, '张待检测照片名称', fileName)
            Color.prediction.loadModel(num_objects=2)
            predictions, probabilities = Color.prediction.predictImage(
                ('./input/' + str(fileName)), result_count=2)
            for eachPrediction, eachProbability in zip(predictions,
                                                       probabilities):
                print(eachPrediction, ':', eachProbability)
                name.append(eachPrediction)
                pro.append(eachProbability)
            i = i + 1
            if (pro[0] > pro[1]):
                Name = name[0]
            else:
                Name = name[1]
            print(Name)
            #                if(Name=='0'):
            ##                    img=cv.imread('./input/'+fileName)
            ##                    cv.imwrite('./0/'+fileName,img)
            #                else:
            ##                    img=cv.imread('./input/'+fileName)
            ##                    cv.imwrite('./1/'+fileName,img)
            #                    Name=name[1]
            end = timer()
            print('单张照片执行时间', end - start)
        print('finish')
コード例 #15
0
    def setupPredictionFlowerModel(self):

        # This gets the path of the .py file or the exe file
        exPath = os.getcwd()

        # Creates a custom image prediction object.
        self.predict = CustomImagePrediction()

        # Tells the custom image prediction object that it will be using
        # self.predict.setModelTypeAsResNet()
        # self.predict.setModelTypeAsInceptionV3()
        self.predict.setModelTypeAsDenseNet()

        # Check to see if there is an .h5 file (The model file). If the file
        # is not found then a message is shown to the user saying that the
        # file is missing. Both buttons are disabled to prevent any
        # unexpected crash of the program.
        if (os.path.isfile(os.path.join(exPath, "DenseNet_flower_model_85.h5"))
                is False):
            print("Could not file a training model file (.h5)")
            self.PredictBtn.setEnabled(False)
            self.selectImage.setEnabled(False)
            self.predictionLbl.setText("Missing the model file (.h5)")

        else:
            # If the file the .h5 file exists then the .h5 model path will
            # be set to it.
            self.predict.setModelPath(
                os.path.join(exPath, "DenseNet_flower_model_85.h5"))
            # Checks to see if the .json model class file is found. If it
            # is found the json path is loaded with the file.
            # If the file is not found the user will be shown a message.
            if os.path.isfile(os.path.join(exPath, "flower_model_class.json")):
                self.predict.setJsonPath(
                    os.path.join(exPath, "flower_model_class.json"))
                self.predict.loadModel(num_objects=5)
            else:
                # The message that is shown if the json file is not found.
                # Both buttons are disabled to prevent any unexpected crash
                # of the program.
                print("Could not file a model class file (.jason)")
                self.PredictBtn.setEnabled(False)
                self.selectImage.setEnabled(False)
                self.predictionLbl.setText(
                    "Missing the model class file (.json)")
def activity_detector(image_name):
    result = []
    predictor = CustomImagePrediction()
    predictor.setModelPath(
        model_path=os.path.join(root, "action-detection-image", "action.h5"))
    predictor.setJsonPath(model_json=os.path.join(
        root, "action-detection-image", "model_class.json"))
    predictor.loadFullModel(num_objects=16)

    predictions, probabilities = predictor.predictImage(image_input=image_name,
                                                        result_count=4)
    for prediction, probability in zip(predictions, probabilities):
        result.append([prediction, probability])
    print(result)
    return result[0][0]
コード例 #17
0
 def __init__(
         self,
         model_type=ModelTypeEnum.RESNET,
         class_number=3,  # We have 3 different objects: "rock", "paper", "scissors"
 ):
     self.model_type = model_type
     self.class_number = class_number
     self.base_path = os.getcwd()
     # Instantiate the CustomImagePrediction object that will predict our moves
     self.predictor = CustomImagePrediction()
     # Set the model type of the neural network (it must be the same of the training)
     self._set_proper_model_type(self.model_type)
     # Set path to the trained model file
     self.predictor.setModelPath(
         os.path.join(self.base_path, "data", "move_detector", "model.h5"))
     # Set path to the json file that contains our classes and their labels
     self.predictor.setJsonPath(
         os.path.join(self.base_path, "data", "move_detector",
                      "model_class.json"))
     # Load the trained model and set it to use "class_number" classes
     self.predictor.loadModel(num_objects=self.class_number)
コード例 #18
0
class RockPaperScissorsPredictor:
    """
    This class contains the required code for model training and move prediction using a
    webcam
    """

    MODEL_TYPE_SET_LOOKUP = {
        ModelTypeEnum.RESNET: lambda x: x.setModelTypeAsResNet(),
        ModelTypeEnum.SQEEZENET: lambda x: x.setModelTypeAsSqueezeNet(),
        ModelTypeEnum.INCEPTIONV3: lambda x: x.setModelTypeAsInceptionV3(),
        ModelTypeEnum.DENSENET: lambda x: x.setModelTypeAsDenseNet(),
    }

    MOVES_LOOKUP = {
        "rock": MovesEnum.ROCK,
        "paper": MovesEnum.PAPER,
        "scissors": MovesEnum.SCISSORS,
    }

    def __init__(
            self,
            model_type=ModelTypeEnum.RESNET,
            class_number=3,  # We have 3 different objects: "rock", "paper", "scissors"
    ):
        self.model_type = model_type
        self.class_number = class_number
        self.base_path = os.getcwd()
        # Instantiate the CustomImagePrediction object that will predict our moves
        self.predictor = CustomImagePrediction()
        # Set the model type of the neural network (it must be the same of the training)
        self._set_proper_model_type(self.model_type)
        # Set path to the trained model file
        self.predictor.setModelPath(
            os.path.join(self.base_path, "data", "move_detector", "model.h5"))
        # Set path to the json file that contains our classes and their labels
        self.predictor.setJsonPath(
            os.path.join(self.base_path, "data", "move_detector",
                         "model_class.json"))
        # Load the trained model and set it to use "class_number" classes
        self.predictor.loadModel(num_objects=self.class_number)

    def _set_proper_model_type(self, model_type):
        self.MODEL_TYPE_SET_LOOKUP[model_type](self.predictor)

    def detect_move_from_picture(self, picture, sensibility=90):
        predictions, probabilities = self.predictor.predictImage(
            picture, result_count=3, input_type="array")
        # Get a tuple (class_predicted, probability) that contains the best
        # prediction
        best_prediction = max(zip(predictions, probabilities),
                              key=lambda x: x[1])
        if best_prediction[1] < sensibility:
            return

        return self.MOVES_LOOKUP[best_prediction[0]]
コード例 #19
0
def test_custom_recognition_full_model_resnet_multi():
    try:
        keras.backend.clear_session()
    except:
        None
    predictor = CustomImagePrediction()
    predictor.setModelPath(os.path.join(main_folder, "data-models", "idenprof_full_resnet_ex-001_acc-0.119792.h5"))
    predictor.setJsonPath(model_json=os.path.join(main_folder, "data-json", "idenprof.json"))
    predictor.loadFullModel(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)
コード例 #20
0
async def predict_image(image_name: Union[str, np.ndarray],
                        model: CustomImagePrediction) -> dict:
    """Predicts a given image with the supplied prediction model"""
    print('\nPredicting the {} image'.format(image_name))

    predictions, probabilities = model.predictImage(os.path.join(
        EXECUTION_PATH, image_name),
                                                    result_count=2)

    representation = {}
    for eachPrediction, eachProbability in zip(predictions, probabilities):
        representation[eachPrediction] = '{0:.2f}%'.format(
            float(eachProbability))

    return representation
コード例 #21
0
ファイル: model.py プロジェクト: JGehl99/SmileFinder
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
コード例 #22
0
def run_predict():
    predictor = CustomImagePrediction()
    predictor.setModelPath(
        model_path="trafficnet_resnet_model_ex-055_acc-0.913750.h5")
    predictor.setJsonPath(model_json="model_class.json")
    predictor.loadFullModel(num_objects=4)

    predictions, probabilities = predictor.predictImage(
        image_input="images/traff.jpg", result_count=4)
    for prediction, probability in zip(predictions, probabilities):
        print(prediction, " : ", probability)
        result["accident"][prediction] = probability
        # otus thresholding of 80
        if probability > 80:
            result["accident_result"][prediction] = True
        else:
            result["accident_result"][prediction] = False
    if result["accident_result"]["Accident"] == True or result[
            "accident_result"]["Fire"] == True:
        sendemail()
    print(result)
    write(result)
コード例 #23
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
コード例 #24
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'}
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]})
コード例 #26
0
    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
コード例 #27
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2019/8/9 下午 08:55
# @Author  : YuXin Chen

from imageai.Prediction.Custom import CustomImagePrediction
import os

prediction = CustomImagePrediction()
prediction.setModelTypeAsResNet()
prediction.setModelPath("./model/model_ex-075_acc-0.866071.h5")
prediction.setJsonPath("./model/model_class.json")
prediction.loadModel(num_objects=5)

predictions, probabilities = prediction.predictImage("./pic/test/tulips.jpg",
                                                     result_count=5)

for eachPrediction, eachProbability in zip(predictions, probabilities):
    print(eachPrediction + " : " + eachProbability)
コード例 #28
0
ファイル: test.py プロジェクト: zc97/Computer-Vision-Team19
from imageai.Prediction.Custom import CustomImagePrediction
import os

# Load the model to use for prediction
predictor = CustomImagePrediction()
predictor.setModelPath(model_path="model_ex-035_acc-0.874667.h5")
predictor.setJsonPath(model_json="model_class.json")
predictor.loadFullModel(num_objects=5)

directory = "C:/Programs/Java/Computer-Vision-Team19/testing/"

ints = []

# Put the names of the image files into the array of ints
for file in os.listdir(directory):
    filename = os.fsdecode(file)
    if filename.endswith(".jpg"):
        ints.append(int(filename.split(".", 1)[0]))
    else:
        print("Ignoring file named " + filename)

# Sort the filenames and print a newline
ints.sort()
print()

# Log prediction results to a file
log = open("../run3.txt", "w")
for i in ints:
    filename = str(i) + ".jpg"
    path = os.path.join(directory, filename)
    prediction, probability = predictor.predictImage(image_input=path,
コード例 #29
0
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)
コード例 #30
0
        #reshaping to a list of pixels
        img = img.reshape((img.shape[0] * img.shape[1], 3))
        #save image after operations
        self.IMAGE = img
        #using k-means to cluster pixels
        kmeans = KMeans(n_clusters = self.CLUSTERS)
        kmeans.fit(img)
        #the cluster centers are our dominant colors.
        self.COLORS = kmeans.cluster_centers_
        #save labels
        self.LABELS = kmeans.labels_
        #returning after converting to integer from float
        return self.COLORS.astype(int)

execution_path = os.getcwd()
prediction = CustomImagePrediction()
prediction.setModelTypeAsDenseNet()
prediction.setModelPath("model_ex-100_acc-0.829508.h5")
prediction.setJsonPath("model_class.json")
prediction.loadModel(num_objects=11)

map_to_classes= { 
    'team1left': '0', 
   	'team1down': '1', 
	'team1up': '2', 
    'team1right': '3',  
    'team2left': '4', 
   	'team2down': '5', 
	'team2up': '6', 
    'team2right': '7',     	
    'Team1GoalAttack': '8', 
コード例 #31
0
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)