Ejemplo n.º 1
0
 def __init__(self, yolo_dir, mode=0):
 
     #darknet.set_gpu(gpu_num)
     self.metaMain = None
     self.netMain = None
     altNames = None
     configPath = None
     weightPath = None
     # Use tiny yolov3
     if(mode == 0):
         configPath = os.path.join(yolo_dir, "cfg/tiny-yolo.cfg")
         weightPath = os.path.join(yolo_dir, "yolov3-tiny.weights")
     # Use yolov3
     elif(mode == 1):
         configPath = os.path.join(yolo_dir, "cfg/yolov3.cfg")
         weightPath = os.path.join(yolo_dir, "yolov3.weights")
     
     metaPath = os.path.join(yolo_dir, "cfg/coco.data")
     if not os.path.exists(configPath):
         raise ValueError("Invalid config path `" +
                             os.path.abspath(configPath)+"`")
     if not os.path.exists(weightPath):
         raise ValueError("Invalid weight path `" +
                             os.path.abspath(weightPath)+"`")
     if not os.path.exists(metaPath):
         raise ValueError("Invalid data file path `" +
                             os.path.abspath(metaPath)+"`")
     if self.netMain is None:
         self.netMain = darknet.load_net_custom(configPath.encode(
             "ascii"), weightPath.encode("ascii"), 0, 1)  # batch size = 1
     if self.metaMain is None:
         self.metaMain = darknet.load_meta(metaPath.encode("ascii"))
     if altNames is None:
         try:
             with open(metaPath) as metaFH:
                 metaContents = metaFH.read()
                 import re
                 match = re.search("names *= *(.*)$", metaContents,
                                     re.IGNORECASE | re.MULTILINE)
                 if match:
                     result = match.group(1)
                 else:
                     result = None
                 try:
                     if os.path.exists(result):
                         with open(result) as namesFH:
                             namesList = namesFH.read().strip().split("\n")
                             altNames = [x.strip() for x in namesList]
                 except TypeError as e:
                     print(e)
                     pass
         except Exception as e:
             print(e)
             pass
     
     self.darknet_image = darknet.make_image(darknet.network_width(self.netMain),
                                     darknet.network_height(self.netMain),3)
Ejemplo n.º 2
0
    def _initialize_darknet(self):

        # Setup paths
        inputDir = os.path.join(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
            "input")
        configPath = os.path.join(inputDir, "yolov3.cfg")
        weightPath = os.path.join(
            inputDir,
            "card.weights")  # Don't change this - change the file name instead
        metaPath = os.path.join(inputDir, "obj.data")
        setupObjPaths(metaPath, os.path.join(inputDir, "obj.names"))

        if not os.path.exists(weightPath):
            print(f"Couldn't find weights path '{weightPath}'")
            sys.exit(101)

        self._darknet_netMain = darknet.load_net_custom(
            configPath.encode("ascii"), weightPath.encode("ascii"), 0,
            1)  # batch size = 1
        self._darknet_metaMain = darknet.load_meta(metaPath.encode("ascii"))

        print("Finished loading")

        # Not sure what is going on here?
        try:
            with open(metaPath) as metaFH:
                metaContents = metaFH.read()
                import re
                match = re.search("names *= *(.*)$", metaContents,
                                  re.IGNORECASE | re.MULTILINE)
                if match:
                    result = match.group(1)
                else:
                    result = None
                try:
                    if os.path.exists(result):
                        with open(result) as namesFH:
                            namesList = namesFH.read().strip().split("\n")
                            altNames = [x.strip() for x in namesList]
                except TypeError as e:
                    print(e)
                    sys.exit(1337)
        except Exception as e:
            print(e)
            sys.exit(1337)

        self._darknet_resolution = (darknet.network_width(
            self._darknet_netMain),
                                    darknet.network_height(
                                        self._darknet_netMain))
        self._darknet_image = darknet.make_image(self._darknet_resolution[0],
                                                 self._darknet_resolution[1],
                                                 3)
