Exemplo n.º 1
0
    def _get_file_wrapper(self):
        """Return the FileWrapper representing this image, creating it if
        it does not already exist. """

        if not self._file_wrapper:
            header = self._get_header()
            filename_raw = os.path.join(self._input_path,
                                        header["ElementDataFile"])
            self._file_wrapper = FileWrapper(filename_raw,
                                             self._file_handle_factory,
                                             self._mode)
        return self._file_wrapper
Exemplo n.º 2
0
    def _get_file_wrapper(self):
        """Return the FileWrapper representing this image, creating it if
        it does not already exist. """

        if not self._file_wrapper:
            header = self._get_header()
            file_section = header["VolumeSection0\\_FileSection0"]
            vol_name = file_section["filename"]
            # pylint: disable=unused-variable
            vol_path, vol_raw = os.path.split(vol_name)
            filename_raw = os.path.realpath(
                os.path.join(self._input_path, '..', vol_raw))
            self._file_wrapper = FileWrapper(filename_raw,
                                             self._file_handle_factory,
                                             self._mode)
        return self._file_wrapper
Exemplo n.º 3
0
class MetaIoFile(LinearImageFileReader):
    """A class for reading or writing 3D imaging data to/from a MetaIO file
    pair (.mhd and .raw). """

    # pylint: disable=too-many-instance-attributes

    def __init__(self, local_file_size, header_filename, file_handle_factory,
                 header_template):
        super(MetaIoFile, self).__init__(local_file_size)
        self._file_handle_factory = file_handle_factory
        self._header_filename = header_filename
        self._input_path = os.path.dirname(os.path.abspath(header_filename))
        self._file_wrapper = None
        self._file_streamer = None
        if header_template:
            # File is for writing
            self._mode = 'wb'
            # Force the raw filename to match the header filename
            base_filename = os.path.splitext(
                os.path.basename(header_filename))[0]
            header = copy.deepcopy(header_template)
            header['ElementDataFile'] = base_filename + '.raw'

            save_mhd_header(header_filename, header)
            self._header = header

        else:
            # File is for reading
            self._mode = 'rb'
            self._header = load_mhd_header(header_filename)

        self._bytes_per_voxel = compute_bytes_per_voxel(
            self._header["ElementType"]
        )  # ToDo: set this based on output format
        self._numpy_format = get_numpy_datatype(
            self._header["ElementType"],
            self._header["BinaryDataByteOrderMSB"])
        self._subimage_size = self._header["DimSize"]
        self._dimension_ordering = get_dimension_ordering(self._header)

    @classmethod
    def load_and_parse_header(cls, filename):
        """Reads a MetaIO header file and parses"""

        header = load_mhd_header(filename)
        return parse_mhd(header)

    @classmethod
    def create_read_file(cls, subimage_descriptor, file_handle_factory):
        """Create a MetaIoFile class for writing"""

        filename = subimage_descriptor.filename
        local_file_size = subimage_descriptor.ranges.image_size
        return cls(local_file_size, filename, file_handle_factory, None)

    @classmethod
    def create_write_file(cls, subimage_descriptor, file_handle_factory):
        """Create a MetaIoFile class for this filename and template"""

        header_template = copy.deepcopy(subimage_descriptor.template)
        local_file_size = subimage_descriptor.get_local_size()
        local_origin = subimage_descriptor.get_local_origin()

        if subimage_descriptor.data_type:
            header_template["ElementType"] = subimage_descriptor.data_type
        header_template["DimSize"] = local_file_size
        header_template["Origin"] = local_origin
        filename = subimage_descriptor.filename
        return cls(local_file_size, filename, file_handle_factory,
                   header_template)

    def close_file(self):
        """Close file"""
        self.close()

    def write_line(self, start_coords, image_line, rescale_limits):
        """Write consecutive voxels to the raw binary file."""

        return self._get_file_streamer().write_line(start_coords, image_line,
                                                    rescale_limits)

    def read_line(self, start_coords, num_voxels_to_read):
        """Read consecutive voxels of image data from the raw binary file
        starting at the specified coordinates. """

        return self._get_file_streamer().read_line(start_coords,
                                                   num_voxels_to_read)

    def get_bytes_per_voxel(self):
        """Return the number of bytes used to represent a single voxel in
        this image. """

        header = self._get_header()
        return compute_bytes_per_voxel(header["ElementType"])

    def get_dimension_ordering(self):
        """
        Return the preferred dimension ordering for writing data.

        Returns an array of 3 element, where each element represents a
        dimension in the global coordinate system numbered from 1 to 3 and
        is positive if data are to be written in ascending coordinates (in
        the global system) or negative if to be written in descending global
        coordinates along that dimension
        """

        return self._dimension_ordering

    def _get_header(self):
        """Return an OrderedDict containing the MetaIO metaheader metadata
        for this image. """

        if not self._header:
            self._header = load_mhd_header(self._header_filename)
        return self._header

    def _get_file_wrapper(self):
        """Return the FileWrapper representing this image, creating it if
        it does not already exist. """

        if not self._file_wrapper:
            header = self._get_header()
            filename_raw = os.path.join(self._input_path,
                                        header["ElementDataFile"])
            self._file_wrapper = FileWrapper(filename_raw,
                                             self._file_handle_factory,
                                             self._mode)
        return self._file_wrapper

    def _get_file_streamer(self):
        """Return the FileStreamer representing this image, creating it
        if it does not already exist. """

        if not self._file_streamer:
            self._file_streamer = FileStreamer(self._get_file_wrapper(),
                                               self._subimage_size,
                                               self._bytes_per_voxel,
                                               self._numpy_format,
                                               self._dimension_ordering)
        return self._file_streamer

    def close(self):
        """Close the files associated with this image, if they are not
        already closed. """

        if self._file_streamer:
            self._file_streamer.close()
            self._file_streamer = None
        if self._file_wrapper:
            self._file_wrapper.close()
            self._file_wrapper = None
