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.

234 lines
6.2 KiB

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