You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

193 lines
5.4 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
  1. from pims.base_frames import FramesSequenceND
  2. from nd2reader.exceptions import EmptyFileError
  3. from nd2reader.parser import Parser
  4. import numpy as np
  5. class ND2Reader(FramesSequenceND):
  6. """PIMS wrapper for the ND2 parser.
  7. This is the main class: use this to process your .nd2 files.
  8. """
  9. class_priority = 12
  10. def __init__(self, filename):
  11. super(self.__class__, self).__init__()
  12. self.filename = filename
  13. # first use the parser to parse the file
  14. self._fh = open(filename, "rb")
  15. self._parser = Parser(self._fh)
  16. # Setup metadata
  17. self.metadata = self._parser.metadata
  18. # Set data type
  19. self._dtype = self._parser.get_dtype_from_metadata()
  20. # Setup the axes
  21. self._setup_axes()
  22. # Other properties
  23. self._timesteps = None
  24. @classmethod
  25. def class_exts(cls):
  26. """Let PIMS open function use this reader for opening .nd2 files
  27. """
  28. return {'nd2'} | super(ND2Reader, cls).class_exts()
  29. def close(self):
  30. """Correctly close the file handle
  31. """
  32. if self._fh is not None:
  33. self._fh.close()
  34. def _get_default(self, coord):
  35. try:
  36. return self.default_coords[coord]
  37. except KeyError:
  38. return 0
  39. def get_frame_2D(self, c=0, t=0, z=0, x=0, y=0, v=0):
  40. """Gets a given frame using the parser
  41. Args:
  42. x: The x-index (pims expects this)
  43. y: The y-index (pims expects this)
  44. c: The color channel number
  45. t: The frame number
  46. z: The z stack number
  47. v: The field of view index
  48. Returns:
  49. numpy.ndarray: The requested frame
  50. """
  51. try:
  52. c_name = self.metadata["channels"][c]
  53. except KeyError:
  54. c_name = self.metadata["channels"][0]
  55. x = self.metadata["width"] if x <= 0 else x
  56. y = self.metadata["height"] if y <= 0 else y
  57. return self._parser.get_image_by_attributes(t, v, c_name, z, y, x)
  58. @property
  59. def parser(self):
  60. """
  61. Returns the parser object.
  62. Returns:
  63. Parser: the parser object
  64. """
  65. return self._parser
  66. @property
  67. def pixel_type(self):
  68. """Return the pixel data type
  69. Returns:
  70. dtype: the pixel data type
  71. """
  72. return self._dtype
  73. @property
  74. def timesteps(self):
  75. """Get the timesteps of the experiment
  76. Returns:
  77. np.ndarray: an array of times in milliseconds.
  78. """
  79. if self._timesteps is None:
  80. return self.get_timesteps()
  81. return self._timesteps
  82. @property
  83. def frame_rate(self):
  84. """The (average) frame rate
  85. Returns:
  86. float: the (average) frame rate in frames per second
  87. """
  88. total_duration = 0.0
  89. for loop in self.metadata['experiment']['loops']:
  90. total_duration += loop['duration']
  91. if total_duration == 0:
  92. raise ValueError('Total measurement duration could not be determined from loops')
  93. return self.metadata['num_frames'] / (total_duration/1000.0)
  94. def _get_metadata_property(self, key, default=None):
  95. if self.metadata is None:
  96. return default
  97. if key not in self.metadata:
  98. return default
  99. if self.metadata[key] is None:
  100. return default
  101. return self.metadata[key]
  102. def _setup_axes(self):
  103. """Setup the xyctz axes, iterate over t axis by default
  104. """
  105. self._init_axis_if_exists('x', self._get_metadata_property("width", default=0))
  106. self._init_axis_if_exists('y', self._get_metadata_property("height", default=0))
  107. self._init_axis_if_exists('c', len(self._get_metadata_property("channels", default=[])), min_size=2)
  108. self._init_axis_if_exists('t', len(self._get_metadata_property("frames", default=[])))
  109. self._init_axis_if_exists('z', len(self._get_metadata_property("z_levels", default=[])), min_size=2)
  110. self._init_axis_if_exists('v', len(self._get_metadata_property("fields_of_view", default=[])), min_size=2)
  111. if len(self.sizes) == 0:
  112. raise EmptyFileError("No axes were found for this .nd2 file.")
  113. # provide the default
  114. self.iter_axes = self._guess_default_iter_axis()
  115. def _init_axis_if_exists(self, axis, size, min_size=1):
  116. if size >= min_size:
  117. self._init_axis(axis, size)
  118. def _guess_default_iter_axis(self):
  119. """
  120. Guesses the default axis to iterate over based on axis sizes.
  121. Returns:
  122. the axis to iterate over
  123. """
  124. priority = ['t', 'z', 'c', 'v']
  125. found_axes = []
  126. for axis in priority:
  127. try:
  128. current_size = self.sizes[axis]
  129. except KeyError:
  130. continue
  131. if current_size > 1:
  132. return axis
  133. found_axes.append(axis)
  134. return found_axes[0]
  135. def get_timesteps(self):
  136. """Get the timesteps of the experiment
  137. Returns:
  138. np.ndarray: an array of times in milliseconds.
  139. """
  140. if self._timesteps is not None and len(self._timesteps) > 0:
  141. return self._timesteps
  142. self._timesteps = np.array(list(self._parser._raw_metadata.acquisition_times), dtype=np.float) * 1000.0
  143. return self._timesteps