Example #1
0
def get_image(lat, lon):
    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath(
        "mapp/model/detection_model-ex-017--loss-0015.576.h5")
    detector.setJsonPath("mapp/config/detection_config.json")
    detector.loadModel()
    print("hello")

    key = "AIzaSyC2I2tRTHHWgVJzkbwrfuzprwo_yoFdlxg"
    url = "https://maps.googleapis.com/maps/api/staticmap?"
    zoom = "18"
    size = "400x400"
    maptype = "satellite"
    scale = "4"

    time.sleep(5)
    center = str(lat) + "," + str(lon)
    print(center)
    # center = "22.0748941,87.341307"
    uri = url + "center=" + center + "&zoom=" + zoom + "&scale=" + scale + "&size=" + size + "&maptype=" + maptype + "&key=" + key
    r = requests.get(uri)
    img_file = "hello.png"
    f = open('mapp/image/' + img_file, 'wb')
    f.write(r.content)
    f.close()

    detections = detector.detectObjectsFromImage(
        input_image="mapp/image/hello.png",
        output_image_path="mapp/static/mapp/hello2.png",
        thread_safe=True)
    for detection in detections:
        print(detection["name"], " : ", detection["percentage_probability"],
              " : ", detection["box_points"])
def test_modal_manually(video_name):
    video_reader = cv2.VideoCapture(video_name)

    number_of_frames = int(video_reader.get(cv2.CAP_PROP_FRAME_COUNT))
    print(number_of_frames)

    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath("detection_model-ex-002--loss-0000.363.h5")
    detector.setJsonPath("detection_config.json")
    detector.loadModel()

    for i in range(number_of_frames):
        success, frame = video_reader.read()
        if success:
            key = cv2.waitKey(1) & 0xFF
            if key == ord("q"):
                break

            detected_image_array, detections = detector.detectObjectsFromImage(input_type="array", input_image=frame, output_type="array")
            best_detection = sorted(detections, key=itemgetter('percentage_probability'), reverse=True)[0]
            points = best_detection["box_points"]

            color = (0, 0, 255) if best_detection["name"] == 'not_scene_start' else (0, 255, 255)
            cv2.putText(frame, '{} [{}]'.format(best_detection["name"], best_detection["percentage_probability"]),
                        (points[0] + 50, points[1] + 50), cv2.FONT_HERSHEY_SIMPLEX, 2, color, 2)
            cv2.rectangle(frame, (points[0], points[1]), (points[2], points[3]), color, 2)
            cv2.imshow('Frame', frame)

    video_reader.release()
    cv2.destroyAllWindows()
Example #3
0
def on_init():
    global detector
    global labels
    global anchors

    gpus = tf.config.experimental.list_physical_devices('GPU')
    if gpus:
        # Restrict TensorFlow to only allocate 1GB of memory on the first GPU
        try:
            tf.config.experimental.set_virtual_device_configuration(
                gpus[0], [
                    tf.config.experimental.VirtualDeviceConfiguration(
                        memory_limit=2048)
                ])
            logical_gpus = tf.config.experimental.list_logical_devices('GPU')
            sys.stdout.write(
                f"{len(gpus)} Physical GPUs, {len(logical_gpus)} Logical GPUs\n"
            )
            sys.stdout.flush()
        except RuntimeError as e:
            # Virtual devices must be set before GPUs have been initialized
            sys.stdout.write(e)
            sys.stdout.flush()

    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath(detection_model_path=weights)
    detector.setJsonPath(configuration_json=config)
    detector.loadModel()

    detection_model_json = json.load(open(config))

    labels = detection_model_json["labels"]
    anchors = detection_model_json["anchors"]
    return True
Example #4
0
def upload():
    if request.method == 'POST':
        f = request.files['file']
        filename = secure_filename(f.filename)
        f.save(os.path.join(app.config["UPLOAD_PATH"], filename))
        detector = CustomObjectDetection()
        detector.setModelTypeAsYOLOv3()
        detector.setModelPath(
            "../images/models/detection_model-ex-059--loss-0006.886.h5")
        detector.setJsonPath("../images/json/detection_config.json")
        detector.loadModel()
        detections = detector.detectObjectsFromImage(
            input_image="static/" + f.filename,
            output_image_path="static/trashfire-" + f.filename,
            minimum_percentage_probability=30)
        image = Image.open("static/" + f.filename)
        for detection in detections:
            print(detection["name"], " : ",
                  detection["percentage_probability"], " : ",
                  detection["box_points"])
            cropped_img = image.crop(detection["box_points"])
            blurred_img = cropped_img.filter(
                ImageFilter.GaussianBlur(radius=20))
            image.paste(blurred_img, detection["box_points"])
            image.save("static/" + f.filename)
        return render_template('image.html',
                               image=f.filename,
                               timage="trashfire-" + f.filename)
    return 'boo'
