Ejemplo n.º 1
0
def main(params, debug_export=DEBUG_EXPORT):
    """ the main entry point

    :param dict params: segmentation parameters
    :param bool debug_export: whether export visualisations
    """
    logging.getLogger().setLevel(logging.DEBUG)

    params = tl_expt.create_experiment_folder(
        params, dir_name=NAME_EXPERIMENT, stamp_unique=EACH_UNIQUE_EXPERIMENT)
    tl_expt.set_experiment_logger(params['path_exp'])
    logging.info(tl_expt.string_dict(params, desc='PARAMETERS'))
    # tl_expt.create_subfolders(params['path_exp'], [FOLDER_IMAGE])

    df_paths = pd.read_csv(params['path_list'], index_col=0)
    logging.info('loaded %i items with columns: %r', len(df_paths),
                 df_paths.columns.tolist())
    df_paths.dropna(how='any', inplace=True)

    # create sub-folders if required
    tl_expt.create_subfolders(params['path_exp'], ['input', 'simple'])
    dict_segment = create_dict_segmentation(params, None, None, None, None)
    dirs_center = [n + DIR_CENTRE_POSIX for n in dict_segment]
    dirs_visu = [n + DIR_VISUAL_POSIX for n in dict_segment]
    tl_expt.create_subfolders(params['path_exp'], [n for n in dict_segment] +
                              dirs_center + dirs_visu)
    if debug_export:
        list_dirs = [n + DIR_DEBUG_POSIX for n in dict_segment if 'rg2sp' in n]
        tl_expt.create_subfolders(params['path_exp'], list_dirs)

    _wrapper_segment = partial(image_segmentation, params=params)
    iterate = tl_expt.WrapExecuteSequence(_wrapper_segment,
                                          df_paths.iterrows(),
                                          nb_workers=params['nb_workers'])
    list(iterate)
Ejemplo n.º 2
0
def main(params):
    """ PIPELINE for new detections

    :param dict params:
    """
    params['path_expt'] = os.path.join(
        params['path_output'], run_detect.FOLDER_EXPERIMENT % params['name'])
    tl_expt.set_experiment_logger(params['path_expt'])
    # tl_expt.create_subfolders(params['path_expt'], LIST_SUBDIRS)
    logging.info(tl_expt.string_dict(params, desc='PARAMETERS'))

    path_csv = os.path.join(params['path_expt'], NAME_CSV_TRIPLES)
    df_paths = run_detect.get_csv_triplets(params['path_list'], path_csv,
                                           params['path_images'],
                                           params['path_segms'],
                                           params['path_centers'],
                                           FORCE_RELOAD)

    df_eval = df_paths.copy(deep=True)
    for stage in params['stages']:
        df_eval = evaluate_detection_stage(df_eval, stage,
                                           params['path_infofile'],
                                           params['path_expt'],
                                           params['nb_workers'])
        if not df_eval.empty and 'image' in df_eval.columns:
            df_eval.set_index('image', inplace=True)
        df_eval.to_csv(os.path.join(params['path_expt'],
                                    NAME_CSV_TRIPLES_STAT))
        gc.collect()
        time.sleep(1)

    if not df_eval.empty:
        df_stat = df_eval.describe().transpose()
        logging.info('STATISTIC: \n %r', df_stat)
        df_stat.to_csv(os.path.join(params['path_expt'], NAME_CSV_STATISTIC))
def main(params):
    """ the main body containgn two approches:
    1) segment each image indecently
    2) estimate model over whole image sequence and estimate

    :param dict params:
    :return dict:
    """
    logging.getLogger().setLevel(logging.DEBUG)
    show_visual = params.get('visual', False)

    reload_dir_config = os.path.isfile(params['path_config']) or FORCE_RELOAD
    stamp_unique = params.get('unique', EACH_UNIQUE_EXPERIMENT)
    params = tl_expt.create_experiment_folder(params,
                                              dir_name=NAME_EXPERIMENT,
                                              stamp_unique=stamp_unique,
                                              skip_load=reload_dir_config)
    tl_expt.set_experiment_logger(params['path_exp'])
    logging.info(tl_expt.string_dict(params, desc='PARAMETERS'))
    tl_expt.create_subfolders(params['path_exp'], LIST_FOLDERS_BASE)
    if show_visual:
        tl_expt.create_subfolders(params['path_exp'], LIST_FOLDERS_DEBUG)

    paths_img = load_path_images(params)
    assert paths_img, 'missing images'

    def _path_expt(n):
        return os.path.join(params['path_exp'], n)

    # Segment as single model per image
    path_visu = _path_expt(FOLDER_SEGM_GMM_VISU) if show_visual else None
    dict_segms_gmm = experiment_single_gmm(params,
                                           paths_img,
                                           _path_expt(FOLDER_SEGM_GMM),
                                           path_visu,
                                           show_debug_imgs=show_visual)
    gc.collect()
    time.sleep(1)

    # Segment as model ober set of images
    if params.get('run_groupGMM', False):
        path_visu = _path_expt(FOLDER_SEGM_GROUP_VISU) if show_visual else None
        dict_segms_group = experiment_group_gmm(params,
                                                paths_img,
                                                _path_expt(FOLDER_SEGM_GROUP),
                                                path_visu,
                                                show_debug_imgs=show_visual)
    else:
        write_skip_file(_path_expt(FOLDER_SEGM_GROUP))
        # write_skip_file(_path_expt(FOLDER_SEGM_GROUP_VISU))
        dict_segms_group = None

    if dict_segms_group is not None:
        df_ars = compare_segms_metric_ars(dict_segms_gmm,
                                          dict_segms_group,
                                          suffix='_gmm-group')
        df_ars.to_csv(_path_expt(NAME_CSV_ARS_CORES))
        logging.info(df_ars.describe())

    return params