Ejemplo n.º 3
0
    def setup(self, netMain=None, metaMain=None, altNames=None):
        # Load the model
        if netMain is None:
            self.netMain = darknet.load_net_custom(
                self.configPath.encode('ascii'),
                self.weightPath.encode('ascii'), 0, 1)  # batch size = 1
        else:
            self.netMain = netMain

        if metaMain is None:
            self.metaMain = darknet.load_meta(self.metaPath.encode('ascii'))
        else:
            self.metaMain = metaMain

        if altNames is None:
            try:
                with open(self.metaPath) as metaFH:
                    metaContents = metaFH.read()
                    import re
                    match = re.search('names *= *(.*)$', metaContents,
                                      re.IGNORECASE | re.MULTILINE)
                    if match: result = match.group(1)
                    else: result = None
                    try:
                        if osp.exists(result):
                            with open(result) as namesFH:
                                namesList = namesFH.read().strip().split('\n')
                                self.altNames = [x.strip() for x in namesList]
                    except TypeError:
                        pass
            except Exception:
                pass
        else:
            self.altNames = altNames

        # Create an image we reuse for each detect
        self.darknet_image = darknet.make_image(
            darknet.network_width(self.netMain),
            darknet.network_height(self.netMain), 3)

        # Performance logging
        self.count = 0
        self.total = 0
Ejemplo n.º 4
0
import sys, os
sys.path.append('../../darknet')
import darknet.darknet as dn

from server import app, is_authenticated
from flask import request, render_template

# load YOLOv4 model
MODEL_CFG = 'darknet/custom5-512.cfg'
MODEL_WEIGHTS = 'darknet/custom5-512.weights'
MODEL_DATA = 'darknet/custom5-512.data'

net = dn.load_net_custom(str.encode(MODEL_CFG), str.encode(MODEL_WEIGHTS), 0,
                         1)
meta = dn.load_meta(str.encode(MODEL_DATA))

# start Flask Server
from flask import Flask, jsonify, request, render_template
from werkzeug.utils import secure_filename
from flask_cors import CORS
import uuid
from PIL import Image

ALLOWED_EXTENSIONS = {'png', 'jpg'}


#utils
def allowed_file(filename):
    return '.' in filename and filename.rsplit(
        '.', 1)[1].lower() in ALLOWED_EXTENSIONS
Ejemplo n.º 5
0
def YOLO():

    global metaMain, netMain, altNames
    configPath = "requirements/yolov3_custom.cfg"
    weightPath = "weights/yolov3_custom_last.weights"
    metaPath = "requirements/detector.data"
    if not os.path.exists(configPath):
        raise ValueError("Invalid config path `" +
                         os.path.abspath(configPath) + "`")
    if not os.path.exists(weightPath):
        raise ValueError("Invalid weight path `" +
                         os.path.abspath(weightPath) + "`")
    if not os.path.exists(metaPath):
        raise ValueError("Invalid data file path `" +
                         os.path.abspath(metaPath) + "`")
    if netMain is None:
        netMain = darknet.load_net_custom(configPath.encode("ascii"),
                                          weightPath.encode("ascii"), 0,
                                          1)  # batch size = 1
    if metaMain is None:
        metaMain = darknet.load_meta(metaPath.encode("ascii"))
    if altNames is None:
        try:
            with open(metaPath) as metaFH:
                metaContents = metaFH.read()
                import re
                match = re.search("names *= *(.*)$", metaContents,
                                  re.IGNORECASE | re.MULTILINE)
                if match:
                    result = match.group(1)
                else:
                    result = None
                try:
                    if os.path.exists(result):
                        with open(result) as namesFH:
                            namesList = namesFH.read().strip().split("\n")
                            altNames = [x.strip() for x in namesList]
                except TypeError:
                    pass
        except Exception:
            pass
    #cap = cv2.VideoCapture(0)
    videopath = argv[1]
    if os.path.exists(videopath):
        name = videopath.split('/')[-1].split('.')[0]
        cap = cv2.VideoCapture(videopath)
    else:
        print("Incorrect path to video")
        return
    cap.set(3, 1280)
    cap.set(4, 720)
    out = cv2.VideoWriter(
        "detections/" + name + "_output.avi", cv2.VideoWriter_fourcc(*"MJPG"),
        10.0,
        (darknet.network_width(netMain), darknet.network_height(netMain)))
    print("Starting the YOLO loop...")

    # Create an image we reuse for each detect
    darknet_image = darknet.make_image(darknet.network_width(netMain),
                                       darknet.network_height(netMain), 3)
    while True:
        prev_time = time.time()
        ret, frame_read = cap.read()
        frame_rgb = cv2.cvtColor(frame_read, cv2.COLOR_BGR2RGB)
        frame_resized = cv2.resize(
            frame_rgb,
            (darknet.network_width(netMain), darknet.network_height(netMain)),
            interpolation=cv2.INTER_LINEAR)

        darknet.copy_image_from_bytes(darknet_image, frame_resized.tobytes())

        detections = darknet.detect_image(netMain,
                                          metaMain,
                                          darknet_image,
                                          thresh=0.1)
        image = cvDrawBoxes(detections, frame_resized)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        print(1 / (time.time() - prev_time))
    cap.release()
    out.release()