Example #5
0
def detect_from_image():
    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath(detection_model_path=os.path.join(
        model_path, "detection_model-ex-33--loss-4.97.h5"))
    detector.setJsonPath(configuration_json=os.path.join(
        execution_path, "detection_config.json"))
    detector.loadModel()

    # image_name = "../fire-dataset/validation/images/small (2).jpg"
    # input_image = os.path.join(execution_path, image_name)
    # input_image = "/mnt/c/temp/FireDetection/FireNet/fire-dataset/train/images/small (107).jpg"
    # input_image = "/mnt/c/temp/FireDetection/FireNet/fire-dataset/validation/images/pic (27).jpg"
    # input_image = "/mnt/c/Dropbox/MATPapers/IMG_20201201_194602.jpg"
    input_image = "images/IMG_20201201_194602_10.jpg"
    # input_image = "/mnt/c/Users/Mahmood/Downloads/Test_Dataset1__Our_Own_Dataset(1)/Test_Dataset1__Our_Own_Dataset/Fire_2/firesamp29_frame25.jpg"
    # input_image = "/mnt/c/temp/FireDetection/FireNet/FireNET-master/images/fire-sunset-01_500.jpg"
    detections = detector.detectObjectsFromImage(
        input_image=input_image,
        output_image_path=os.path.join(execution_path, "Mahdi_kebrit3.jpg"),
        minimum_percentage_probability=10)

    for detection in detections:
        print(detection["name"], " : ", detection["percentage_probability"],
              " : ", detection["box_points"])
Example #6
0
def getCustom(request):
    if request.method == "POST":
        try:
            f = request.FILES['sentFile']  # here you get the files needed
        except:
            return render(request, 'homepage.html')
        execution_path = os.getcwd()
        modelPath = os.path.join(settings.MODELS,"detection_model.h5")
        configPath = os.path.join(settings.MODELS, "detection_config.json")
        detector = CustomObjectDetection()
        detector.setModelTypeAsYOLOv3()
        detector.setModelPath(modelPath)
        detector.setJsonPath(configPath)
        detector.loadModel()
        try:
            detections = detector.detectObjectsFromImage(input_image=f,
                                                     output_image_path='media/imagetest.jpg')
        except:
            return  render(request, 'failPredictions.html')

        item = []
        object = ''
        for eachObject in detections:
            item.append(eachObject["name"])
        categoryName = objectCategory.objects.filter(object__in=item).values_list('categoryName', flat=True)
        ac = AdvertisementCategory.objects.filter(id__in=categoryName)
        ads = Advertisement.objects.filter(categoryName__in=ac)
        context = {
            'ac': ac,
            'ads': ads,
        }
        return render(request, 'predictions.html', context)
    else:
        return render(request, 'homepage.html')
def keurmerk_predict(print_results=False, min_prob=30):
    """Predicts labels with trained model files stored in ../models.

    Keyword Arguments:
        print_results {bool} -- Optional print feedback of predicted labels
        (default: {False}).
    """

    # Model path variables
    dtc = CustomObjectDetection()
    dtc.setModelTypeAsYOLOv3()
    dtc.setModelPath(MODEL_PATH)
    dtc.setJsonPath(JSON_PATH)
    dtc.loadModel()

    for f in os.listdir(IMAGE_DIR):
        # Detect object in input image
        detections = dtc.detectObjectsFromImage(input_image=IMAGE_DIR + f,
                                                output_image_path=RESULTS_DIR + f,
                                                minimum_percentage_probability=min_prob)

        # Print detection results detected in input image
        if print_results is True:
            for detection in detections:
                print(f+"\n",
                      detection["name"], ":",
                      detection["percentage_probability"], ":",
                      detection["box_points"])