def main_predict(path_classif,
                 path_pattern_imgs,
                 path_out,
                 name='SEGMENT___',
                 params_local=None):
    """ given trained classifier segment new images

    :param str path_classif:
    :param str path_pattern_imgs:
    :param str path_out:
    :param str name:
    """
    logging.getLogger().setLevel(logging.INFO)
    logging.info('running PREDICTION...')
    assert path_pattern_imgs is not None

    dict_classif = seg_clf.load_classifier(path_classif)
    classif = dict_classif['clf_pipeline']
    params = dict_classif['params']
    if params_local is not None:
        params.update({
            k: params_local[k]
            for k in params_local
            if k.startswith('path_') or k.startswith('gc_')
        })

    path_out, path_visu = prepare_output_dir(path_pattern_imgs,
                                             path_out,
                                             name,
                                             visual=params.get(
                                                 'visual', False))
    tl_expt.set_experiment_logger(path_out)
    logging.info(tl_expt.string_dict(params, desc='PARAMETERS'))

    paths_img = sorted(glob.glob(path_pattern_imgs))
    logging.info('found %i images on path "%s"', len(paths_img),
                 path_pattern_imgs)

    logging.debug('run prediction...')
    show_debug_imgs = params.get('visual', False)
    _wrapper_segment = partial(
        try_segment_image,
        params=params,
        classif=classif,
        path_out=path_out,
        path_visu=path_visu,
        show_debug_imgs=show_debug_imgs,
    )
    list_img_path = list(zip([None] * len(paths_img), paths_img))
    iterate = tl_expt.WrapExecuteSequence(
        _wrapper_segment,
        list_img_path,
        nb_workers=params['nb_workers'],
        desc='segmenting images',
    )
    for _ in iterate:
        gc.collect()
        time.sleep(1)

    logging.info('prediction DONE')
Ejemplo n.º 5
0
def main(params):
    """ PIPELINE for new detections

    :param {str: str} params:
    """
    params = run_train.prepare_experiment_folder(params, FOLDER_EXPERIMENT)

    # run_train.check_pathes_patterns(paths)
    tl_expt.set_experiment_logger(params['path_expt'])
    logging.info('COMPUTER: \n%r', platform.uname())
    logging.info(tl_expt.string_dict(params, desc='PARAMETERS'))

    tl_expt.create_subfolders(params['path_expt'], LIST_SUBFOLDER)

    path_csv = os.path.join(params['path_expt'], NAME_CSV_TRIPLES)
    df_paths = get_csv_triplets(params['path_list'],
                                path_csv,
                                params['path_images'],
                                params['path_segms'],
                                force_reload=FORCE_RERUN)

    dict_classif = seg_clf.load_classifier(params['path_classif'])
    params_clf = dict_classif['params']
    params_clf.update(params)
    logging.info(tl_expt.string_dict(params, desc='UPDATED PARAMETERS'))

    # perform on new images
    df_stat = pd.DataFrame()
    _wrapper_detection = partial(
        load_compute_detect_centers,
        params=params_clf,
        path_classif=params['path_classif'],
        path_output=params['path_expt'],
    )
    iterate = tl_expt.WrapExecuteSequence(_wrapper_detection,
                                          df_paths.iterrows(),
                                          nb_workers=params['nb_workers'])
    for dict_center in iterate:
        df_stat = df_stat.append(dict_center, ignore_index=True)
        df_stat.to_csv(os.path.join(params['path_expt'],
                                    NAME_CSV_TRIPLES_TEMP))

    df_stat.set_index(['image'], inplace=True)
    df_stat.to_csv(os.path.join(params['path_expt'], NAME_CSV_TRIPLES))
    logging.info('STATISTIC: \n %r', df_stat.describe())
