| | import os |
| | import numpy as np |
| | import pandas as pd |
| | from deepcell_tracking.trk_io import load_trks |
| | from skimage.io import imsave |
| | import tifffile |
| |
|
| | def convert_to_ctc_format(data_dir, output_dir): |
| | """ |
| | Convert DynamicNuclearNet tracking data to CTC format |
| | |
| | CTC format requires: |
| | - SEG/ folder with segmentation masks (man_seg####.tif) |
| | - TRA/ folder with tracking masks (man_track####.tif) |
| | - res_track.txt file with tracking results |
| | """ |
| | |
| | |
| | data = load_trks(os.path.join(data_dir, 'test.trks')) |
| | |
| | X = data['X'] |
| | y = data['y'] |
| | lineages = data['lineages'] |
| | |
| | |
| | data_source = np.load(os.path.join(data_dir, 'data-source.npz'), allow_pickle=True) |
| | meta = pd.DataFrame(data_source['test'], columns=['filename', 'experiment', 'pixel_size', 'screening_passed', 'time_step', 'specimen']) |
| | |
| | |
| | seg_dir = os.path.join(output_dir, 'SEG') |
| | tra_dir = os.path.join(output_dir, 'TRA') |
| | os.makedirs(seg_dir, exist_ok=True) |
| | os.makedirs(tra_dir, exist_ok=True) |
| | |
| | |
| | tracking_results = [] |
| | |
| | for seq_idx in range(len(X)): |
| | print(f"Processing sequence {seq_idx + 1}/{len(X)}") |
| | |
| | sequence_images = X[seq_idx] |
| | sequence_masks = y[seq_idx] |
| | sequence_lineages = lineages[seq_idx] |
| | |
| | |
| | if sequence_masks.ndim == 4: |
| | sequence_masks = sequence_masks.squeeze(-1) |
| | |
| | num_frames = sequence_masks.shape[0] |
| | |
| | |
| | for t in range(num_frames): |
| | |
| | seg_filename = f"man_seg{t:04d}.tif" |
| | seg_path = os.path.join(seg_dir, seg_filename) |
| | tifffile.imwrite(seg_path, sequence_masks[t].astype(np.uint16)) |
| | |
| | |
| | tra_filename = f"man_track{t:04d}.tif" |
| | tra_path = os.path.join(tra_dir, tra_filename) |
| | tifffile.imwrite(tra_path, sequence_masks[t].astype(np.uint16)) |
| | |
| | |
| | frame_mask = sequence_masks[t] |
| | unique_cells = np.unique(frame_mask) |
| | unique_cells = unique_cells[unique_cells > 0] |
| | |
| | for cell_id in unique_cells: |
| | |
| | cell_lineage = None |
| | for lineage in sequence_lineages: |
| | if cell_id in lineage.get('label', []): |
| | cell_lineage = lineage |
| | break |
| | |
| | if cell_lineage: |
| | parent_id = cell_lineage.get('parent', 0) |
| | generation = cell_lineage.get('generation', 0) |
| | |
| | |
| | |
| | cell_frames = [] |
| | for frame_idx in range(num_frames): |
| | if cell_id in np.unique(sequence_masks[frame_idx]): |
| | cell_frames.append(frame_idx) |
| | |
| | if cell_frames: |
| | start_frame = min(cell_frames) |
| | end_frame = max(cell_frames) |
| | |
| | tracking_results.append([ |
| | cell_id, |
| | start_frame, |
| | end_frame, |
| | parent_id |
| | ]) |
| |
|
| | |
| | tracking_df = pd.DataFrame(tracking_results, columns=['L', 'B', 'E', 'P']) |
| | tracking_df = tracking_df.drop_duplicates().sort_values('L') |
| | |
| | |
| | res_track_path = os.path.join(output_dir, 'res_track.txt') |
| | with open(res_track_path, 'w') as f: |
| | for _, row in tracking_df.iterrows(): |
| | f.write(f"{int(row['L'])} {int(row['B'])} {int(row['E'])} {int(row['P'])}\n") |
| | |
| | print(f"CTC format conversion completed!") |
| | print(f"Segmentation masks saved to: {seg_dir}") |
| | print(f"Tracking masks saved to: {tra_dir}") |
| | print(f"Tracking results saved to: {res_track_path}") |
| | |
| | return tracking_df |
| |
|
| | |
| | def convert_all_trks_to_ctc(data_dir, output_base_dir): |
| | """ |
| | Convert all .trks files (train, test, val) to CTC format |
| | """ |
| | trks_files = ['train.trks', 'test.trks', 'val.trks'] |
| | |
| | for trks_file in trks_files: |
| | if os.path.exists(os.path.join(data_dir, trks_file)): |
| | dataset_name = trks_file.split('.')[0] |
| | output_dir = os.path.join(output_base_dir, dataset_name) |
| | |
| | print(f"\nConverting {trks_file} to CTC format...") |
| | |
| | |
| | data = load_trks(os.path.join(data_dir, trks_file)) |
| | |
| | |
| | os.makedirs(output_dir, exist_ok=True) |
| | |
| | |
| | for seq_idx in range(len(data['X'])): |
| | seq_output_dir = os.path.join(output_dir, f"sequence_{seq_idx:03d}") |
| | |
| | |
| | single_seq_data = { |
| | 'X': [data['X'][seq_idx]], |
| | 'y': [data['y'][seq_idx]], |
| | 'lineages': [data['lineages'][seq_idx]] |
| | } |
| | |
| | |
| | convert_single_sequence_to_ctc(single_seq_data, seq_output_dir) |
| |
|
| | def trk_to_isbi(track, path=None): |
| | """Convert a lineage track into an ISBI formatted text file. |
| | |
| | Args: |
| | track (dict): Cell lineage object. |
| | path (str): Path to save the .txt file. |
| | |
| | Returns: |
| | pd.DataFrame: DataFrame of ISBI data for each label. |
| | """ |
| | isbi = [] |
| | for label in track: |
| | first_frame = min(track[label]['frames']) |
| | last_frame = max(track[label]['frames']) |
| | parent = track[label]['parent'] |
| | parent = 0 if parent is None else parent |
| | if parent: |
| | parent_frames = track[parent]['frames'] |
| | if parent_frames[-1] != first_frame - 1: |
| | parent = 0 |
| |
|
| | isbi_dict = {'Cell_ID': label, |
| | 'Start': first_frame, |
| | 'End': last_frame, |
| | 'Parent_ID': parent} |
| | isbi.append(isbi_dict) |
| |
|
| | if path is not None: |
| | with open(path, 'w') as text_file: |
| | for cell in isbi: |
| | line = '{cell_id} {start} {end} {parent}\n'.format( |
| | cell_id=cell['Cell_ID'], |
| | start=cell['Start'], |
| | end=cell['End'], |
| | parent=cell['Parent_ID'] |
| | ) |
| | text_file.write(line) |
| | df = pd.DataFrame(isbi) |
| | return df |
| |
|
| | def convert_single_sequence_to_ctc(data, output_dir): |
| | """ |
| | Convert a single sequence to CTC format |
| | """ |
| | X = data['X'][0] |
| | y = data['y'][0] |
| | lineages = data['lineages'][0] |
| | |
| | |
| | print(f"Lineages type: {type(lineages)}") |
| | print(f"Lineages shape/length: {len(lineages) if hasattr(lineages, '__len__') else 'N/A'}") |
| | if len(lineages) > 0: |
| | if isinstance(lineages, dict): |
| | first_key = list(lineages.keys())[0] |
| | print(f"First lineage key: {first_key}") |
| | print(f"First lineage value type: {type(lineages[first_key])}") |
| | print(f"First lineage value: {lineages[first_key]}") |
| | print(f"All keys (first 10): {list(lineages.keys())[:10]}") |
| | else: |
| | print(f"First lineage item type: {type(lineages[0])}") |
| | print(f"First lineage item: {lineages[0]}") |
| | |
| | |
| | seg_dir = os.path.join(output_dir, 'SEG') |
| | tra_dir = os.path.join(output_dir, 'TRA') |
| | os.makedirs(seg_dir, exist_ok=True) |
| | os.makedirs(tra_dir, exist_ok=True) |
| | |
| | |
| | if y.ndim == 4: |
| | y = y.squeeze(-1) |
| | |
| | |
| | for t in range(y.shape[0]): |
| | |
| | seg_filename = f"man_seg{t:04d}.tif" |
| | tifffile.imwrite(os.path.join(seg_dir, seg_filename), y[t].astype(np.uint16)) |
| | |
| | |
| | tra_filename = f"man_track{t:04d}.tif" |
| | tifffile.imwrite(os.path.join(tra_dir, tra_filename), y[t].astype(np.uint16)) |
| | |
| | |
| | res_track_path = os.path.join(output_dir, 'res_track.txt') |
| | |
| | |
| | isbi_df = trk_to_isbi(lineages, res_track_path) |
| | |
| | print(f"Converted {len(isbi_df)} cell tracks to CTC format") |
| | return isbi_df |
| |
|
| |
|
| | |
| | if __name__ == "__main__": |
| | data_dir = '/l/users/sahal.mullappilly/Komal/documents/Cell/DEEPCELL/DynamicNuclearNet-tracking-v1_0' |
| | output_dir = '/l/users/sahal.mullappilly/Komal/documents/Cell/DEEPCELL/CTCformat' |
| | |
| | |
| | convert_all_trks_to_ctc(data_dir, output_dir) |
| | |
| | |
| | |