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.

185 lines
5.1 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. return 1000. / np.mean(np.diff(self.timesteps))
  89. def _get_metadata_property(self, key, default=None):
  90. if self.metadata is None:
  91. return default
  92. if key not in self.metadata:
  93. return default
  94. if self.metadata[key] is None:
  95. return default
  96. return self.metadata[key]
  97. def _setup_axes(self):
  98. """Setup the xyctz axes, iterate over t axis by default
  99. """
  100. self._init_axis_if_exists('x', self._get_metadata_property("width", default=0))
  101. self._init_axis_if_exists('y', self._get_metadata_property("height", default=0))
  102. self._init_axis_if_exists('c', len(self._get_metadata_property("channels", default=[])), min_size=2)
  103. self._init_axis_if_exists('t', len(self._get_metadata_property("frames", default=[])))
  104. self._init_axis_if_exists('z', len(self._get_metadata_property("z_levels", default=[])), min_size=2)
  105. self._init_axis_if_exists('v', len(self._get_metadata_property("fields_of_view", default=[])), min_size=2)
  106. if len(self.sizes) == 0:
  107. raise EmptyFileError("No axes were found for this .nd2 file.")
  108. # provide the default
  109. self.iter_axes = self._guess_default_iter_axis()
  110. def _init_axis_if_exists(self, axis, size, min_size=1):
  111. if size >= min_size:
  112. self._init_axis(axis, size)
  113. def _guess_default_iter_axis(self):
  114. """
  115. Guesses the default axis to iterate over based on axis sizes.
  116. Returns:
  117. the axis to iterate over
  118. """
  119. priority = ['t', 'z', 'c', 'v']
  120. found_axes = []
  121. for axis in priority:
  122. try:
  123. current_size = self.sizes[axis]
  124. except KeyError:
  125. continue
  126. if current_size > 1:
  127. return axis
  128. found_axes.append(axis)
  129. return found_axes[0]
  130. def get_timesteps(self):
  131. """Get the timesteps of the experiment
  132. Returns:
  133. np.ndarray: an array of times in milliseconds.
  134. """
  135. if self._timesteps is not None and len(self._timesteps) > 0:
  136. return self._timesteps
  137. self._timesteps = np.array(list(self._parser._raw_metadata.acquisition_times), dtype=np.float) * 1000.0
  138. return self._timesteps