def main_train(params):
    """ PIPELINE for training
    0) load triplets or create triplets from path to images, annotations
    1) load precomputed data or compute them now
    2) train classifier with hyper-parameters
    3) perform Leave-One-Out experiment

    :param {str: any} params:
    """
    params = prepare_experiment_folder(params, FOLDER_EXPERIMENT)

    tl_expt.set_experiment_logger(params['path_expt'])
    logging.info(tl_expt.string_dict(params, desc='PARAMETERS'))
    tl_expt.save_config_yaml(
        os.path.join(params['path_expt'], NAME_YAML_PARAMS), params)
    tl_expt.create_subfolders(params['path_expt'], LIST_SUBDIRS)

    df_paths, _ = load_df_paths(params)

    path_dump_data = os.path.join(params['path_expt'], NAME_DUMP_TRAIN_DATA)
    if not os.path.isfile(path_dump_data) or FORCE_RECOMP_DATA:
        (dict_imgs, dict_segms, dict_slics, dict_points, dict_centers,
         dict_features, dict_labels, feature_names) = \
            dataset_load_images_segms_compute_features(params, df_paths, params['nb_workers'])
        assert len(dict_imgs) > 0, 'missing images'
        save_dump_data(
            path_dump_data,
            dict_imgs,
            dict_segms,
            dict_slics,
            dict_points,
            dict_centers,
            dict_features,
            dict_labels,
            feature_names,
        )
    else:
        (dict_imgs, dict_segms, dict_slics, dict_points, dict_centers,
         dict_features, dict_labels,
         feature_names) = load_dump_data(path_dump_data)

    if is_drawing(params['path_expt']) and EXPORT_TRAINING_DATA:
        export_dataset_visual(params['path_expt'], dict_imgs, dict_segms,
                              dict_slics, dict_points, dict_labels,
                              params['nb_workers'])

    # concentrate features, labels
    features, labels, sizes = seg_clf.convert_set_features_labels_2_dataset(
        dict_features,
        dict_labels,
        drop_labels=[-1],
        balance_type=params['balance'])
    # remove all bad values from features space
    features[np.isnan(features)] = 0
    features[np.isinf(features)] = -1
    assert np.sum(sizes) == len(labels), \
        'not equal sizes (%d) and labels (%i)' \
        % (int(np.sum(sizes)), len(labels))

    # feature norm & train classification
    nb_holdout = int(np.ceil(len(sizes) * CROSS_VAL_LEAVE_OUT_SEARCH))
    cv = seg_clf.CrossValidateGroups(sizes, nb_holdout)
    classif, params[
        'path_classif'] = seg_clf.create_classif_search_train_export(
            params['classif'],
            features,
            labels,
            cross_val=cv,
            params=params,
            feature_names=feature_names,
            nb_search_iter=params['nb_classif_search'],
            pca_coef=params.get('pca_coef', None),
            nb_workers=params['nb_workers'],
            path_out=params['path_expt'],
        )
    nb_holdout = int(np.ceil(len(sizes) * CROSS_VAL_LEAVE_OUT_EVAL))
    cv = seg_clf.CrossValidateGroups(sizes, nb_holdout)
    seg_clf.eval_classif_cross_val_scores(params['classif'],
                                          classif,
                                          features,
                                          labels,
                                          cross_val=cv,
                                          path_out=params['path_expt'])
    seg_clf.eval_classif_cross_val_roc(params['classif'],
                                       classif,
                                       features,
                                       labels,
                                       cross_val=cv,
                                       path_out=params['path_expt'])

    if RUN_LEAVE_ONE_OUT:
        experiment_loo(classif, dict_imgs, dict_segms, dict_centers,
                       dict_slics, dict_points, dict_features, feature_names,
                       params)
