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.

154 lines
4.3 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. from pims import FramesSequenceND, Frame
  2. from nd2reader.parser import Parser
  3. import numpy as np
  4. class ND2Reader(FramesSequenceND):
  5. """PIMS wrapper for the ND2 parser.
  6. This is the main class: use this to process your .nd2 files.
  7. """
  8. def __init__(self, filename):
  9. self.filename = filename
  10. # first use the parser to parse the file
  11. self._fh = open(filename, "rb")
  12. self._parser = Parser(self._fh)
  13. # Setup metadata
  14. self.metadata = self._parser.metadata
  15. # Set data type
  16. self._dtype = self._parser.get_dtype_from_metadata()
  17. # Setup the axes
  18. self._setup_axes()
  19. @classmethod
  20. def class_exts(cls):
  21. """Let PIMS open function use this reader for opening .nd2 files
  22. """
  23. return {'nd2'} | super(ND2Reader, cls).class_exts()
  24. def close(self):
  25. """Correctly close the file handle
  26. """
  27. if self._fh is not None:
  28. self._fh.close()
  29. def get_frame(self, i):
  30. """Return one frame
  31. Args:
  32. i: The frame number
  33. Returns:
  34. numpy.ndarray: The requested frame
  35. """
  36. fetch_all_channels = 'c' in self.bundle_axes
  37. if fetch_all_channels:
  38. return self._get_frame_all_channels(i)
  39. else:
  40. return self.get_frame_2D(self.default_coords['c'], i, self.default_coords['z'])
  41. def _get_frame_all_channels(self, i):
  42. """Get all color channels for this frame
  43. Args:
  44. i: The frame number
  45. Returns:
  46. numpy.ndarray: The requested frame, with all color channels.
  47. """
  48. frames = None
  49. for c in range(len(self.metadata["channels"])):
  50. frame = self.get_frame_2D(c, i, self.default_coords['z'])
  51. if frames is None:
  52. frames = Frame([frame])
  53. else:
  54. frames = np.concatenate((frames, [frame]), axis=0)
  55. return frames
  56. def get_frame_2D(self, c, t, z):
  57. """Gets a given frame using the parser
  58. Args:
  59. c: The color channel number
  60. t: The frame number
  61. z: The z stack number
  62. Returns:
  63. numpy.ndarray: The requested frame
  64. """
  65. c_name = self.metadata["channels"][c]
  66. return self._parser.get_image_by_attributes(t, 0, c_name, z, self.metadata["height"], self.metadata["width"])
  67. @property
  68. def parser(self):
  69. """
  70. Returns the parser object.
  71. Returns:
  72. Parser: the parser object
  73. """
  74. return self._parser
  75. @property
  76. def pixel_type(self):
  77. """Return the pixel data type
  78. Returns:
  79. dtype: the pixel data type
  80. """
  81. return self._dtype
  82. def _get_metadata_property(self, key, default=None):
  83. if self.metadata is None:
  84. return default
  85. if key not in self.metadata:
  86. return default
  87. if self.metadata[key] is None:
  88. return default
  89. return self.metadata[key]
  90. def _setup_axes(self):
  91. """Setup the xyctz axes, iterate over t axis by default
  92. """
  93. self._init_axis('x', self._get_metadata_property("width", default=0))
  94. self._init_axis('y', self._get_metadata_property("height", default=0))
  95. self._init_axis('c', len(self._get_metadata_property("channels", default=[])))
  96. self._init_axis('t', len(self._get_metadata_property("frames", default=[])))
  97. self._init_axis('z', len(self._get_metadata_property("z_levels", default=[])))
  98. # provide the default
  99. self.iter_axes = 't'
  100. def get_timesteps(self):
  101. """Get the timesteps of the experiment
  102. Returns:
  103. np.ndarray: an array of times in milliseconds.
  104. """
  105. timesteps = np.array([])
  106. current_time = 0.0
  107. for loop in self.metadata['experiment']['loops']:
  108. if loop['stimulation']:
  109. continue
  110. timesteps = np.concatenate(
  111. (timesteps, np.arange(current_time, current_time + loop['duration'], loop['sampling_interval'])))
  112. current_time += loop['duration']
  113. # if experiment did not finish, number of timesteps is wrong. Take correct amount of leading timesteps.
  114. return timesteps[:self.metadata['num_frames']]