class FireDetection:
    def __init__(self):

        self.execution_path = "/home/swc/spark-2.4.5-bin-hadoop2.7/CCTV-pyspark/"

        self.detector = CustomObjectDetection()
        self.detector.setModelTypeAsYOLOv3()
        self.detector.setModelPath(detection_model_path=os.path.join(
            self.execution_path, "detection_model-ex-33--loss-4.97.h5"))
        self.detector.setJsonPath(configuration_json=os.path.join(
            self.execution_path, "detection_config.json"))
        self.detector.loadModel()

    def FireDetection(self, decoded_img):
        detections = self.detector.detectObjectsFromImage(
            input_image=decoded_img,
            input_type="array",
            output_image_path=os.path.join(self.execution_path,
                                           "fire_detected.jpg"),
            minimum_percentage_probability=40)

        if len(detections) == 0: fire_broken = False
        else: fire_broken = True

        return fire_broken
def detection(Image):
    name1 = "G:/capstone/ImageAI/take_picture/" + Image
    name2 = "G:/capstone/ImageAI/in_out/" + Image
    foldername = 'person'
    execution_path = 'G:/capstone/ImageAI/' + foldername
    points = []
    count = 0
    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath(
        os.path.join(execution_path, "models",
                     "detection_model-ex-216--loss-0003.244.h5"))
    detector.setJsonPath(
        os.path.join(execution_path, "json", "detection_config.json"))
    detector.loadModel()
    detections = detector.detectObjectsFromImage(input_image=name1,
                                                 output_image_path=name2)
    for detection in detections:
        #print(detection["name"], " : ", detection["percentage_probability"], " : ", detection["box_points"])
        #print("center : (", (detection["box_points"][0] + detection["box_points"][2]) / 2, ", ", detection["box_points"][3], ")")
        points.append([])
        for i in range(4):
            points[count].append(detection["box_points"][i])
        points[count].append(
            (detection["box_points"][0] + detection["box_points"][2]) // 2)
        points[count].append(detection["box_points"][3] - 10)
        count += 1
    return points
Example #10
0
    def Detection(self):
        from imageai.Detection.Custom import CustomObjectDetection
        import matplotlib.pyplot as plt
        from matplotlib.image import imread
        import os

        self.StatusBox.setText('Library Loading Finished. Run Detection.')

        PretrainedModel = self.WeightFileName
        self.outputImg = self.InputImgName[:-4] + '_output.jpg'

        detector = CustomObjectDetection()
        detector.setModelTypeAsYOLOv3()
        detector.setModelPath(PretrainedModel)
        detector.setJsonPath(self.jsonFileName)
        detector.loadModel()
        detectionImg = detector.detectObjectsFromImage(
            input_image=self.InputImgName,
            output_image_path=self.outputImg,
            minimum_percentage_probability=30)

        self.StatusBox.setText('Finished')

        for eachObject in detectionImg:
            print(eachObject["name"], " : ",
                  eachObject["percentage_probability"], " : ",
                  eachObject["box_points"])
Example #11
0
def simple_valid(model_path, json_path):
    parmas = sys.argv
    if len(parmas) <= 1:
        print('请输入要检测的类型,获取边界位置(box)或者判断目标是否存在(exist)')
        return

    if parmas[1] == 'exist' and len(parmas) <= 2:
        print('请输入目标label')
        return

    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath(os.path.join(execution_path, model_path))
    detector.setJsonPath(os.path.join(execution_path, json_path))
    detector.loadModel()

    detections = detector.detectObjectsFromImage(
        input_image=os.path.join(execution_path, parmas[2]),
        output_image_path=os.path.join(execution_path, parmas[3]))

    if parmas[1] == 'box':
        info = [{
            'name': eachObject["name"],
            'percent': str(eachObject["percentage_probability"]),
            'box': eachObject["box_points"]
        } for eachObject in detections]
        json_info = json.dumps(info)
        print(json_info)
    elif parmas[1] == 'exist':
        exist = False
        for eachObject in detections:
            if eachObject["name"] == parmas[2]:
                exist = True
                break
        print(exist)
Example #12
0
def setUpNN(model_path, json_path):
    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath(model_path)
    detector.setJsonPath(json_path)
    detector.loadModel()

    return detector
def load_model():
    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath(
        "tomato/models/detection_model-ex-052--loss-0033.691.h5")
    detector.setJsonPath("tomato/json/detection_config.json")
    detector.loadModel()

    return detector
def path(image):
    img = image
    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath("detection_model.h5")
    detector.setJsonPath("detection_config.json")
    detector.loadModel()
    detector.detectObjectsFromImage(input_image=img,
                                    output_image_path="mask-detected.jpg",
                                    display_percentage_probability=False)
Example #15
0
def detect_shoes(image_path):
    from imageai.Detection.Custom import CustomObjectDetection

    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath("../data/shoetect.h5")
    detector.setJsonPath("../data/detection_config.json")
    detector.loadModel()
    detections = detector.detectObjectsFromImage(input_image=image_path, output_image_path='../detected_images/image.jpg', minimum_percentage_probability=95)
    
    return [{'name': detection['name'], 'percentage_probability': detection['percentage_probability'], 'box_points': detection['box_points']} for detection in detections]
Example #16
0
def init():
    global detector

    execution_path = os.getcwd()
    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath(detection_model_path=os.path.join(
        execution_path, "detection_model-ex-33--loss-4.97.h5"))
    detector.setJsonPath(configuration_json=os.path.join(
        execution_path, "detection_config.json"))
    detector.loadModel()
Example #17
0
def deet(fold,best):
  detector = CustomObjectDetection()
  detector.setModelTypeAsYOLOv3()
  detector.setModelPath("Dataset{}/models/{}.h5".format(fold,best))
  detector.setJsonPath("Dataset{}/json/detection_config.json".format(fold))
  detector.loadModel()
  for ikl in [1,2,3,4,5,6]:
    detections = detector.detectObjectsFromImage("Dataset{}/test/T{}.jpg".format(fold,ikl), output_image_path="Dataset{}/test/T{}_detected.jpg".format(fold,ikl),nms_treshold=0.1, minimum_percentage_probability=30)
    print("T{}".format(ikl))
    for detection in detections:
      print(detection["name"], " : ", detection["percentage_probability"], " : ", detection["box_points"])
Example #18
0
class api:
    def __init__(self):
        self.detector = CustomObjectDetection()
        self.detector.setModelTypeAsYOLOv3()
        self.detector.setModelPath("detection_model-ex-046--loss-8.848.h5")
        self.detector.setJsonPath("detection1_config.json")
        self.detector.loadModel()
        self.username="******"
        self.password="******"
        self.data={
                "kadi" : f"{self.username}",
                "sifre" : f"{self.password}"
                  }
        self.baseurl="***" #http://blabla
        self.signin()
    def signin(self):
        self.s=requests.session()
        self.r=self.s.post(f"{self.baseurl}/api/giris",json=self.data)
        if self.r.status_code==200:
            self.getimageList()
        elif self.r.status_code==400:
            print("Kullanıcı adı veya parola geçersiz")
        else:
            print(self.r.status_code+"*???*"+self.r.content)

            
    def getimageList(self):
         self.jsonReq=self.s.get(f"{self.baseurl}/api/frame_listesi")
         with open("frame_list.txt","w") as fp:
             fp.write(self.jsonReq.text)
         print("json indi")
         self.sendimageData()
         
    def sendimageData(self):
        json_file = open('frame_list.txt')
        data = json.load(json_file)
        for do in data:
            a={"frame_id":do['frame_id'],"objeler":[]}
            img=imageio.imread(f"http://{do['frame_link']}")
            detections = self.detector.detectObjectsFromImage(input_type="array",input_image=img,output_type="array",thread_safe=True)
            for detection in detections[1]:
                a["objeler"].append({"tur":detection["name"],"x1":detection["box_points"][0],"y1":detection["box_points"][1],"x2":detection["box_points"][2],"y2":detection["box_points"][3]})   

            self.true=self.s.post(f"{self.baseurl}/api/cevap_gonder",json=a)
            print(f"[+] http://{do['frame_link']} "+str(self.true.status_code))
            a["objeler"].clear()
        
        print("Tüm resimler okundu")
        self.logout()

    def logout(self):
        self.s.get(f"{self.baseurl}/api/cikis")
def init_video_processing(configs):
    global global_configs, rekognition_client, image_ai_detector
    print("Initiated video processing")
    global_configs = configs
    session = boto3.Session(profile_name='rekognition')
    rekognition_client = session.client('rekognition', region_name='us-east-1')

    image_ai_detector = CustomObjectDetection()
    image_ai_detector.setModelTypeAsYOLOv3()
    image_ai_detector.setModelPath(
        "../model/detection_model-ex-002--loss-0000.363.h5")
    image_ai_detector.setJsonPath("../model/detection_config.json")
    image_ai_detector.loadModel()
Example #20
0
def detect_from_image():
    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath(detection_model_path=os.path.join(execution_path, "detection_model-ex-33--loss-4.97.h5"))
    detector.setJsonPath(configuration_json=os.path.join(execution_path, "detection_config.json"))
    detector.loadModel()

    detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path, "1.jpg"),
                                                 output_image_path=os.path.join(execution_path, "1-detected.jpg"),
                                                 minimum_percentage_probability=40)

    for detection in detections:
        print(detection["name"], " : ", detection["percentage_probability"], " : ", detection["box_points"])