Ejemplo n.º 6
0
def YOLO():

    global metaMain, netMain, altNames
    configPath = "Configuration/yolov4_obj.cfg"
    weightPath = "Weights/yolov4_obj_final.weights"
    metaPath = "Configuration/detector.data"
    if not os.path.exists(configPath):
        raise ValueError("Invalid config path `" +
                         os.path.abspath(configPath) + "`")
    if not os.path.exists(weightPath):
        raise ValueError("Invalid weight path `" +
                         os.path.abspath(weightPath) + "`")
    if not os.path.exists(metaPath):
        raise ValueError("Invalid data file path `" +
                         os.path.abspath(metaPath) + "`")
    if netMain is None:
        netMain = darknet.load_net_custom(configPath.encode("ascii"),
                                          weightPath.encode("ascii"), 0,
                                          1)  # batch size = 1
    if metaMain is None:
        metaMain = darknet.load_meta(metaPath.encode("ascii"))
    if altNames is None:
        try:
            with open(metaPath) as metaFH:
                metaContents = metaFH.read()
                import re
                match = re.search("names *= *(.*)$", metaContents,
                                  re.IGNORECASE | re.MULTILINE)
                if match:
                    result = match.group(1)
                else:
                    result = None
                try:
                    if os.path.exists(result):
                        with open(result) as namesFH:
                            namesList = namesFH.read().strip().split("\n")
                            altNames = [x.strip() for x in namesList]
                except TypeError:
                    pass
        except Exception:
            pass
    #cap = cv2.VideoCapture(0)
    imagepath = argv[1]
    if os.path.exists(imagepath):
        name = imagepath.split('/')[-1].split('.')[0]
        frame_read = cv2.imread(imagepath)
    else:
        print("Incorrect path to image")
        return
    print("Starting the YOLO loop...")

    inputshape = (darknet.network_width(netMain),
                  darknet.network_height(netMain))

    darknet_image = darknet.make_image(inputshape[0], inputshape[1], 3)
    prev_time = time.time()
    frame_rgb = cv2.cvtColor(frame_read, cv2.COLOR_BGR2RGB)
    frame_resized = cv2.resize(frame_rgb,
                               inputshape,
                               interpolation=cv2.INTER_LINEAR)

    darknet.copy_image_from_bytes(darknet_image, frame_resized.tobytes())

    detections = darknet.detect_image(netMain,
                                      metaMain,
                                      darknet_image,
                                      thresh=0.2)
    image = cvDrawBoxes(detections, frame_rgb, inputshape)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    print("FPS : ", end='')
    print(1.0 / (time.time() - prev_time))
    cv2.imwrite(name + "_output.jpg", image)
