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.

207 lines
5.8 KiB

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. class_priority = 12
  11. def __init__(self, filename):
  12. super(ND2Reader, self).__init__()
  13. if not filename.endswith(".nd2"):
  14. raise InvalidFileType("The file %s you want to read with nd2reader does not have extension .nd2." % filename)
  15. self.filename = filename
  16. # first use the parser to parse the file
  17. self._fh = open(filename, "rb")
  18. self._parser = Parser(self._fh)
  19. # Setup metadata
  20. self.metadata = self._parser.metadata
  21. # Set data type
  22. self._dtype = self._parser.get_dtype_from_metadata()
  23. # Setup the axes
  24. self._setup_axes()
  25. # Other properties
  26. self._timesteps = None
  27. @classmethod
  28. def class_exts(cls):
  29. """Let PIMS open function use this reader for opening .nd2 files
  30. """
  31. return {'nd2'} | super(ND2Reader, cls).class_exts()
  32. def close(self):
  33. """Correctly close the file handle
  34. """
  35. if self._fh is not None:
  36. self._fh.close()
  37. def _get_default(self, coord):
  38. try:
  39. return self.default_coords[coord]
  40. except KeyError:
  41. return 0
  42. def get_frame_2D(self, c=0, t=0, z=0, x=0, y=0, v=0):
  43. """Gets a given frame using the parser
  44. Args:
  45. x: The x-index (pims expects this)
  46. y: The y-index (pims expects this)
  47. c: The color channel number
  48. t: The frame number
  49. z: The z stack number
  50. v: The field of view index
  51. Returns:
  52. pims.Frame: The requested frame
  53. """
  54. # This needs to be set to width/height to return an image
  55. x = self.metadata["width"]
  56. y = self.metadata["height"]
  57. return self._parser.get_image_by_attributes(t, v, c, 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 events(self):
  84. """Get the events of the experiment
  85. Returns:
  86. iterator of events as dict
  87. """
  88. return self._get_metadata_property("events")
  89. @property
  90. def frame_rate(self):
  91. """The (average) frame rate
  92. Returns:
  93. float: the (average) frame rate in frames per second
  94. """
  95. total_duration = 0.0
  96. for loop in self.metadata['experiment']['loops']:
  97. total_duration += loop['duration']
  98. if total_duration == 0:
  99. total_duration = self.timesteps[-1]
  100. if total_duration == 0:
  101. raise ValueError('Total measurement duration could not be determined from loops')
  102. return self.metadata['num_frames'] / (total_duration/1000.0)
  103. def _get_metadata_property(self, key, default=None):
  104. if self.metadata is None:
  105. return default
  106. if key not in self.metadata:
  107. return default
  108. if self.metadata[key] is None:
  109. return default
  110. return self.metadata[key]
  111. def _setup_axes(self):
  112. """Setup the xyctz axes, iterate over t axis by default
  113. """
  114. self._init_axis_if_exists('x', self._get_metadata_property("width", default=0))
  115. self._init_axis_if_exists('y', self._get_metadata_property("height", default=0))
  116. self._init_axis_if_exists('c', len(self._get_metadata_property("channels", default=[])), min_size=2)
  117. self._init_axis_if_exists('t', len(self._get_metadata_property("frames", default=[])))
  118. self._init_axis_if_exists('z', len(self._get_metadata_property("z_levels", default=[])), min_size=2)
  119. self._init_axis_if_exists('v', len(self._get_metadata_property("fields_of_view", default=[])), min_size=2)
  120. if len(self.sizes) == 0:
  121. raise EmptyFileError("No axes were found for this .nd2 file.")
  122. # provide the default
  123. self.iter_axes = self._guess_default_iter_axis()
  124. self._register_get_frame(self.get_frame_2D, 'yx')
  125. def _init_axis_if_exists(self, axis, size, min_size=1):
  126. if size >= min_size:
  127. self._init_axis(axis, size)
  128. def _guess_default_iter_axis(self):
  129. """
  130. Guesses the default axis to iterate over based on axis sizes.
  131. Returns:
  132. the axis to iterate over
  133. """
  134. priority = ['t', 'z', 'c', 'v']
  135. found_axes = []
  136. for axis in priority:
  137. try:
  138. current_size = self.sizes[axis]
  139. except KeyError:
  140. continue
  141. if current_size > 1:
  142. return axis
  143. found_axes.append(axis)
  144. return found_axes[0]
  145. def get_timesteps(self):
  146. """Get the timesteps of the experiment
  147. Returns:
  148. np.ndarray: an array of times in milliseconds.
  149. """
  150. if self._timesteps is not None and len(self._timesteps) > 0:
  151. return self._timesteps
  152. self._timesteps = np.array(list(self._parser._raw_metadata.acquisition_times), dtype=np.float) * 1000.0
  153. return self._timesteps