def run_all_calibration(sweep_config_json, **kwargs):
    '''
    A Python based command line utility to run calibration for ADI TOF modules

    SWEEP_CONFIG_JSON: Specify the default sweep config json file. The default options can be overriden by explictly specifying the options on the command line
    '''

    sweep_config_dict = {}
    if (sweep_config_json is not None):
        with open(sweep_config_json) as f:
            sweep_config_dict = json.load(f)

    for key, value in kwargs.items():
        if value is not None:
            sweep_config_dict[key] = kwargs[key]
        if key in sweep_config_dict:
            if sweep_config_dict[key] is None:
                print(
                    'Need to specify %s either as a command line option or in the sweep config json file'
                )
                raise SystemExit

    if sweep_config_dict['unique_id'] == None:
        unique_id = generate_unique_id()
        sweep_config_dict['unique_id'] = unique_id
    sweep_config_dict['unique_id_list'] = split_unique_id(
        sweep_config_dict['unique_id'], 4)

    ipString = ''
    if 'remote' in sweep_config_dict:
        ip = ipaddress.ip_address(sweep_config_dict['remote'])
        print('Running script for a camera connected over Ethernet at ip:', ip)
        ipString = sweep_config_dict['remote']

    #Initialize tof class
    system = tof.System()
    status = system.initialize()
    logger.info("System Initialize: " + str(status))

    # Get Camera and program firmware
    cam_handle = device.open_device2(system, ipString)
    firmware_path = sweep_config_dict['firmware_path']
    device.program_firmware2(cam_handle, firmware_path)

    logger.info("Running Calibration")
    #Initialize Dataframes
    depth_stats_calibrated_df = pd.DataFrame([], columns=['NO DATA'])
    depth_stats_df = pd.DataFrame([], columns=['NO DATA'])
    linear_offset_df = pd.DataFrame([], columns=['NO DATA'])
    metrics_df = pd.DataFrame([], columns=['NO DATA'])

    # If using rail create handle and store handle in cfg
    rail_handle = None
    if (sweep_config_dict['calib_type'] == 'Rail'
            or sweep_config_dict['verification_type'] == 'Rail'):
        rail_handle = calib.initialize_rail(sweep_config_dict)

    latest, archive = save.make_results_dir(sweep_config_dict['results_path'],
                                            sweep_config_dict['unique_id'],
                                            mode=sweep_config_dict['mode'])

    t = time.time()
    d = 0
    while d < sweep_config_dict['warmup_time']:
        d = time.time() - t

    if sweep_config_dict['calibrate']:
        if sweep_config_dict['calib_type'] == 'Sweep':
            linear_offset_df, depth_stats_df = calib.run_sweep_calibration(
                cam_handle=cam_handle,
                cfg=sweep_config_dict,
                firmware_path=firmware_path)
        elif sweep_config_dict['calib_type'] == 'Rail':
            logger.info("Running Rail Calibration")
            # Run Rail calibration and store lf files
            linear_offset_df, depth_stats_df = calib.run_rail_calibration(
                cam_handle=cam_handle,
                rail_handle=rail_handle,
                cfg=sweep_config_dict,
                firmware_path=firmware_path)

        save.save_lf_files(latest, archive, firmware_path)
        write_lf.write_linear_offset_to_lf2(firmware_path,
                                            os.path.join(latest, 'lf_files'),
                                            sweep_config_dict,
                                            linear_offset_df)

    depth_stats_calibrated_df = pd.DataFrame()
    if sweep_config_dict['verify_sweep']:
        if sweep_config_dict['verification_type'] == 'Sweep':
            logger.info("Verifying Sweep")
            _, depth_stats_calibrated_df = calib.verify_sweep(
                cam_handle, sweep_config_dict,
                os.path.join(latest, 'lf_files'))

        elif sweep_config_dict['verification_type'] == 'Rail':
            logger.info("Verifying Sweeap")
            device.program_firmware2(cam_handle,
                                     os.path.join(latest, 'lf_files'))
            #_, depth_stats_calibrated_df = calib.rail_verify(cam_handle, rail_handle, sweep_config_dict, os.path.join(latest, 'lf_files'))
            cfg = sweep_config_dict
            frame_count = cfg['frame_count']
            window = {}
            window['X'] = cfg['window_x']
            window['Y'] = cfg['window_y']

            frame = {}
            frame['height'] = cfg['frame_height']
            frame['width'] = cfg['frame_width']

            raw_frame = {}
            raw_frame['height'] = cfg['raw_frame_height']
            raw_frame['width'] = cfg['raw_frame_width']

            repeat_num_file = os.path.join(firmware_path,
                                           cfg['repeat_num_filename'])
            hpt_data_file = os.path.join(firmware_path,
                                         cfg['hpt_data_filename'])
            data_file = os.path.join(firmware_path, cfg['data_filename'])
            seq_file = os.path.join(firmware_path, cfg['seq_info_filename'])

            min_dist = cfg['rail_min_dist']
            max_dist = cfg['rail_max_dist']
            dist_step = cfg['rail_dist_step']
            depth_conv_gain = cfg['depth_conv_gain']

            sw_gain = cfg['sw_gain']
            sw_offset = cfg['sw_offset']
            depth_stats_calibrated_df = sc.rail_stats(
                min_dist, max_dist, dist_step, raw_frame, frame, frame_count,
                window, sw_gain, sw_offset, rail_handle, cam_handle)

    logger.info("Calculating Metrics")
    metrics_df = pd.DataFrame()
    #if sweep_config_dict['verify_sweep'] and sweep_config_dict['calculate_metrics']:
    #    metrics_df = metcalc.calculate_metrics(depth_stats_df, depth_stats_calibrated_df)

    logger.info("writing to calibration json files")
    cal_json = os.path.join(firmware_path, 'linear_cal.json')
    output_cal_dict = write_to_cal_json(cal_json, sweep_config_dict)

    save.save_results(latest, archive, depth_stats_df,
                      depth_stats_calibrated_df, linear_offset_df,
                      sweep_config_dict, firmware_path, metrics_df,
                      output_cal_dict)

    camera_results_path = save.get_results_path(sweep_config_json,
                                                sweep_config_dict['unique_id'])
    logger.info('camera results path %s', camera_results_path)
    return linear_offset_df