Ejemplo n.º 7
0
configPath = "./darknet/cfg/obj.cfg"
weightPath = "./darknet/obj_last_yolov3.weights"
metaPath = "./darknet/cfg/obj.data"
if not os.path.exists(configPath):
    raise ValueError("Invalid config path `" + os.path.abspath(configPath) +
                     "`")
if not os.path.exists(weightPath):
    raise ValueError("Invalid weight path `" + os.path.abspath(weightPath) +
                     "`")
if not os.path.exists(metaPath):
    raise ValueError("Invalid data file path `" + os.path.abspath(metaPath) +
                     "`")
if netMain is None:
    netMain = darknet.load_net_custom(configPath.encode("utf-8"),
                                      weightPath.encode("utf-8"), 0,
                                      1)  # batch size = 1
if metaMain is None:
    metaMain = darknet.load_meta(metaPath.encode("ascii"))
if altNames is None:
    try:
        with open(metaPath) as metaFH:
            metaContents = metaFH.read()
            import re
            match = re.search("names *= *(.*)$", metaContents,
                              re.IGNORECASE | re.MULTILINE)
            if match:
                result = match.group(1)
            else:
                result = None
            try:
Ejemplo n.º 8
0
def main():

    global metaMain, netMain, altNames
    configPath = "darknet/cfg/yolov3-seabird.cfg"
    weightPath = "darknet/backup_608/yolov3-seabird_final.weights"
    metaPath = "darknet/cfg/seabird.data"
    if not os.path.exists(configPath):
        raise ValueError("Invalid config path `" +
                         os.path.abspath(configPath)+"`")
    if not os.path.exists(weightPath):
        raise ValueError("Invalid weight path `" +
                         os.path.abspath(weightPath)+"`")
    if not os.path.exists(metaPath):
        raise ValueError("Invalid data file path `" +
                         os.path.abspath(metaPath)+"`")
    if netMain is None:
        netMain = darknet.load_net_custom(configPath.encode(
            "ascii"), weightPath.encode("ascii"), 0, 1)  # batch size = 1
    if metaMain is None:
        metaMain = darknet.load_meta(metaPath.encode("ascii"))
    if altNames is None:
        try:
            with open(metaPath) as metaFH:
                metaContents = metaFH.read()
                import re
                match = re.search("names *= *(.*)$", metaContents,
                                  re.IGNORECASE | re.MULTILINE)
                if match:
                    result = match.group(1)
                else:
                    result = None
                try:
                    if os.path.exists(result):
                        with open(result) as namesFH:
                            namesList = namesFH.read().strip().split("\n")
                            altNames = [x.strip() for x in namesList]
                except TypeError:
                    pass
        except Exception:
            pass


   # Definition of the parameters
    max_cosine_distance = 0.3
    max_euclidean_distance = 150.0
    nn_budget = None
    nms_max_overlap = 1
   # deep_sort 
    
    metric = nn_matching.NearestNeighborDistanceMetric("euclidean", max_euclidean_distance, nn_budget)
    #metric = nn_matching.NearestNeighborDistanceMetric("cosine", max_cosine_distance, nn_budget)
    tracker = Tracker(metric)

    writeVideo_flag = False
    
    #video_capture = cv2.VideoCapture('/data/Farallon3_20190706_000001_No001.avi')
    #video_capture = cv2.VideoCapture('/data/15_fps/Farallon3_20190620_021546_No001.mp4')
    video_capture = cv2.VideoCapture('/data/15_fps/Farallon3_20190621_090300_No004.mp4')
    #video_capture = cv2.VideoCapture('/data/rows_data/15_fps/Farallon3_20190603_155007_No001.avi')

    video_fps = video_capture.get(cv2.CAP_PROP_FPS)
    #video_fps = 25
    list_file = open('events.csv', 'w')
    track_log_file = open('track_log.csv', 'w')
    wr = csv.writer(list_file, dialect='excel')
    wr_tracklog = csv.writer(track_log_file, dialect='excel')
    if writeVideo_flag:
    # Define the codec and create VideoWriter object
        w = int(video_capture.get(3))
        h = int(video_capture.get(4))
        fourcc = cv2.VideoWriter_fourcc(*'MJPG')
        out = cv2.VideoWriter('1.avi', fourcc, 15, (w, h))
        zone = cv2.imread('mask/test_zone.png', -1)
     # Create an image we reuse for each detect
    darknet_image = darknet.make_image(darknet.network_width(netMain),
                                    darknet.network_height(netMain),3)
    
    fps = 0.0
    frame_index = -1 
    mask = cv2.imread('mask/mask_new.jpg')
    mask = np.uint8(mask/255)
    ##############################################
    #points = [(130,102),(535,370),(808,345),(1570,391),(1494,808),(373,817),(4,496),(1,276)]
    #points = [(4,22),(121,96),(207,99),(537,366),(819,324),(1564,385),(1764,322),(1648,889),(105,915),(3,762)]
    points = [(2,24),(127,24),(579,321),(1746,336),(1674,878),(1912,957),(1926,1081),(2,1074)]
    zone_polygon = Polygon(points)
    text_count_size = 9e-3 * 200
    text_count_x,text_count_y = 550,  1000
    avg_area_box_all_frames = 0
    time_stamp = datetime(2019, 6, 21, 10, 33, 5) 
    
    while True:
        ret, frame = video_capture.read()  # frame shape 640*480*3
        if ret != True:
            break
        frame_index = frame_index +1  
        t1 = time.time()
        write = 0 
        if frame_index % 15 == 0:
           write = 1 
            
        draw_frame  = frame 
        frame = np.multiply(frame, mask)
        # image = Image.fromarray(frame)
        #image = Image.fromarray(frame[...,::-1]) #bgr to rgb
        
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        frame_resized = cv2.resize(frame_rgb,
                                   (darknet.network_width(netMain),
                                    darknet.network_height(netMain)),
                                   interpolation=cv2.INTER_LINEAR)
        darknet.copy_image_from_bytes(darknet_image,frame_resized.tobytes())
        detections = darknet.detect_image(netMain, metaMain, darknet_image, thresh=0.5)

        boxs, class_ids=convert(detections, dw, dh)
        
        # score to 1.0 here).
        dets = [Detection(bbox, 1.0, class_id) for bbox,class_id in zip(boxs, class_ids)]
        
        # Run non-maxima suppression.
        boxes = np.array([d.tlwh for d in dets])
        scores = np.array([d.confidence for d in dets])
        indices = preprocessing.non_max_suppression(boxes, nms_max_overlap, scores)
        detections_tracker = [dets[i] for i in indices]
        ids = [class_ids[i] for i in indices]
        time_lapsed_sec = frame_index / video_fps
        time_stamp_now = time_stamp + timedelta(seconds=time_lapsed_sec) 

        # Call the tracker
        tracker.predict()
        tracker.update(detections_tracker, ids, time_stamp_now)
        tracker.update_events(draw_frame, time_stamp_now, wr, wr_tracklog, write )
   
        avg_area_box = 0
        for det in detections:
            name , x, y, w, h = det[0],det[2][0],det[2][1],det[2][2],det[2][3]
            class_id = altNames.index(name.decode("utf-8") )
            bbox = [(x-w/2)*dw,(y-h/2)*dh,(x+w/2)*dw,(y+h/2)*dh]
            area_box = w*h*dw*dh
            if area_box > 3*avg_area_box_all_frames:
                 cv2.rectangle(draw_frame,(int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])),(255,255,255), 3)
                 cv2.putText(draw_frame,"Flapping detected !!!!",(text_count_x,text_count_y),4,text_count_size, (255,0,0),4) 
            avg_area_box = avg_area_box + area_box
            cv2.rectangle(draw_frame,(int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])),get_rgb(class_id,3), 2)
        avg_area_box = avg_area_box/len(detections)
        avg_area_box_all_frames=avg_area_box 
        
        if writeVideo_flag:
            # save a frame
            out.write(draw_frame)
      
        fps  = ( fps + (1./(time.time()-t1)) ) / 2
        print("fps= %f"%(fps))
        

    video_capture.release()
    if writeVideo_flag:
        out.release()
        list_file.close()
    cv2.destroyAllWindows()