Example #21
0
def detect(filepath):
    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath("set/models/detection_model-ex-013--loss-0016.700.h5")
    detector.setJsonPath("set/json/detection_config.json")
    detector.loadModel()
    detections = detector.detectObjectsFromImage(input_image=filepath, output_image_path="piwo2.png")
    for detection in detections:
        print(detection["name"], " : ", detection["percentage_probability"], " : ", detection["box_points"])
    if len(detections) > 0:
        return detections[0]["name"]
    else:
        return "piwo"
 def process_image(self, image_path_new, image_path_detected):
     detector = CustomObjectDetection()
     detector.setModelTypeAsYOLOv3()
     detector.setModelPath("detection_model-ex-013--loss-0015.740.h5")
     detector.setJsonPath("detection_config.json")
     detector.loadModel()
     detections = detector.detectObjectsFromImage(
         input_image=image_path_new, output_image_path=image_path_detected)
     print(str(len(detections)) + ' on image')
     for detection in detections:
         print(detection["name"], " : ",
               detection["percentage_probability"], " : ",
               detection["box_points"])
     return detections
Example #23
0
def detection():
    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    model_name = './model/' + parse.model_name
    detector.setModelPath(model_name)
    detector.setJsonPath("detection_config.json")
    detector.loadModel()
    input_file = './input_folder/' + parse.input_file
    output_file = './output_folder/' + parse.output_file
    detections = detector.detectObjectsFromImage(
        input_image=input_file,
        output_image_path=output_file,
        minimum_percentage_probability=parse.match_percentage)
    print(detections)