Exemplo n.º 4
0
class VolFile(LinearImageFileReader):
    """A class for reading or writing 3D imaging data to/from a MetaIO file
    pair (.mhd and .raw). """

    # pylint: disable=too-many-instance-attributes

    def __init__(self, local_image_size, header_filename, file_handle_factory):
        super(VolFile, self).__init__(local_image_size)
        self._file_handle_factory = file_handle_factory
        self._header_filename = header_filename
        self._input_path = os.path.dirname(os.path.abspath(header_filename))
        self._file_wrapper = None
        self._file_streamer = None
        # File is for reading
        self._mode = 'rb'
        self._header = load_vge_header(header_filename)

        file_section = self._header["VolumeSection0\\_FileSection0"]
        self._bytes_per_voxel = compute_bytes_per_voxel(
            file_section["filedatatype"])
        self._numpy_format = get_numpy_datatype(file_section["filedatatype"],
                                                file_section["fileendian"])
        self._subimage_size = [
            int(s) for s in file_section["filesize"].split()
        ]
        self._dimension_ordering = dim_order_from_header(self._header)

    @staticmethod
    def create_read_file(subimage_descriptor, file_handle_factory):
        """Create a MetaIoFile class for writing"""

        filename = subimage_descriptor.filename
        local_file_size = subimage_descriptor.ranges.image_size
        return VolFile(local_file_size, filename, file_handle_factory)

    def close_file(self):
        """Close file"""
        self.close()

    # pylint: disable=unused-argument
    def write_line(self, start_coords, image_line, rescale_limits):
        """Write consecutive voxels to the raw binary file."""

        raise ValueError("Writing of vol files is not supported")

    def read_line(self, start_coords, num_voxels_to_read):
        """Read consecutive voxels of image data from the raw binary file
        starting at the specified coordinates. """

        return self._get_file_streamer().read_line(start_coords,
                                                   num_voxels_to_read)

    def get_bytes_per_voxel(self):
        """Return the number of bytes used to represent a single voxel in
        this image. """

        header = self._get_header()
        return compute_bytes_per_voxel(header["FileDataType"])

    def get_dimension_ordering(self):
        """
        Return the preferred dimension ordering for writing data.

        Returns an array of 3 element, where each element represents a
        dimension in the global coordinate system numbered from 1 to 3 and
        is positive if data are to be written in ascending coordinates (in
        the global system) or negative if to be written in descending global
        coordinates along that dimension
        """

        return self._dimension_ordering

    def _get_header(self):
        """Return an OrderedDict containing the MetaIO metaheader metadata
        for this image. """

        if not self._header:
            self._header = load_vge_header(self._header_filename)
        return self._header

    def _get_file_wrapper(self):
        """Return the FileWrapper representing this image, creating it if
        it does not already exist. """

        if not self._file_wrapper:
            header = self._get_header()
            file_section = header["VolumeSection0\\_FileSection0"]
            vol_name = file_section["filename"]
            # pylint: disable=unused-variable
            vol_path, vol_raw = os.path.split(vol_name)
            filename_raw = os.path.realpath(
                os.path.join(self._input_path, '..', vol_raw))
            self._file_wrapper = FileWrapper(filename_raw,
                                             self._file_handle_factory,
                                             self._mode)
        return self._file_wrapper

    def _get_file_streamer(self):
        """Return the FileStreamer representing this image, creating it
        if it does not already exist. """

        if not self._file_streamer:
            self._file_streamer = FileStreamer(self._get_file_wrapper(),
                                               self._subimage_size,
                                               self._bytes_per_voxel,
                                               self._numpy_format,
                                               self._dimension_ordering)
        return self._file_streamer

    def close(self):
        """Close the files associated with this image, if they are not
        already closed. """

        if self._file_streamer:
            self._file_streamer.close()
            self._file_streamer = None
        if self._file_wrapper:
            self._file_wrapper.close()
            self._file_wrapper = None

    @classmethod
    def load_and_parse_header(cls, filename):
        """Load vge header file and parse into FileImageDescriptor"""

        header = load_vge_header(filename)
        return parse_vge(header)