Skip to content

Commit

Permalink
Merge pull request #14 from ofgulban/master
Browse files Browse the repository at this point in the history
pep 8 & pep 257 style improvements and some cleanup
  • Loading branch information
chrisgorgo authored Dec 1, 2017
2 parents b6c8468 + bdabf73 commit 240912f
Show file tree
Hide file tree
Showing 4 changed files with 233 additions and 175 deletions.
104 changes: 104 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/

# Translations
*.mo
*.pot

# Django stuff:
*.log
.static_storage/
.media/
local_settings.py

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
18 changes: 9 additions & 9 deletions pydeface/utils.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
"""
util scripts for pydeface
"""
"""Utility scripts for pydeface."""

import sys
import subprocess


def run_shell_cmd(cmd,cwd=[]):
""" run a command in the shell using Popen
"""
def run_shell_cmd(cmd, cwd=[]):
"""Run a command in the shell using Popen."""
if cwd:
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,cwd=cwd)
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
cwd=cwd)
else:
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in process.stdout:
print line.strip()
print(line.strip())
process.wait()


def usage():
""" print the docstring and exit"""
"""Print the docstring and exit."""
sys.stdout.write(__doc__)
sys.exit(2)
185 changes: 82 additions & 103 deletions scripts/pydeface.py
Original file line number Diff line number Diff line change
@@ -1,143 +1,122 @@
#!/usr/bin/env python
""" deface an image using FSL
USAGE: deface <filename to deface> <optional: outfilename>
"""

## Copyright 2011, Russell Poldrack. All rights reserved.

## Redistribution and use in source and binary forms, with or without modification, are
## permitted provided that the following conditions are met:
"""Deface an image using FSL.
## 1. Redistributions of source code must retain the above copyright notice, this list of
## conditions and the following disclaimer.

## 2. Redistributions in binary form must reproduce the above copyright notice, this list
## of conditions and the following disclaimer in the documentation and/or other materials
## provided with the distribution.

## THIS SOFTWARE IS PROVIDED BY RUSSELL POLDRACK ``AS IS'' AND ANY EXPRESS OR IMPLIED
## WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
## FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RUSSELL POLDRACK OR
## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
## SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
## ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
## NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Usage:
------
pydeface.py <filename to deface> <optional: outfilename>
"""

# Copyright 2011, Russell Poldrack. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY RUSSELL POLDRACK ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL RUSSELL POLDRACK OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import nibabel
import os,sys
import numpy as N
import os
import sys
import tempfile
import subprocess
import inspect
from nipype.interfaces import fsl
from pkg_resources import resource_filename,Requirement

def run_shell_cmd(cmd,cwd=[]):
""" run a command in the shell using Popen
"""
if cwd:
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,cwd=cwd)
else:
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in process.stdout:
print((line.strip()))
process.wait()

def usage():
""" print the docstring and exit"""
sys.stdout.write(__doc__)
sys.exit(2)
from pkg_resources import resource_filename, Requirement, require


def main():
cleanup=True
verbose=False
scriptdir=os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # script directory

template=resource_filename(Requirement.parse("pydeface"), 'pydeface/data/mean_reg2mean.nii.gz')
facemask=resource_filename(Requirement.parse("pydeface"), "pydeface/data/facemask.nii.gz")

try:
assert os.path.exists(facemask)
except:
raise Exception('missing facemask: %s'%facemask)
cleanup, verbose = True, False

try:
assert os.path.exists(template)
except:
raise Exception('missing template: %s'%template)
template = resource_filename(Requirement.parse("pydeface"),
"pydeface/data/mean_reg2mean.nii.gz")
facemask = resource_filename(Requirement.parse("pydeface"),
"pydeface/data/facemask.nii.gz")

if not os.path.exists(template):
raise Exception('Missing template: %s' % template)
if not os.path.exists(facemask):
raise Exception('Missing face mask: %s' % facemask)


if len(sys.argv)<2:
usage()
if len(sys.argv) < 2:
sys.stdout.write(__doc__)
sys.exit(2)
else:
infile=sys.argv[1]
infile = sys.argv[1]

