def test_cal_eeprom():
    cal1 = cal_map()
    cal1.init_default_cal_map()
    print("Calibration map written to Bin File")
    cal1.display_cal_map()
    cal1.save_cal_map("calibration_map.bin")

    cal2 = cal_map()
    cal2.read_cal_map("calibration_map.bin")
    print("\n\nCalibration map read back from Bin File")
    cal2.display_cal_map()
    input("Press Enter to continue...")

    cal2.add_json_to_map(NEAR_CAL, "./linear_cal.json")
    print("\n\nCalibration map after adding linear_cal.json to map")
    cal2.display_cal_map()
    input("Press Enter to continue...")

    cal2.add_load_files_to_map(NEAR_LF, "../config/ADDI9043/")
    print("\n\nCalibration map after adding load files to map")
    cal2.display_cal_map()
    print("\n\nSaving to 'calibration_map.bin'")
    cal2.save_cal_map("caibration_map.bin")
    input("Press Enter to continue...")

    #cal2.add_linear_correct_offset(NEAR_CAL, "../saved_results/latest/linear_offset.csv")
    #cal2.display_cal_map()
    #cal2.save_cal_map()

    # Open the ADI TOF Camera
    system = tof.System()
    status = system.initialize()
    print("system.initialize()", status)
    cam_handle = device.open_device2(system)
    dev_handle = cam_handle.getDevice()

    print("\n\nWriting to EEPROM")
    cal2.write_eeprom_cal_map(dev_handle)

    print("\n\nReading from EEPROM")
    cal3 = cal_map()
    cal3.read_eeprom_cal_map(dev_handle)
    cal3.save_cal_map("eeprom_read_map.bin")
    with open("eeprom_read_map.json", 'w') as f:
        f.write(str(cal3.calibration_map))
    f.close()
    cal3.display_cal_map()
    input("Press Enter to continue...")

    cal3.replace_eeprom_mode('near', "./config/BM_Kit/Near/linear_cal.json",
                             "./config/BM_Kit/Near/")
    with open("eeprom_read_map_modified.json", 'w') as f:
        f.write(str(cal1.calibration_map))
    f.close()
Example #2
0
def run_intrinsic_calibration(intrinsic_config_json, **kwargs):

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

    firmware_path = intrinsic_config_dict['firmware_path']
    file_list = natsorted(os.listdir("./" + firmware_path + "/"),
                          alg=ns.IGNORECASE)[:14]
    print(file_list)

    #Initialize tof class
    system = tof.System()

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

    device.write_AFE_reg(cam_handle, [0xC0A9], [0x0002])
    device.write_AFE_reg(cam_handle, [0x4001], [0x0006])
    device.write_AFE_reg(cam_handle, [0x7c22], [0x0004])
    device.write_AFE_reg(cam_handle, [0x4001], [0x0007])
    device.write_AFE_reg(cam_handle, [0x7c22], [0x0004])

    config_path = intrinsic_config_dict['config_path']
    output_path = intrinsic_config_dict['output_path']

    ic_c = ic.intrinsic_calibration()
    if intrinsic_config_dict['get_coordinates']:
        ic_c.get_coordinates(get_ir_image(cam_handle))
        ic_c.output_coordinates(config_path)
    else:
        ic_c.load_coordinates(config_path)

    if intrinsic_config_dict['calibrate_intrinsic']:
        num, _, roi = ic_c.calibrate_intrinsic(get_ir_image(cam_handle))

    if num >= (intrinsic_config_dict['min_checkerboards']):
        ic_c.output_intrinsic(output_path,
                              intrinsic_config_dict['serial_number'])
    else:
        logger.error(str(num) + " checkerboards found, no params output")

    if intrinsic_config_dict['output_data']:
        ic_c.output_intrinsic_data(output_path)
Example #3
0
import aditofpython as tof
import numpy as np

system = tof.System()
status = system.initialize()
print("system.initialize()", status)

cameras = []
status = system.getCameraList(cameras)
print("system.getCameraList()", status)

camera1 = cameras[0]

modes = []
status = camera1.getAvailableModes(modes)
print("system.getAvailableModes()", status)
print(modes)

types = []
status = camera1.getAvailableFrameTypes(types)
print("system.getAvailableFrameTypes()", status)
print(types)

status = camera1.initialize()
print("camera1.initialize()", status)

camDetails = tof.CameraDetails()
status = camera1.getDetails(camDetails)
print("system.getDetails()", status)
print("camera1 details:", "id:", camDetails.cameraId, "connection:",
      camDetails.connection)
Example #4
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))
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
Example #6
0
def run_eeprom_replace_cal(config_json, **kwargs):
    '''
    Replace the calibration data for a single mode in an ADI TOF module

    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
    '''
    logger = logging.getLogger(__name__)

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

    for key, value in kwargs.items():
        if value is not None:
            config_dict[key] = kwargs[key]
        if key in config_dict:
            if 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

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

    # Retrieve parameters
    cal_map_path = config_dict['cal_map_path']
    firmware_path = config_dict['firmware_path']
    mode = config_dict['mode']

    # Open the ADI TOF Camera
    system = tof.System()
    status = system.initialize()
    print("system.initialize()", status)
    cam_handle = device.open_device2(system, ipString)
    eeproms = []
    cam_handle.getEeproms(eeproms)
    eeprom = eeproms[0]

    # Read the cal map from the camera and store it locally
    cal = ce.cal_map()
    cal.read_eeprom_cal_map(eeprom)

    save_path = cal_map_path + "/eeprom_read_map.bin"
    logger.info("Save the original cal map to .bin and .json files, path: %s",
                save_path)
    cal.save_cal_map(save_path)
    save_path = cal_map_path + "/eeprom_read_map.json"
    with open(save_path, 'w') as f:
        f.write(str(cal.calibration_map))
    f.close()

    # cal.display_cal_map()
    #input("Press Enter to continue...")

    # Replace a single mode's cal data
    logger.info("Replace mode %s cal data from path: %s", mode, save_path)
    cal.replace_eeprom_mode(mode, firmware_path + "/linear_cal.json",
                            firmware_path)
    save_path = cal_map_path + "/eeprom_read_map_modified.json"
    with open(save_path, 'w') as f:
        f.write(str(cal.calibration_map))
    f.close()

    # Write the cal map back to the camera's EEPROM
    cal.write_eeprom_cal_map(eeprom)
    logger.info("Write back to EEPROM complete")
Example #7
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()