Example #24
0
def model_load(detection_model_path,
               json_path,
               cls_model_path,):
    
    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    
    detector.setModelPath(detection_model_path) 
    detector.setJsonPath(json_path)
    detector.loadModel()
    
    model = tf.keras.models.load_model(cls_model_path)
    
    return detector, model
Example #25
0
def main():
    if (len(sys.argv) < 2):
        print("Usage: " + sys.argv[0] +
              " <model_dir> [image_file] [threshold]")
        exit(-1)

    model_dir = sys.argv[1]

    if (len(sys.argv) > 2):
        image_name = sys.argv[2]
    else:
        print("Enter image or directory name: ")
        image_name = input()

    dest_dir = model_dir

    threshold = 0.75
    if (len(sys.argv) > 3):
        threshold = sys.argv[3]

    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath(os.path.join(model_dir, "model_berry.h5"))
    detector.setJsonPath(os.path.join(model_dir, "detection_config.json"))
    print("Loading model....")
    detector.loadModel()
    print("Model loaded, ready to detect me some berries!")

    if os.path.isdir(image_name):
        #it is a directory so iterate over all the images
        image_dir = image_name
        for file_name in os.listdir(image_dir):
            image_base_name, ext = os.path.splitext(file_name)
            if ext.lower() == '.jpg' or ext.lower() == '.png' or ext.lower(
            ) == '.jpeg':
                yolov3_detect_objects_and_show_image(
                    detector, os.path.join(image_dir, file_name), dest_dir)
            else:
                print("Skipping " + file_name)
    else:
        while len(image_name
                  ) > 0 and image_name != 'no' and image_name != 'exit':
            yolov3_detect_objects_and_show_image(detector, image_name,
                                                 dest_dir)
            print("Enter new image name (no or exit to quit): ")
            image_name = input()

    print("Done!")
