Exemple #1
0
def run():
    '''
    Initialize counter class and run counting loop.
    '''

    import ast
    import os
    import time
    import cv2

    from util.image import take_screenshot
    from util.logger import get_logger
    from util.debugger import mouse_callback
    from VehicleCounter import VehicleCounter

    logger = get_logger()

    # capture traffic scene video
    is_cam = ast.literal_eval(os.getenv('IS_CAM'))
    video = int(os.getenv('VIDEO')) if is_cam else os.getenv('VIDEO')
    cap = cv2.VideoCapture(video)
    if not cap.isOpened():
        raise Exception('Invalid video source {0}'.format(video))
    ret, frame = cap.read()
    f_height, f_width, _ = frame.shape

    detection_interval = int(os.getenv('DI'))
    mcdf = int(os.getenv('MCDF'))
    mctf = int(os.getenv('MCTF'))
    detector = os.getenv('DETECTOR')
    tracker = os.getenv('TRACKER')
    # create detection region of interest polygon
    use_droi = ast.literal_eval(os.getenv('USE_DROI'))
    droi = ast.literal_eval(os.getenv('DROI')) \
            if use_droi \
            else [(0, 0), (f_width, 0), (f_width, f_height), (0, f_height)]
    show_droi = ast.literal_eval(os.getenv('SHOW_DROI'))
    counting_lines = ast.literal_eval(os.getenv('COUNTING_LINES'))
    show_counts = ast.literal_eval(os.getenv('SHOW_COUNTS'))

    vehicle_counter = VehicleCounter(frame, detector, tracker, droi, show_droi,
                                     mcdf, mctf, detection_interval,
                                     counting_lines, show_counts)

    record = ast.literal_eval(os.getenv('RECORD'))
    headless = ast.literal_eval(os.getenv('HEADLESS'))

    if record:
        # initialize video object to record counting
        output_video = cv2.VideoWriter(os.getenv('OUTPUT_VIDEO_PATH'), \
                                        cv2.VideoWriter_fourcc(*'MJPG'), \
                                        30, \
                                        (f_width, f_height))

    logger.info('Processing started.',
                extra={
                    'meta': {
                        'label': 'START_PROCESS',
                        'counter_config': {
                            'di': detection_interval,
                            'mcdf': mcdf,
                            'mctf': mctf,
                            'detector': detector,
                            'tracker': tracker,
                            'use_droi': use_droi,
                            'droi': droi,
                            'show_droi': show_droi,
                            'counting_lines': counting_lines
                        },
                    },
                })

    if not headless:
        # capture mouse events in the debug window
        cv2.namedWindow('Debug')
        cv2.setMouseCallback('Debug', mouse_callback, {
            'frame_width': f_width,
            'frame_height': f_height
        })

    is_paused = False
    output_frame = None

    # main loop
    while is_cam or cap.get(cv2.CAP_PROP_POS_FRAMES) + 1 < cap.get(
            cv2.CAP_PROP_FRAME_COUNT):
        k = cv2.waitKey(1) & 0xFF
        if k == ord('p'):  # pause/play loop if 'p' key is pressed
            is_paused = False if is_paused else True
            logger.info('Loop paused/played.',
                        extra={
                            'meta': {
                                'label': 'PAUSE_PLAY_LOOP',
                                'is_paused': is_paused
                            }
                        })
        if k == ord(
                's'
        ) and output_frame is not None:  # save frame if 's' key is pressed
            take_screenshot(output_frame)
        if k == ord('q'):  # end video loop if 'q' key is pressed
            logger.info('Loop stopped.',
                        extra={'meta': {
                            'label': 'STOP_LOOP'
                        }})
            break

        if is_paused:
            time.sleep(0.5)
            continue

        _timer = cv2.getTickCount(
        )  # set timer to calculate processing frame rate

        if ret:
            vehicle_counter.count(frame)
            output_frame = vehicle_counter.visualize()

            if record:
                output_video.write(output_frame)

            if not headless:
                debug_window_size = ast.literal_eval(
                    os.getenv('DEBUG_WINDOW_SIZE'))
                resized_frame = cv2.resize(output_frame, debug_window_size)
                cv2.imshow('Debug', resized_frame)

        processing_frame_rate = round(
            cv2.getTickFrequency() / (cv2.getTickCount() - _timer), 2)
        frames_processed = round(cap.get(cv2.CAP_PROP_POS_FRAMES))
        frames_count = round(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        logger.debug('Frame processed.',
                     extra={
                         'meta': {
                             'label':
                             'FRAME_PROCESS',
                             'frames_processed':
                             frames_processed,
                             'frame_rate':
                             processing_frame_rate,
                             'frames_left':
                             frames_count - frames_processed,
                             'percentage_processed':
                             round((frames_processed / frames_count) * 100, 2),
                         },
                     })

        ret, frame = cap.read()

    # end capture, close window, close log file and video object if any
    cap.release()
    if not headless:
        cv2.destroyAllWindows()
    if record:
        output_video.release()
    logger.info('Processing ended.', extra={'meta': {'label': 'END_PROCESS'}})
Exemple #2
0
def run():
    '''
    Initialize counter class and run counting loop.
    '''

    import ast
    import os
    import sys
    import time

    import cv2

    from util.image import take_screenshot
    from util.logger import get_logger
    from VehicleCounter import VehicleCounter

    logger = get_logger()

    # capture traffic scene video
    is_cam = ast.literal_eval(os.getenv('IS_CAM'))
    video = int(os.getenv('VIDEO')) if is_cam else os.getenv('VIDEO')
    cap = cv2.VideoCapture(video)
    if not cap.isOpened():
        logger.error('Error capturing video. Invalid source.', extra={
            'meta': {
                'cat': 'VIDEO_CAPTURE',
                'source': video,
            },
        })
        sys.exit(0)
    ret, frame = cap.read()
    f_height, f_width, _ = frame.shape

    detection_interval = int(os.getenv('DI'))
    mcdf = int(os.getenv('MCDF'))
    mctf = int(os.getenv('MCTF'))
    detector = os.getenv('DETECTOR')
    tracker = os.getenv('TRACKER')
    # create detection region of interest polygon
    use_droi = ast.literal_eval(os.getenv('USE_DROI'))
    droi = ast.literal_eval(os.getenv('DROI')) \
            if use_droi \
            else [(0, 0), (f_width, 0), (f_width, f_height), (0, f_height)]
    show_droi = ast.literal_eval(os.getenv('SHOW_DROI'))
    counting_line_position = os.getenv('COUNTING_LINE_POSITION')

    vehicle_counter = VehicleCounter(frame, detector, tracker, droi, show_droi, mcdf,
                                     mctf, detection_interval, counting_line_position)

    record = ast.literal_eval(os.getenv('RECORD'))
    headless = ast.literal_eval(os.getenv('HEADLESS'))

    if record:
        # initialize video object to record counting
        output_video = cv2.VideoWriter(os.getenv('OUTPUT_VIDEO_PATH'), \
                                        cv2.VideoWriter_fourcc(*'MJPG'), \
                                        30, \
                                        (f_width, f_height))

    logger.info('Processing started.', extra={
        'meta': {
            'cat': 'COUNT_PROCESS',
            'counter_config': {
                'di': detection_interval,
                'mcdf': mcdf,
                'mctf': mctf,
                'detector': detector,
                'tracker': tracker,
                'use_droi': use_droi,
                'droi': droi,
                'show_droi': show_droi,
                'counting_line_position': counting_line_position
            },
        },
    })

    is_paused = False
    output_frame = None

    # main loop
    while is_cam or cap.get(cv2.CAP_PROP_POS_FRAMES) + 1 < cap.get(cv2.CAP_PROP_FRAME_COUNT):
        k = cv2.waitKey(1) & 0xFF
        if k == ord('p'): # pause/play loop if 'p' key is pressed
            is_paused = False if is_paused else True
            logger.info('Loop paused/played.', extra={'meta': {'cat': 'COUNT_PROCESS', 'is_paused': is_paused}})
        if k == ord('s') and output_frame is not None: # save frame if 's' key is pressed
            take_screenshot(output_frame)
        if k == ord('q'): # end video loop if 'q' key is pressed
            logger.info('Loop stopped.', extra={'meta': {'cat': 'COUNT_PROCESS'}})
            break

        if is_paused:
            time.sleep(0.5)
            continue

        if ret:
            vehicle_counter.count(frame)
            output_frame = vehicle_counter.visualize()

            if record:
                output_video.write(output_frame)

            if not headless:
                debug_window_size = ast.literal_eval(os.getenv('DEBUG_WINDOW_SIZE'))
                resized_frame = cv2.resize(output_frame, debug_window_size)
                cv2.imshow('Debug', resized_frame)

        ret, frame = cap.read()

    # end capture, close window, close log file and video object if any
    cap.release()
    if not headless:
        cv2.destroyAllWindows()
    if record:
        output_video.release()
    logger.info('Processing ended.', extra={'meta': {'cat': 'COUNT_PROCESS'}})
Exemple #3
0
def run():
    '''
    Loads environment variables, initializes counter class and runs counting loop.
    '''
    # capture traffic scene video
    is_cam = ast.literal_eval(os.getenv('IS_CAM'))
    video = int(os.getenv('VIDEO')) if is_cam else os.getenv('VIDEO')
    cap = cv2.VideoCapture(video)
    if not cap.isOpened():
        log_error('Error capturing video. Invalid source.', {
            'cat': 'VIDEO_CAPTURE',
            'source': video
        })
    ret, frame = cap.read()
    f_height, f_width, _ = frame.shape

    detection_interval = int(os.getenv('DI'))
    mcdf = int(os.getenv('MCDF'))
    mctf = int(os.getenv('MCTF'))
    detector = os.getenv('DETECTOR')
    tracker = os.getenv('TRACKER')
    # create detection region of interest polygon
    use_droi = ast.literal_eval(os.getenv('USE_DROI'))
    droi = ast.literal_eval(os.getenv('DROI')) \
            if use_droi \
            else [(0, 0), (f_width, 0), (f_width, f_height), (0, f_height)]
    show_droi = ast.literal_eval(os.getenv('SHOW_DROI'))
    counting_line_position = os.getenv('COUNTING_LINE_POSITION')

    vehicle_counter = VehicleCounter(frame, detector, tracker, droi, show_droi,
                                     mcdf, mctf, detection_interval,
                                     counting_line_position)

    record = ast.literal_eval(os.getenv('RECORD'))
    headless = ast.literal_eval(os.getenv('HEADLESS'))

    if record:
        # initialize video object to record counting
        output_video = cv2.VideoWriter(os.getenv('OUTPUT_VIDEO_PATH'), \
                                        cv2.VideoWriter_fourcc(*'MJPG'), \
                                        30, \
                                        (f_width, f_height))

    log_info(
        'Processing started...', {
            'cat': 'COUNT_PROCESS',
            'counter_config': {
                'di': detection_interval,
                'mcdf': mcdf,
                'mctf': mctf,
                'detector': detector,
                'tracker': tracker,
                'use_droi': use_droi,
                'droi': droi,
                'show_droi': show_droi,
                'clp': counting_line_position
            }
        })
    # main loop
    while is_cam or cap.get(cv2.CAP_PROP_POS_FRAMES) + 1 < cap.get(
            cv2.CAP_PROP_FRAME_COUNT):
        if ret:
            vehicle_counter.count(frame)
            output_frame = vehicle_counter.visualize()

            if record:
                output_video.write(output_frame)

            if not headless:
                debug_window_size = ast.literal_eval(
                    os.getenv('DEBUG_WINDOW_SIZE'))
                resized_frame = cv2.resize(output_frame, debug_window_size)
                cv2.imshow('Debug', resized_frame)

        k = cv2.waitKey(1) & 0xFF
        if k == ord('s'):  # save frame if 's' key is pressed
            take_screenshot(output_frame)
        if k == ord('q'):  # end video loop if 'q' key is pressed
            log_info('Processing stopped.', {'cat': 'COUNT_PROCESS'})
            break

        ret, frame = cap.read()

    # end capture, close window, close log file and video object if any
    cap.release()
    if not headless:
        cv2.destroyAllWindows()
    if record:
        output_video.release()
    log_info('Processing ended.', {'cat': 'COUNT_PROCESS'})
Exemple #4
0
def run():
    '''
    Initialize object counter class and run counting loop.
    '''

    video = settings.VIDEO
    cap = cv2.VideoCapture(video)
    if not cap.isOpened():
        logger.error('Invalid video source %s',
                     video,
                     extra={
                         'meta': {
                             'label': 'INVALID_VIDEO_SOURCE'
                         },
                     })
        sys.exit()
    retval, frame = cap.read()
    f_height, f_width, _ = frame.shape
    detection_interval = settings.DI
    mcdf = settings.MCDF
    mctf = settings.MCTF
    detector = settings.DETECTOR
    tracker = settings.TRACKER
    use_droi = settings.USE_DROI
    # create detection region of interest polygon
    droi = settings.DROI \
            if use_droi \
            else [(0, 0), (f_width, 0), (f_width, f_height), (0, f_height)]
    show_droi = settings.SHOW_DROI
    counting_lines = settings.COUNTING_LINES
    show_counts = settings.SHOW_COUNTS
    hud_color = settings.HUD_COLOR

    object_counter = ObjectCounter(frame, detector, tracker, droi, show_droi,
                                   mcdf, mctf, detection_interval,
                                   counting_lines, show_counts, hud_color)

    record = settings.RECORD
    if record:
        # initialize video object to record counting
        output_video = cv2.VideoWriter(settings.OUTPUT_VIDEO_PATH, \
                                        cv2.VideoWriter_fourcc(*'MJPG'), \
                                        30, \
                                        (f_width, f_height))

    logger.info('Processing started.',
                extra={
                    'meta': {
                        'label': 'START_PROCESS',
                        'counter_config': {
                            'di': detection_interval,
                            'mcdf': mcdf,
                            'mctf': mctf,
                            'detector': detector,
                            'tracker': tracker,
                            'use_droi': use_droi,
                            'droi': droi,
                            'counting_lines': counting_lines
                        },
                    },
                })

    headless = settings.HEADLESS
    if not headless:
        # capture mouse events in the debug window
        cv2.namedWindow('Debug')
        cv2.setMouseCallback('Debug', mouse_callback, {
            'frame_width': f_width,
            'frame_height': f_height
        })

    is_paused = False
    output_frame = None
    frames_count = round(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    frames_processed = 0

    try:
        # main loop
        while retval:
            k = cv2.waitKey(1) & 0xFF
            if k == ord('p'):  # pause/play loop if 'p' key is pressed
                is_paused = False if is_paused else True
                logger.info('Loop paused/played.',
                            extra={
                                'meta': {
                                    'label': 'PAUSE_PLAY_LOOP',
                                    'is_paused': is_paused
                                }
                            })
            if k == ord(
                    's'
            ) and output_frame is not None:  # save frame if 's' key is pressed
                take_screenshot(output_frame)
            if k == ord('q'):  # end video loop if 'q' key is pressed
                logger.info('Loop stopped.',
                            extra={'meta': {
                                'label': 'STOP_LOOP'
                            }})
                break

            if is_paused:
                time.sleep(0.5)
                continue

            _timer = cv2.getTickCount(
            )  # set timer to calculate processing frame rate

            object_counter.count(frame)
            output_frame = object_counter.visualize()

            if record:
                output_video.write(output_frame)

            if not headless:
                debug_window_size = settings.DEBUG_WINDOW_SIZE
                resized_frame = cv2.resize(output_frame, debug_window_size)
                cv2.imshow('Debug', resized_frame)

            processing_frame_rate = round(
                cv2.getTickFrequency() / (cv2.getTickCount() - _timer), 2)
            frames_processed += 1
            logger.debug('Frame processed.',
                         extra={
                             'meta': {
                                 'label':
                                 'FRAME_PROCESS',
                                 'frames_processed':
                                 frames_processed,
                                 'frame_rate':
                                 processing_frame_rate,
                                 'frames_left':
                                 frames_count - frames_processed,
                                 'percentage_processed':
                                 round((frames_processed / frames_count) * 100,
                                       2),
                             },
                         })

            retval, frame = cap.read()
    finally:
        # end capture, close window, close log file and video object if any
        cap.release()
        if not headless:
            cv2.destroyAllWindows()
        if record:
            output_video.release()
        logger.info('Processing ended.',
                    extra={
                        'meta': {
                            'label': 'END_PROCESS',
                            'counts': object_counter.get_counts(),
                            'completed': frames_count - frames_processed == 0,
                        },
                    })
Exemple #5
0
                )

    if not NO_UI_DISPLAY:
        cv2.namedWindow('DEBUG', cv2.WINDOW_NORMAL)
        cv2.setMouseCallback('DEBUG', mouse_callback, {'frame_width': f_width, 'frame_height': f_height})

    is_paused = False
    output_frame = None
    json_counts = None
    while CAPTURE_FROM_CAM or cap.get(cv2.CAP_PROP_POS_FRAMES) + 1 < cap.get(cv2.CAP_PROP_FRAME_COUNT):
        k = cv2.waitKey(1) & 0xFF
        if k == ord('p'):
            is_paused = False if is_paused else True
            logger.info('Loop paused/played.', extra={'meta': {'label': 'PAUSE_PLAY_LOOP', 'is_paused': is_paused}})
        if k == ord('s') and output_frame is not None:
            take_screenshot(output_frame)
        if k == ord('q'):
            with open(f"{CURRENT_DIR}/counts.json", 'w') as outfile:
                json.dump(json_counts, outfile)
            logger.info('Loop stopped.', extra={'meta': {'label': 'STOP_LOOP'}})
            break

        if is_paused:
            time.sleep(0.5)
            continue

        _timer = cv2.getTickCount()

        if ret:
            vehicle_counter.count(frame)
            json_counts = vehicle_counter.get_counts()
Exemple #6
0
def run():
    '''
    Initialize object counter class and run counting loop.
    '''

    video = settings.VIDEO
    print( 'video Path : ' + video)
    cap = cv2.VideoCapture(video)
    
    if not cap.isOpened():
        print('Not able to open video file .. exiting ..')
        sys.exit()
        
    retval, frame = cap.read()
    f_height, f_width, _ = frame.shape
    detection_interval = settings.DI
    mcdf = settings.MCDF
    mctf = settings.MCTF
    detector = settings.DETECTOR
    tracker = settings.TRACKER
    use_droi = settings.USE_DROI
    print('detector : ' + detector)
    # create detection region of interest polygon
    droi = settings.DROI \
            if use_droi \
            else [(0, 0), (f_width, 0), (f_width, f_height), (0, f_height)]
    show_droi = settings.SHOW_DROI
    counting_lines = settings.COUNTING_LINES
    show_counts = settings.SHOW_COUNTS
    hud_color = settings.HUD_COLOR

    object_counter = ObjectCounter(frame, detector, tracker, droi, show_droi, mcdf, mctf,
                                   detection_interval, counting_lines, show_counts, hud_color)

    record = settings.RECORD
    if record:
        # initialize video object to record counting
        output_video = cv2.VideoWriter(settings.OUTPUT_VIDEO_PATH, \
                                        cv2.VideoWriter_fourcc(*'MJPG'), \
                                        30, \
                                        (f_width, f_height))


    headless = settings.HEADLESS
    if not headless:
        # capture mouse events in the debug window
        cv2.namedWindow('Debug')
        cv2.setMouseCallback('Debug', mouse_callback, {'frame_width': f_width, 'frame_height': f_height})

    is_paused = False
    output_frame = None
    #frames_count = round(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    frames_processed = 0

    try:

        # count the number of frames 
        frames_count = cap.get(cv2.CAP_PROP_FRAME_COUNT) 
        fps = int(cap.get(cv2.CAP_PROP_FPS)) 
  
        # calculate dusration of the video 
        
        dict1 = dict()
        # main loop
        while retval:
            k = cv2.waitKey(1) & 0xFF
            if k == ord('p'): # pause/play loop if 'p' key is pressed
                is_paused = False if is_paused else True
                #logger.info('Loop paused/played.', extra={'meta': {'label': 'PAUSE_PLAY_LOOP', 'is_paused': is_paused}})
            if k == ord('s') and output_frame is not None: # save frame if 's' key is pressed
                take_screenshot(output_frame)
            if k == ord('q'): # end video loop if 'q' key is pressed
                #logger.info('Loop stopped.', extra={'meta': {'label': 'STOP_LOOP'}})
                break

            if is_paused:
                time.sleep(0.5)
                continue

            _timer = cv2.getTickCount() # set timer to calculate processing frame rate

            object_counter.count(frame, dict1,frames_count,fps)
            output_frame = object_counter.visualize()

            if record:
                output_video.write(output_frame)

            if not headless:
                debug_window_size = settings.DEBUG_WINDOW_SIZE
                resized_frame = cv2.resize(output_frame, debug_window_size)
                cv2.imshow('Debug', resized_frame)

            #processing_frame_rate = round(cv2.getTickFrequency() / (cv2.getTickCount() - _timer), 2)
            frames_processed += 1

            retval, frame = cap.read()
    finally:
        # end capture, close window, close log file and video object if any
        cap.release()
        if not headless:
            cv2.destroyAllWindows()
        if record:
            output_video.release()