Ejemplo n.º 9
0
def YOLO():
    #os.chdir("./darknet")
    #os.system("pwd")
    #print('dir changed!')

    from darknet import darknet
    print("Imported")
    #================================================================
    base_dir = get_base_dir()
    image_list = read_image()
    #=================================================================#
    # Read parking regions file
    parked_cars = read_regions()
    #================================================================
    global metaMain, netMain, altNames
    configPath = "./darknet/cfg/yolov4.cfg"
    weightPath = "./darknet/yolov4.weights"
    metaPath = "./darknet/cfg/coco.data"
    if not os.path.exists(configPath):
        raise ValueError("Invalid config path `" +
                         os.path.abspath(configPath) + "`")
    if not os.path.exists(weightPath):
        raise ValueError("Invalid weight path `" +
                         os.path.abspath(weightPath) + "`")
    if not os.path.exists(metaPath):
        raise ValueError("Invalid data file path `" +
                         os.path.abspath(metaPath) + "`")
    if netMain is None:
        netMain = darknet.load_net_custom(configPath.encode("ascii"),
                                          weightPath.encode("ascii"), 0,
                                          1)  # batch size = 1
    if metaMain is None:
        metaMain = darknet.load_meta(metaPath.encode("ascii"))
    if altNames is None:
        try:
            with open(metaPath) as metaFH:
                metaContents = metaFH.read()
                import re
                match = re.search("names *= *(.*)$", metaContents,
                                  re.IGNORECASE | re.MULTILINE)
                if match:
                    result = match.group(1)
                else:
                    result = None
                try:
                    if os.path.exists(result):
                        with open(result) as namesFH:
                            namesList = namesFH.read().strip().split("\n")
                            altNames = [x.strip() for x in namesList]
                except TypeError:
                    pass
        except Exception:
            pass
    # i = 0
    # while True:
    for i in range(len(image_list)):
        image = cv2.imread(image_list[i])
        width = image.shape[1]
        height = image.shape[0]

        # Create an image we reuse for each detect
        darknet_image = darknet.make_image(width, height, 3)

        image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        image_rgb = cv2.resize(image_rgb, (width, height),
                               interpolation=cv2.INTER_LINEAR)

        darknet.copy_image_from_bytes(darknet_image, image_rgb.tobytes())

        detections = darknet.detect_image(netMain,
                                          metaMain,
                                          darknet_image,
                                          thresh=0.25)
        # Print detections
        # image = cvDrawBoxesonCars(detections, image_rgb)
        # image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        # Draw occupied parking spaces
        image, parked_cars_updated = cvOverlapcheck(parked_cars, detections,
                                                    image_rgb)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        from cv2 import imwrite
        file2 = os.path.join(base_dir +
                             '/Api/templates/static/images/new_output.jpg')
        imwrite(file2, image)
        print("Image saved!")

        # cv2.imshow('Output', image)
        cv2.waitKey(0)
        # i += 1
    cv2.destroyAllWindows()
    #================================================================
    # Save the file with occupancy
    post_process(parked_cars_updated)