Example #26
0
def detection():
    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath(detection_model_path=os.path.join(execution_path, "detection_model-ex-33--loss-4.97.h5"))
    detector.setJsonPath(configuration_json=os.path.join(execution_path, "detection_config.json"))
    detector.loadModel()
    while True:
        cam, image = q.get()
        detected_image, detected_data = detector.detectObjectsFromImage(input_image=image,
                                        input_type="array",
                                        output_type="array",
                                        minimum_percentage_probability=40)
        cv2.imshow(f"video : {cam}", detected_image)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        print(image.shape)
class items():
    def __init__(self, detectorModel, setJson):
        self.detector = CustomObjectDetection()
        self.detector.setModelPath(detectorModel)
        self.detector.setJsonPath(setJson)
        self.detector.loadModel()
    
    def items_draw(self, frame):
        detected_image, detections = self.detector.detectObjectsFromImage(input_image=frame,input_type="array",output_type="array")
        for detection in detections:
            print(detection["name"], " : ", detection["percentage_probability"])
            (x1,y1,x2,y2) = detection["box_points"]
            print("x1: ", x1," - y1: ", y1," - x2: ", x2," - y2: ", y2)
            cv2.rectangle(frame,(x1,y1),(x2,y2),(0,0,255),2)
            font = cv2.FONT_HERSHEY_DUPLEX
            cv2.putText(frame, detection["name"],(x1 + 6, y1 - 6), font, 1.0, (255,255,255), 1)
Example #28
0
def detector_model():
    model_path = 'detection_model-ex-005--loss-0003.767.h5'
    json_path = 'model/detection_config.json'

    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath(model_path)
    detector.setJsonPath(json_path)
    detector.loadModel()
    detections = detector.detectObjectsFromImage(
        input_image="uploaded.jpg", output_image_path='nplate3-detected.jpg')
    for obj in detections:
        print('hi')
        x, y, w, h = obj['box_points']
    lpimg = cv2.imread("uploaded.jpg")
    crop_img = lpimg[y:h, x:w]
    return crop_img
    def recognize_custom(image_path, vehicle_type, isVideo):
        if vehicle_type == 'TANK':
            model_name = 'tank_model_3_loss-0008.h5'
            json_name = 'tank_detection_config.json'
        elif vehicle_type == 'APC':
            model_name = 'apc_model_6_loss-0012.h5'
            json_name = 'apc_detection_config.json'
        elif vehicle_type == 'SHIP':
            print('3')
        elif vehicle_type == 'AERO':
            print('4')
        folder_path = str(
            os.getcwd()) + "\\recognize_app\\rec_api\\imageairecognizer\\"

        if isVideo == False:
            detector = CustomObjectDetection()
            detector.setModelTypeAsYOLOv3()
            detector.setModelPath(folder_path + model_name)
            detector.setJsonPath(folder_path + json_name)
            detector.loadModel()
            detector = detector.detectObjectsFromImage(
                input_image=image_path,
                output_image_path=image_path,
                minimum_percentage_probability=30)

        else:
            video_detector = CustomVideoObjectDetection()
            video_detector.setModelTypeAsYOLOv3()
            video_detector.setModelPath(folder_path + model_name)
            video_detector.setJsonPath(folder_path + json_name)
            video_detector.loadModel()
            print(Path(image_path).stem)
            video_detector = video_detector.detectObjectsFromVideo(
                input_file_path=image_path,
                output_file_path=image_path,
                minimum_percentage_probability=30,
                frames_per_second=30,
                log_progress=True)

            os.remove(image_path)
            p = Path(video_detector)
            FILE_NAME = p.with_suffix('').with_suffix('').name
            os.popen(
                "ffmpeg -i {input} -ac 2 -b:v 2000k -c:a aac -c:v libx264 -b:a 160k -vprofile high -bf 0 -strict experimental -f mp4 {output}.mp4"
                .format(input=p,
                        output='.\media\{0}'.format(FILE_NAME))).close()
Example #30
0
def get_health(image):
    detector = CustomObjectDetection()
    detector.setModelTypeAsYOLOv3()
    detector.setModelPath("models/detection_model-ex-046--loss-0006.159.h5")
    detector.setJsonPath("json/detection_config.json")
    detector.loadModel()
    detections = detector.detectObjectsFromImage(input_image=image,
                                                 input_type="array",
                                                 output_type="array")
    for detection in detections[1]:
        print(detection["name"], " : ", detection["percentage_probability"],
              " : ", detection["box_points"])
    cv2.imshow("frame", detections[0])
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    return detections[1]