Esempio n. 1
0
def read_hdf5(filename, ondisk=False, dsetname=DEFAULT_DSETNAME):
    """Read an array with attributes from an HDF5 file.

    With parameter "ondisk" True it will not be read into memory."""
    try:
        f = h5py.File(filename, 'r')
    # On missing file, h5py raises OSError without errno (or filename).
    except OSError as e:
        if not Path(filename).exists():
            raise FileNotFoundError(2, 'No such file or directory', filename)
        e.filename = e.filename or filename
        raise
    except IOError as e:
        e.filename = e.filename or filename
        raise
    if dsetname not in f:
        # No dataset of given name, try the one there is.
        try:
            dsetname, = f.keys()
        except ValueError:
            raise ValueError('Ambiguous content: {}'.format(filename))
    dset = f[dsetname]
    if ondisk:
        array = dset
    else:
        array = np.array(dset)
    attrs = read_attrs(dset)
    if not ondisk:
        f.close()
    return array, attrs
Esempio n. 2
0
def read_lmask(mode, case, scan):
    mode = ImageMode(mode)
    paths = []
    try:
        for i in range(1, 4):
            path = Path(dwi.paths.mask_path(mode, 'lesion', case, scan,
                                            lesion=i))
            if path.exists():
                paths.append(path)
    except IOError:
        pass
    masks = [dwi.files.read_mask(x) for x in paths]

    # # Manually override slice index.
    # slice_indices = {
    #     (64, '1a', 'T2w-std'): 7,
    #     (64, '1a', 'T2-fitted'): 5,
    #     }

    # slice_index = slice_indices.get((case, scan, str(mode)))
    slice_index = None
    lmask, img_slice = get_lesion_mask(masks, slice_index=slice_index)
    return lmask, img_slice, [x[img_slice] for x in masks]
Esempio n. 3
0
def main():
    """Main."""
    args = parse_args()
    logging.basicConfig()
    # logging.basicConfig(level=logging.INFO)

    # thresholds = None
    # thresholds = ('3+3', '3+4')
    thresholds = ('3+3', )
    blacklist = []  # + [21, 22, 27, 42, 74, 79]
    # whitelist = []  # + [23, 24, 26, 29, 64]
    whitelist = [26, 42, 64]

    for i, line in enumerate(dwi.files.valid_lines(args.featlist)):
        words = line.split()
        mode = words[0]
        texture_spec = TextureSpec(*words[1:])
        it = cases_scans_lesions(mode, args.samplelist, thresholds=thresholds)
        for c, s, l in it:
            if blacklist and c in blacklist:
                continue
            if whitelist and c not in whitelist:
                continue
            # if 0 not in (x.label for x in l):
            #     continue  # Exclude if there's no first score group present.
            print(i, mode, texture_spec, c, s, l)
            try:
                images, _ = read(mode, c, s, texture_spec)
            except IOError as e:
                logging.error(e)
                continue

            labelnames = ['low', 'high']
            lesions = ', '.join(
                '{} {} {}'.format(x.score, x.location, labelnames[x.label])
                for x in l)
            d = dict(m=mode,
                     c=c,
                     s=s,
                     l=lesions,
                     tw=texture_spec.winsize,
                     tm=texture_spec.method,
                     tf=texture_spec.feature,
                     suffix='png')
            title = '{c}-{s} ({l})\n{m} {tm}({tf})-{tw}'.format(**d)
            path = '{c:03}-{s}_{m}_{tm}({tf})-{tw}.{suffix}'.format(**d)
            plot(images, title, Path(args.outdir, path))
Esempio n. 4
0
import argparse
# import logging

import dwi.autoroi
import dwi.dataset
import dwi.mask
import dwi.patient
import dwi.util
from dwi.types import AlgParams, Path

# import matplotlib
import matplotlib.pyplot as plt
import numpy as np

DEFAULT_OUT_IMAGE_DIR = Path('find_roi_images')
DEFAULT_OUT_MASK_DIR = Path('masks_auto')


def parse_args():
    """Parse command-line arguments."""
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('-v', '--verbose', action='count',
                   help='increase verbosity')
    p.add_argument('--patients', type=Path,
                   help='patients file')
    p.add_argument('--pmapdir', type=Path,
                   help='input parametric map directory')
    p.add_argument('--subregiondir', type=Path,
                   help='subregion bounding box directory')
    p.add_argument('--prostatemaskdir', type=Path,
Esempio n. 5
0
#!/usr/bin/python3
"""List lesion statistics."""

from collections import OrderedDict
from itertools import product

import dwi.dataset
import dwi.image
from dwi.types import ImageMode, Path
import numpy as np
from tabulate import tabulate

BASE = Path('/mri')
LIST = 'misc/list/all.txt'


def read_cases():
    return sorted(int(x) for x in (BASE / LIST).read_text().split())


def read_lmasks(paths, case, scan):
    for les in [1, 2, 3]:
        try:
            yield dwi.image.Image.read_mask(
                paths.mask('lesion', case, scan, les))
        except OSError:
            yield None


def get_image_stats(paths, case, scan):
    try:
Esempio n. 6
0
    # logging.info(masks[-1][1])
    # logging.info(len(parse_mask(masks[-1][1])))
    for i, m in enumerate(masks, 1):
        number, mask = m
        logging.info('Mask: %i, $i', number, len(mask))
        mask = parse_mask(mask)
        try:
            mask.shape = shape + (1,)
        except ValueError as e:
            logging.error('%s: %s', e, path)
            continue
        assert mask.ndim == 4, mask.shape
        outname = '{p}.{i:02d}-{n}.{f}'.format(p=path.name, i=i, n=number,
                                               f=fmt)
        outpath = outdir / outname
        attrs = {}
        print('Writing mask shape {}: {}'.format(mask.shape, outpath))
        dwi.files.ensure_dir(outpath)
        dwi.files.write_pmap(outpath, mask, attrs)


if __name__ == '__main__':
    # Arguments: input file; output directory; shape (eg 20,224,224).
    logging.basicConfig(level=logging.INFO)
    path, outdir, shape = sys.argv[1:]
    logging.info(path, outdir, shape, sys.argv[1:])
    path = Path(path)
    shape = tuple(int(x) for x in shape.split(','))
    outdir = Path(outdir)
    main(path, shape, outdir)