Ejemplo n.º 10
0
def YOLO():

    global metaMain, netMain, altNames
    configPath = "Configuration/yolov4_obj.cfg"
    weightPath = "Weights/yolov4_obj_final.weights"
    metaPath = "Configuration/detector.data"
    if not os.path.exists(configPath):
        raise ValueError("Invalid config path `" +
                         os.path.abspath(configPath) + "`")
    if not os.path.exists(weightPath):
        raise ValueError("Invalid weight path `" +
                         os.path.abspath(weightPath) + "`")
    if not os.path.exists(metaPath):
        raise ValueError("Invalid data file path `" +
                         os.path.abspath(metaPath) + "`")
    if netMain is None:
        netMain = darknet.load_net_custom(configPath.encode("ascii"),
                                          weightPath.encode("ascii"), 0,
                                          1)  # batch size = 1
    if metaMain is None:
        metaMain = darknet.load_meta(metaPath.encode("ascii"))
    if altNames is None:
        try:
            with open(metaPath) as metaFH:
                metaContents = metaFH.read()
                import re
                match = re.search("names *= *(.*)$", metaContents,
                                  re.IGNORECASE | re.MULTILINE)
                if match:
                    result = match.group(1)
                else:
                    result = None
                try:
                    if os.path.exists(result):
                        with open(result) as namesFH:
                            namesList = namesFH.read().strip().split("\n")
                            altNames = [x.strip() for x in namesList]
                except TypeError:
                    pass
        except Exception:
            pass
    videopath = argv[1]
    if os.path.exists(videopath):
        name = videopath.split('/')[-1].split('.')[0]
        cap = cv2.VideoCapture(videopath)
    else:
        print("Incorrect path to video")
        return
    cap = cv2.VideoCapture(videopath)
    fps = cap.get(cv2.CAP_PROP_FPS)
    print(fps)
    cap.set(3, 1280)
    cap.set(4, 720)
    ret, frame_read = cap.read()
    out = cv2.VideoWriter(name + "_output.avi",
                          cv2.VideoWriter_fourcc(*"MJPG"), fps,
                          (frame_read.shape[1], frame_read.shape[0]))
    print("Starting the YOLO loop...")

    inputshape = (darknet.network_width(netMain),
                  darknet.network_height(netMain))
    # Create an image we reuse for each detect
    darknet_image = darknet.make_image(inputshape[0], inputshape[1], 3)

    start = time.time()
    cnt = 1
    while ret:
        cnt += 1
        prev_time = time.time()
        if ret:
            frame_rgb = cv2.cvtColor(frame_read, cv2.COLOR_BGR2RGB)
            frame_resized = cv2.resize(frame_rgb,
                                       inputshape,
                                       interpolation=cv2.INTER_LINEAR)

            darknet.copy_image_from_bytes(darknet_image,
                                          frame_resized.tobytes())

            detections = darknet.detect_image(netMain,
                                              metaMain,
                                              darknet_image,
                                              thresh=0.25)
            image = cvDrawBoxes(detections, frame_rgb, inputshape)
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            print(1 / (time.time() - prev_time))
            out.write(image)

        ret, frame_read = cap.read()
        # cv2.imshow('Demo', image)     #uncomment if running on local machine
        # cv2.waitKey(3)    #uncomment if running on local machine
    print()
    print("Average FPS : ", end='')
    print(cnt * 1.0 / (time.time() - start))
    cap.release()
    out.release()
            str(round(detection[1] * 100, 2)) + "]", (pt1[0], pt1[1] - 5),
            cv2.FONT_HERSHEY_SIMPLEX, 0.5, [0, 255, 0], 2)
    return img


netMain = None
metaMain = None
altNames = None

# YOLO parameters
config = "cfg/igvc-yolov3.cfg"
weights = "igvc-yolov3_6000.weights"
names = "data/igvc.names"

netMain = darknet.load_net_custom(config.encode("ascii"),
                                  weights.encode("ascii"), 0,
                                  1)  # batch size = 1
#metaMain = darknet.load_meta(data.encode("ascii"))
altNames = [x.strip() for x in open(names, 'r').readlines()]


def get_distance(depth_val):
    '''
    Old get_distance function. 
    '''
    return 250.477 * depth_val**(-1.1504)


# Create stereo matcher
window_size = 17
left_matcher = cv2.StereoSGBM_create(