if len(sys.argv)>2:
outfile=sys.argv[2]
else:
outfile=infile.replace('.nii.gz','_defaced.nii.gz')
try:
assert not os.path.exists(outfile)
except:
raise Exception('%s already exists, remove it first'%outfile)

if 'FSLDIR' in os.environ:
FSLDIR=os.environ['FSLDIR']
if len(sys.argv) > 2:
outfile = sys.argv[2]
else:
print('FSL must be installed and FSLDIR environment variable must be defined')
sys.exit(2)
outfile = infile.replace('.nii', '_defaced.nii')

if os.path.exists(outfile):
raise Exception('%s already exists, remove it first.' % outfile)

if 'FSLDIR' not in os.environ:
raise Exception("FSL must be installed and "
"FSLDIR environment variable must be defined.")
sys.exit(2)

foo,tmpmat=tempfile.mkstemp()
tmpmat=tmpmat+'.mat'
foo,tmpfile=tempfile.mkstemp()
tmpfile=tmpfile+'.nii.gz'
_, tmpmat = tempfile.mkstemp()
tmpmat = tmpmat + '.mat'
_, tmpfile = tempfile.mkstemp()
tmpfile = tmpfile + '.nii.gz'
if verbose:
print(tmpmat)
print(tmpfile)
foo,tmpfile2=tempfile.mkstemp()
foo,tmpmat2=tempfile.mkstemp()
_, tmpfile2 = tempfile.mkstemp()
_, tmpmat2 = tempfile.mkstemp()

print(('defacing', infile))
# register template to infile
print('Defacing...\n%s' % infile)

flirt=fsl.FLIRT()
flirt.inputs.cost_func='mutualinfo'
flirt.inputs.in_file=template
flirt.inputs.out_matrix_file=tmpmat
flirt.inputs.out_file=tmpfile2
flirt.inputs.reference=infile
# register template to infile
flirt = fsl.FLIRT()
flirt.inputs.cost_func = 'mutualinfo'
flirt.inputs.in_file = template
flirt.inputs.out_matrix_file = tmpmat
flirt.inputs.out_file = tmpfile2
flirt.inputs.reference = infile
flirt.run()

# warp facemask to infile
flirt=fsl.FLIRT()
flirt.inputs.in_file=facemask
flirt.inputs.in_matrix_file=tmpmat
flirt.inputs.apply_xfm=True
flirt.inputs.reference=infile
flirt.inputs.out_file=tmpfile
flirt.inputs.out_matrix_file=tmpmat2
flirt = fsl.FLIRT()
flirt.inputs.in_file = facemask
flirt.inputs.in_matrix_file = tmpmat
flirt.inputs.apply_xfm = True
flirt.inputs.reference = infile
flirt.inputs.out_file = tmpfile
flirt.inputs.out_matrix_file = tmpmat2
flirt.run()

# multiply mask by infile and save

infile_img=nibabel.load(infile)
tmpfile_img=nibabel.load(tmpfile)
outdata=infile_img.get_data()*tmpfile_img.get_data()
outfile_img=nibabel.Nifti1Image(outdata,infile_img.get_affine(),infile_img.get_header())
infile_img = nibabel.load(infile)
tmpfile_img = nibabel.load(tmpfile)
outdata = infile_img.get_data() * tmpfile_img.get_data()
outfile_img = nibabel.Nifti1Image(outdata, infile_img.get_affine(),
infile_img.get_header())
outfile_img.to_filename(outfile)

if cleanup:
os.remove(tmpfile)
os.remove(tmpfile2)
os.remove(tmpmat)

print('Output saved as:\n%s' % outfile)


if __name__ == "__main__":
welcome_str = 'pydeface ' + require("pydeface")[0].version
welcome_decor = '-' * len(welcome_str)
print(welcome_decor + '\n' + welcome_str + '\n' + welcome_decor)
main()
Loading

0 comments on commit 240912f

Please sign in to comment.