Пример #2
0
def run_example(remote):
    cam_ip = ''
    if remote is not None:
        ip = ipaddress.ip_address(remote)
        print('Running script for a camera connected over Ethernet at ip:', ip)
        cam_ip = remote

    system = tof.System()
    status = system.initialize()

    #Specify if you want to load firmware from lf files, or from EEPROM
    from_software = True

    if (from_software):
        #Choose firmware path from here
        firmware_path = "config/BM_Kit/Near/"

        logger.info("Programming firmware from : " + firmware_path)
        cam_handle = device.open_device2(system, cam_ip)
        device.program_firmware2(cam_handle, firmware_path)

        # The following parameters must be specified if firmware is loaded from software
        sw_gain = 1
        sw_offset = 0

    else:
        #Specify which mode to load from EEPROM 'near', 'medium', 'far'
        mode = 'near'

        cameras = []
        if not cam_ip:
            status = system.getCameraList(cameras)
            logger.info("system.getCameraList()" + str(status))
        else:
            status = system.getCameraListAtIp(cameras, cam_ip)
            logger.info("system.getCameraListAtIp()" + str(status))

        cam_handle = cameras[0]

        modes = []
        status = cam_handle.getAvailableModes(modes)
        logger.info("system.getAvailableModes()" + str(status))
        logger.info(str(modes))

        types = []
        status = cam_handle.getAvailableFrameTypes(types)
        logger.info("system.getAvailableFrameTypes()" + str(status))
        logger.info(str(types))

        status = cam_handle.initialize()
        logger.info("cam_handle.initialize()" + str(status))

        status = cam_handle.setFrameType(types[0])
        logger.info("cam_handle.setFrameType()" + str(status))
        logger.info(types[0])

        status = cam_handle.setMode(mode)
        logger.info("cam_handle.setMode()" + str(status))

        frame = tof.Frame()

    logger.info("Device Programmed")

    i = 0

    # Specify frames to capture to output averaged data
    avg_vals = 1
    values_depth = np.zeros(avg_vals)
    values_ir = np.zeros(avg_vals)
    while (True):

        if (from_software):
            # Get depth and ir frames
            depth_image, ir_image = device.get_depth_ir_image(cam_handle)
            # Apply gain and offset
            depth_image = (depth_image * sw_gain) + sw_offset
        else:
            status = cam_handle.requestFrame(frame)
            depth_image = np.array(frame.getData(tof.FrameDataType.Depth),
                                   dtype="uint16",
                                   copy=False)
            ir_image = np.array(frame.getData(tof.FrameDataType.IR),
                                dtype="uint16",
                                copy=False)

        depth_image_size = (int(depth_image.shape[0] / 2),
                            depth_image.shape[1])
        depth_image_2 = np.resize(depth_image, depth_image_size)
        depth_image_2 = cv2.flip(depth_image_2, 1)
        depth_image_2 = np.uint8(depth_image_2)
        color_depth = cv2.applyColorMap(depth_image_2, cv2.COLORMAP_RAINBOW)

        #Draw rectangle at the center of depth image
        cv2.rectangle(color_depth, (315, 235), (325, 245), (0, 0, 0), 2)

        ir_image_2 = np.uint8(255 * (ir_image / 4095))
        ir_image_2.resize((480, 640))
        ir_image_2 = cv2.flip(ir_image_2, 1)
        ir_image_2 = cv2.applyColorMap(ir_image_2, cv2.COLORMAP_BONE)

        #Output images as .png
        cv2.imwrite('ir.png', ir_image_2)
        cv2.imwrite('depth.png', color_depth)

        #Uncomment if running example on 96/Arrow board with HDMI to show stream data on monitor
        #cv2.namedWindow("Depth", cv2.WINDOW_AUTOSIZE)
        #cv2.imshow( "Depth", color_depth)
        #cv2.imshow( "IR", ir_image_2)

        #if cv2.waitKey(1) >= 0:
        #        break

        # values_depth[i] = depth_image[240,320]
        # values_ir[i] = ir_image[240,320]
        # i = i + 1
        # # Generates stats for middle pixel
        # if i == avg_vals:
        # Depth = np.average(values_depth)
        # ir = np.average(values_ir)
        # Std = np.std(values_depth)
        # Noise = (Std/Depth) * 100
        # print('Depth:' + str(Depth))
        # print('STD:' + str(Std))
        # print('N%:' + str(Noise))
        # print('IR:' + str(ir))
        # i = 0

        print(get_TAL_values(cam_handle))