Ejemplo n.º 7
0
def main_train(params):
    """ the main composed from following steps:
    1) load already computed data (features and labels) or compute them now
    2) visualise labeled superpixels aka annotation
    3) load or train classifier with hyper-parameters search
    4) perform Leave-One-Out and Leave-P-Out experiments on images

    :param {str: ...} params:
    :return {str: ...}:
    """
    logging.getLogger().setLevel(logging.DEBUG)
    logging.info('running TRAINING...')
    show_visual = params.get('visual', False)

    reload_dir_config = (os.path.isfile(params.get('path_config', ''))
                         or FORCE_RELOAD)
    params = tl_expt.create_experiment_folder(params,
                                              dir_name=NAME_EXPERIMENT,
                                              stamp_unique=params.get(
                                                  'unique',
                                                  EACH_UNIQUE_EXPERIMENT),
                                              skip_load=reload_dir_config)
    tl_expt.set_experiment_logger(params['path_exp'])
    logging.info(tl_expt.string_dict(params, desc='PARAMETERS'))
    tl_expt.create_subfolders(params['path_exp'], LIST_FOLDERS_BASE)
    if show_visual:
        tl_expt.create_subfolders(params['path_exp'], LIST_FOLDERS_DEBUG)
    df_stat = pd.DataFrame()

    path_dump = os.path.join(params['path_exp'], NAME_DUMP_TRAIN_DATA)
    if os.path.isfile(path_dump) and not FORCE_RECOMP_DATA:
        dict_imgs, dict_annot, dict_slics, dict_features, dict_labels, \
        dict_label_hist, feature_names = load_dump_data(path_dump)
    else:
        dict_imgs, dict_annot, dict_slics, dict_features, dict_labels, \
        dict_label_hist, feature_names = \
            dataset_load_images_annot_compute_features(params,
                                                       show_visual)
        save_dump_data(path_dump, dict_imgs, dict_annot, dict_slics,
                       dict_features, dict_labels, dict_label_hist,
                       feature_names)
    assert len(dict_imgs) > 1, 'training require at least 2 images'

    dict_annot_slic = {
        n: np.asarray(dict_labels[n])[dict_slics[n]]
        for n in dict_annot
    }
    df = eval_segment_with_annot(params, dict_annot, dict_annot_slic,
                                 dict_label_hist,
                                 NAME_CSV_SEGM_STAT_SLIC_ANNOT,
                                 params.get('drop_labels',
                                            None), params['nb_jobs'])
    df_stat = df_stat.append(get_summary(df, 'SLIC-annot'), ignore_index=True)
    path_csv_stat = os.path.join(params['path_exp'],
                                 NAME_CSV_SEGM_STAT_RESULTS)
    df_stat.set_index(['name']).to_csv(path_csv_stat)

    if params['gc_use_trans']:
        params['label_transitions'] = \
            seg_gc.count_label_transitions_connected_segments(dict_slics,
                                                              dict_labels)
        logging.info('summary on edge-label transitions: \n %s',
                     repr(params['label_transitions']))

    path_purity_visu = os.path.join(params['path_exp'], FOLDER_SLIC_ANNOT) \
        if show_visual else None
    dict_labels = filter_train_with_purity(dict_imgs,
                                           dict_labels,
                                           dict_label_hist,
                                           params['label_purity'],
                                           dict_slics,
                                           drop_labels=params.get(
                                               'drop_labels', None),
                                           path_visu=path_purity_visu,
                                           nb_jobs=params['nb_jobs'])

    logging.info('prepare features...')
    # concentrate features, labels
    features, labels, sizes = seg_clf.convert_set_features_labels_2_dataset(
        dict_features,
        dict_labels,
        balance_type=params['balance'],
        drop_labels=[-1, np.nan] + params.get('drop_labels', []))
    # drop "do not care" label which are -1
    features = np.nan_to_num(features)

    nb_holdout = params.get('cross_val', CROSS_VAL_LEAVE_OUT_SEARCH)
    nb_holdout = max(1, int(round(len(sizes) * nb_holdout)))  # minimum is 1
    nb_holdout = min(nb_holdout, int(len(sizes) / 2))  # max is half of the set
    params, classif, path_classif = load_train_classifier(
        params, features, labels, feature_names, sizes, nb_holdout)

    def _path_expt(n):
        return os.path.join(params['path_exp'], n)

    # test classif. on  training images
    df_paths = pd.read_csv(params['path_train_list'], index_col=0)
    df_paths.reset_index(inplace=True)
    paths_img = df_paths['path_image'].tolist()
    if RUN_TRAIN_PREDICT:
        perform_train_predictions(params,
                                  paths_img,
                                  classif,
                                  show_debug_imgs=show_visual)
    else:
        write_skip_file(_path_expt(FOLDER_TRAIN))

    gc.collect()
    time.sleep(1)

    # LEAVE P OUT
    if params.get('run_LPO', True):
        idx_paths_img = list(
            zip(df_paths.index.tolist(), df_paths['path_image'].tolist()))
        df_stat = experiment_lpo(params,
                                 df_stat,
                                 dict_annot,
                                 idx_paths_img,
                                 path_classif,
                                 path_dump,
                                 nb_holdout,
                                 show_debug_imgs=show_visual)
    else:
        write_skip_file(_path_expt(FOLDER_LPO))
        # write_skip_file(_path_expt(FOLDER_LPO_VISU))

    logging.info('Statistic: \n %s', repr(df_stat.describe()))
    logging.info('training DONE')
    return params