### Install PyDeface using pip Source: https://github.com/poldracklab/pydeface/blob/master/README.md Install PyDeface directly from PyPI using pip. This is the recommended method for most users. ```bash pip install pydeface ``` -------------------------------- ### Install PyDeface from source Source: https://github.com/poldracklab/pydeface/blob/master/README.md Clone the repository and install PyDeface locally. This is useful for development or if you need to modify the source code. ```bash git clone https://github.com/poldracklab/pydeface.git cd pydeface pip install . ``` -------------------------------- ### Environment Validation with pydeface.utils.initial_checks Source: https://context7.com/poldracklab/pydeface/llms.txt Verify that required files and FSL dependencies are present before starting processing. This function returns the paths to the template and mask files. ```python import pydeface.utils as pdu # Use default template and facemask bundled with pydeface template, facemask = pdu.initial_checks() print(f"Template: {template}") print(f"Facemask: {facemask}") # Verify custom template and facemask exist try: template, facemask = pdu.initial_checks( template='custom_template.nii.gz', facemask='custom_facemask.nii.gz' ) except Exception as e: print(f"Check failed: {e}") # Possible errors: # - "Missing template: custom_template.nii.gz" # - "Missing face mask: custom_facemask.nii.gz" # - "FSL must be installed and FSLDIR environment variable must be defined." ``` -------------------------------- ### Get Output File Type Source: https://context7.com/poldracklab/pydeface/llms.txt Determines the FSL output type string based on the file extension. ```python import pydeface.utils as pdu # Compressed NIfTI format output_type = pdu.get_outfile_type('brain_defaced.nii.gz') print(output_type) # Output: NIFTI_GZ # Uncompressed NIfTI format output_type = pdu.get_outfile_type('brain_defaced.nii') print(output_type) # Output: NIFTI # Invalid extension raises ValueError try: output_type = pdu.get_outfile_type('brain.mgz') except ValueError as e: print(f"Error: {e") # Output: outfile path should be have .nii or .nii.gz suffix ``` -------------------------------- ### Display PyDeface help message Source: https://github.com/poldracklab/pydeface/blob/master/README.md Access the help message for PyDeface to see all available command-line options and their descriptions. ```bash pydeface --help ``` -------------------------------- ### pydeface.utils.initial_checks Source: https://context7.com/poldracklab/pydeface/llms.txt Performs sanity checks to ensure required files and FSL dependencies are available. ```APIDOC ## pydeface.utils.initial_checks ### Description Validates that the required template and facemask files exist and that FSL is correctly installed in the environment. ### Parameters #### Request Body - **template** (string) - Optional - Path to custom template. - **facemask** (string) - Optional - Path to custom face mask. ### Response - **template** (string) - Path to the validated template file. - **facemask** (string) - Path to the validated face mask file. ``` -------------------------------- ### Generate Temporary Files Source: https://context7.com/poldracklab/pydeface/llms.txt Creates temporary files for registration and provides cleanup methods. ```python import pydeface.utils as pdu # Generate temporary files with verbose output template_reg, template_reg_mat, warped_mask, warped_mask_mat = pdu.generate_tmpfiles( verbose=True ) # Output: # Temporary files: # /tmp/tmpXXXXXX.mat # /tmp/tmpXXXXXX.nii.gz print(f"Template registration: {template_reg}") # .nii.gz file print(f"Registration matrix: {template_reg_mat}") # .mat file print(f"Warped mask: {warped_mask}") # .nii.gz file print(f"Warped mask matrix: {warped_mask_mat}") # .mat file # Silent mode template_reg, template_reg_mat, warped_mask, warped_mask_mat = pdu.generate_tmpfiles( verbose=False ) # Remember to cleanup after use pdu.cleanup_files(template_reg, template_reg_mat, warped_mask, warped_mask_mat) ``` -------------------------------- ### Force Overwrite Existing Output Source: https://context7.com/poldracklab/pydeface/llms.txt Use output_checks with force=True to overwrite existing files. ```python # Force overwrite existing output outfile = pdu.output_checks( infile='scan.nii.gz', force=True # Will print: "Previous output will be overwritten." ) ``` -------------------------------- ### Command Line Interface Usage Source: https://context7.com/poldracklab/pydeface/llms.txt Execute defacing operations directly from the terminal. Use these commands to process single files, apply masks to multiple modalities, or customize registration parameters. ```bash # Basic defacing - creates infile_defaced.nii.gz pydeface brain_scan.nii.gz # Specify custom output filename pydeface brain_scan.nii.gz --outfile anonymized_scan.nii.gz # Force overwrite existing output pydeface brain_scan.nii.gz --outfile anonymized_scan.nii.gz --force # Apply the computed face mask to additional images (e.g., other modalities) pydeface T1w.nii.gz --applyto T2w.nii.gz FLAIR.nii.gz # Use a different FSL-FLIRT cost function (default: mutualinfo) pydeface brain_scan.nii.gz --cost corratio # Keep temporary registration files for inspection pydeface brain_scan.nii.gz --nocleanup # Enable verbose output and debug mode pydeface brain_scan.nii.gz --verbose --debug # Use custom template and face mask pydeface brain_scan.nii.gz --template custom_template.nii.gz --facemask custom_mask.nii.gz ``` -------------------------------- ### Run PyDeface on an input file Source: https://github.com/poldracklab/pydeface/blob/master/README.md Basic command-line usage of PyDeface to process an input MRI image file. Replace 'infile.nii.gz' with your actual file name. ```bash pydeface infile.nii.gz ``` -------------------------------- ### pydeface.utils.generate_tmpfiles Source: https://context7.com/poldracklab/pydeface/llms.txt Creates temporary files required for the registration process, including template registration outputs and masks. ```APIDOC ## pydeface.utils.generate_tmpfiles ### Description Creates temporary files needed for the registration process. Returns paths to template registration output, transformation matrix, warped mask, and warped mask matrix. ### Parameters #### Query Parameters - **verbose** (boolean) - Optional - If True, prints paths of generated temporary files. ``` -------------------------------- ### Programmatic Defacing with pydeface.utils.deface_image Source: https://context7.com/poldracklab/pydeface/llms.txt Use this function to integrate defacing into Python pipelines. It handles registration, mask warping, and optional file cleanup. ```python import pydeface.utils as pdu # Basic usage - deface a single image warped_mask_img, warped_mask, template_reg, template_reg_mat = pdu.deface_image( infile='path/to/T1w.nii.gz' ) # Output: Creates T1w_defaced.nii.gz in same directory # Full control with all options warped_mask_img, warped_mask, template_reg, template_reg_mat = pdu.deface_image( infile='path/to/brain.nii.gz', outfile='path/to/brain_anonymized.nii.gz', # Custom output path cost='mutualinfo', # FSL-FLIRT cost function force=True, # Overwrite existing output verbose=True # Print status messages ) # Cleanup temporary files after processing pdu.cleanup_files(warped_mask, template_reg, template_reg_mat) # Auto-cleanup with forcecleanup option (returns only mask image) warped_mask_img = pdu.deface_image( infile='path/to/brain.nii.gz', forcecleanup=True ) # Use custom template and face mask warped_mask_img = pdu.deface_image( infile='path/to/brain.nii.gz', template='path/to/custom_template.nii.gz', facemask='path/to/custom_facemask.nii.gz', forcecleanup=True ) ``` -------------------------------- ### Output Path Validation with pydeface.utils.output_checks Source: https://context7.com/poldracklab/pydeface/llms.txt Generate and validate output filenames. This utility handles default naming conventions and checks for existing files to prevent accidental overwrites. ```python import pydeface.utils as pdu # Default output naming - adds '_defaced' suffix outfile = pdu.output_checks(infile='scan.nii.gz') print(outfile) # Output: scan_defaced.nii.gz outfile = pdu.output_checks(infile='scan.nii') print(outfile) # Output: scan_defaced.nii # Custom output path outfile = pdu.output_checks( infile='scan.nii.gz', outfile='anonymized/output.nii.gz' ) # Handle existing output files try: outfile = pdu.output_checks(infile='scan.nii.gz') except Exception as e: print(f"Error: {e}") # "scan_defaced.nii.gz already exists. Remove it first or use '--force' flag to overwrite." ``` -------------------------------- ### Apply Mask to Multiple Images Source: https://context7.com/poldracklab/pydeface/llms.txt Applies a generated face mask to additional images in the same space. ```python import numpy as np from nibabel import Nifti1Image, load import pydeface.utils as pdu # First, deface the primary T1w image and keep the mask warped_mask_img, warped_mask, template_reg, template_reg_mat = pdu.deface_image( infile='T1w.nii.gz', outfile='T1w_defaced.nii.gz' ) # Apply the same mask to other images in the same space additional_images = ['T2w.nii.gz', 'FLAIR.nii.gz', 'PD.nii.gz'] for img_path in additional_images: # Load the image and mask data img = load(img_path) img_data = np.asarray(img.dataobj) mask_data = np.asarray(warped_mask_img.dataobj) # Apply mask try: defaced_data = img_data * mask_data except ValueError: # Handle 4D images (e.g., fMRI) mask_4d = np.stack([mask_data] * img_data.shape[-1], axis=-1) defaced_data = img_data * mask_4d # Save defaced image defaced_img = Nifti1Image(defaced_data, img.affine, img.header) outfile = pdu.output_checks(img_path, force=True) defaced_img.to_filename(outfile) print(f"Saved: {outfile}") # Cleanup temporary files pdu.cleanup_files(warped_mask, template_reg, template_reg_mat) ``` -------------------------------- ### pydeface.utils.output_checks Source: https://context7.com/poldracklab/pydeface/llms.txt Determines and validates the output file path for the defaced image. ```APIDOC ## pydeface.utils.output_checks ### Description Generates a default output filename if none is provided and checks if the file already exists to prevent accidental overwriting. ### Parameters #### Request Body - **infile** (string) - Required - Path to the input file. - **outfile** (string) - Optional - Desired output path. ### Response - **outfile** (string) - The validated output file path. ``` -------------------------------- ### pydeface.utils.cleanup_files Source: https://context7.com/poldracklab/pydeface/llms.txt Removes temporary files created during the defacing process, safely handling non-existent files. ```APIDOC ## pydeface.utils.cleanup_files ### Description Removes temporary files created during the defacing process. Safely handles non-existent files. ### Parameters #### Request Body - **files** (string/list) - Required - Paths to the files to be removed. ``` -------------------------------- ### Cleanup Temporary Files Source: https://context7.com/poldracklab/pydeface/llms.txt Removes temporary files safely, even if they do not exist. ```python import pydeface.utils as pdu # Clean up single file pdu.cleanup_files('/tmp/registration.mat') # Output: Cleaning up... # Clean up multiple files at once pdu.cleanup_files( '/tmp/template_reg.nii.gz', '/tmp/registration.mat', '/tmp/warped_mask.nii.gz' ) # Safe to call on non-existent files (no error raised) pdu.cleanup_files('/tmp/nonexistent_file.nii.gz') ``` -------------------------------- ### pydeface.utils.get_outfile_type Source: https://context7.com/poldracklab/pydeface/llms.txt Determines the FSL output type string based on the provided file extension. ```APIDOC ## pydeface.utils.get_outfile_type ### Description Returns the FSL output type string based on file extension. Used internally for FSL-FLIRT configuration. ### Parameters #### Request Body - **infile** (string) - Required - The path to the file to check. ### Response #### Success Response (200) - **output_type** (string) - The FSL output type (e.g., NIFTI, NIFTI_GZ). ``` -------------------------------- ### pydeface.utils.deface_image Source: https://context7.com/poldracklab/pydeface/llms.txt The primary function for defacing MRI images. It registers a template to the input image, warps a face mask, and applies it to the input scan. ```APIDOC ## pydeface.utils.deface_image ### Description Registers a template to the input image, warps a face mask accordingly, and applies it to remove facial features. Returns the warped mask image and optionally paths to temporary files. ### Parameters #### Request Body - **infile** (string) - Required - Path to the input NIfTI file. - **outfile** (string) - Optional - Custom output path for the defaced image. - **cost** (string) - Optional - FSL-FLIRT cost function (default: mutualinfo). - **force** (boolean) - Optional - Whether to overwrite existing output files. - **verbose** (boolean) - Optional - Enable status messages. - **template** (string) - Optional - Path to custom template file. - **facemask** (string) - Optional - Path to custom face mask file. - **forcecleanup** (boolean) - Optional - Automatically clean up temporary files. ### Response - **warped_mask_img** (object) - The warped mask image. - **warped_mask** (string) - Path to the warped mask file. - **template_reg** (string) - Path to the registered template file. - **template_reg_mat** (string) - Path to the registration matrix file. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.