Пример #3
0
def run_find_pc(config_json, **kwargs):
    logger = logging.getLogger(__name__)

    pc_config_dict = load_config_dict(config_json)

    log_dict['pc_config_dict'] = pc_config_dict
    sweep_config_dict = load_config_dict(
        pc_config_dict['firmware_config_json_path'])
    firmware_path = sweep_config_dict['firmware_path']
    mode = pc_config_dict['firmware_config_json_path'].split('/')[2]
    multiply_factor = 2 if mode == "M3W" else 1
    log_dict['mode'] = mode
    log_dict['results'] = []

    # Initialize tof class
    system = tof.System()

    ipString = ''
    # Get Camera and program firmware
    cam_handle = device.open_device2(system, ipString)
    firmware_path = sweep_config_dict['firmware_path']
    device.program_firmware2(cam_handle, firmware_path)

    # Open Repeat Number file and load PC
    lf_path = os.path.join(sweep_config_dict['firmware_path'],
                           sweep_config_dict['repeat_num_filename'])
    file = open(lf_path)
    text = file.read()
    pc_dict = create_code_dict(text)

    target_ir = pc_config_dict['target_ir']
    start_pc = pc_config_dict['start_pc']
    max_pc = pc_config_dict['max_pc']

    pc, pc_dict = get_target_pc(cam_handle, pc_dict, start_pc, target_ir,
                                max_pc, sweep_config_dict, multiply_factor)

    t = time.time()
    d = 0
    while d < sweep_config_dict['warmup_time']:
        d = time.time() - t

    pc, pc_dict = get_target_pc(cam_handle, pc_dict, pc, target_ir, max_pc,
                                sweep_config_dict, multiply_factor)

    with open(pc_config_dict['out_file'], 'w') as outfile:
        json.dump(log_dict, outfile)

    # Create new lf file
    repeat_folder = 'r_lfs'
    files = glob.glob(
        os.path.join(sweep_config_dict['firmware_path'], repeat_folder, '9_*'))
    new_filename = '9_RepeatNumAddrList_' + str(len(files)) + '.lf'
    os.rename(
        lf_path,
        os.path.join(sweep_config_dict['firmware_path'], repeat_folder,
                     new_filename))

    # Write to new pulse count to file
    file = open(lf_path, 'w')
    file.writelines('/*Pulsecount :' + str(pc) + '*/ \n')
    for key in pc_dict.keys():
        file.writelines(
            tohex(key, 16, '04x') + '  ' + tohex(pc_dict[key], 16, '04x') +
            '\n')
    file.close()