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.

232 lines
8.0 KiB

9 years ago
9 years ago
9 years ago
  1. # -*- coding: utf-8 -*-
  2. from nd2reader.parser import get_parser
  3. from nd2reader.version import get_version
  4. import six
  5. class Nd2(object):
  6. """ Allows easy access to NIS Elements .nd2 image files. """
  7. def __init__(self, filename):
  8. self._filename = filename
  9. self._fh = open(filename, "rb")
  10. major_version, minor_version = get_version(self._fh)
  11. self._parser = get_parser(self._fh, major_version, minor_version)
  12. self._metadata = self._parser.metadata
  13. def __repr__(self):
  14. return "\n".join(["<ND2 %s>" % self._filename,
  15. "Created: %s" % (self.date if self.date is not None else "Unknown"),
  16. "Image size: %sx%s (HxW)" % (self.height, self.width),
  17. "Frames: %s" % len(self.frames),
  18. "Channels: %s" % ", ".join(["%s" % str(channel) for channel in self.channels]),
  19. "Fields of View: %s" % len(self.fields_of_view),
  20. "Z-Levels: %s" % len(self.z_levels)
  21. ])
  22. def __enter__(self):
  23. return self
  24. def __exit__(self, exc_type, exc_val, exc_tb):
  25. if self._fh is not None:
  26. self._fh.close()
  27. def __len__(self):
  28. """
  29. This should be the total number of images in the ND2, but it may be inaccurate. If the ND2 contains a
  30. different number of images in a cycle (i.e. there are "gap" images) it will be higher than reality.
  31. :rtype: int
  32. """
  33. return self._metadata.total_images_per_channel * len(self.channels)
  34. def __getitem__(self, item):
  35. """
  36. Allows slicing ND2s.
  37. :type item: int or slice
  38. :rtype: nd2reader.model.Image() or generator
  39. """
  40. if isinstance(item, int):
  41. try:
  42. image = self._parser.driver.get_image(item)
  43. except KeyError:
  44. raise IndexError
  45. else:
  46. return image
  47. elif isinstance(item, slice):
  48. return self._slice(item.start, item.stop, item.step)
  49. raise IndexError
  50. def select(self, fields_of_view=None, channels=None, z_levels=None):
  51. """
  52. Iterates over images matching the given criteria. This can be 2-10 times faster than manually iterating over
  53. the Nd2 and checking the attributes of each image, as this method skips disk reads for any images that don't
  54. meet the criteria.
  55. :type fields_of_view: int or tuple or list
  56. :type channels: str or tuple or list
  57. :type z_levels: int or tuple or list
  58. """
  59. fields_of_view = self._to_tuple(fields_of_view, self.fields_of_view)
  60. channels = self._to_tuple(channels, self.channels)
  61. z_levels = self._to_tuple(z_levels, self.z_levels)
  62. for frame in range(len(self)):
  63. field_of_view, channel, z_level = self._parser.driver.calculate_image_properties(frame)
  64. if field_of_view in fields_of_view and channel in channels and z_level in z_levels:
  65. image = self._parser.driver.get_image(frame)
  66. if image is not None:
  67. yield image
  68. @property
  69. def height(self):
  70. """
  71. The height of each image in pixels.
  72. :rtype: int
  73. """
  74. return self._metadata.height
  75. @property
  76. def width(self):
  77. """
  78. The width of each image in pixels.
  79. :rtype: int
  80. """
  81. return self._metadata.width
  82. @property
  83. def z_levels(self):
  84. """
  85. A list of integers that represent the different levels on the Z-axis that images were taken. Currently this is
  86. just a list of numbers from 0 to N. For example, an ND2 where images were taken at -3µm, 0µm, and +5µm from a
  87. set position would be represented by 0, 1 and 2, respectively. ND2s do store the actual offset of each image
  88. in micrometers and in the future this will hopefully be available. For now, however, you will have to match up
  89. the order yourself.
  90. :return: list of int
  91. """
  92. return self._metadata.z_levels
  93. @property
  94. def fields_of_view(self):
  95. """
  96. A list of integers representing the various stage locations, in the order they were taken in the first round
  97. of acquisition.
  98. :return: list of int
  99. """
  100. return self._metadata.fields_of_view
  101. @property
  102. def channels(self):
  103. """
  104. A list of channel (i.e. wavelength) names. These are set by the user in NIS Elements.
  105. :return: list of str
  106. """
  107. return self._metadata.channels
  108. @property
  109. def frames(self):
  110. """
  111. A list of integers representing groups of images. ND2s consider images to be part of the same frame if they
  112. are in the same field of view and don't have the same channel. So if you take a bright field and GFP image at
  113. four different fields of view over and over again, you'll have 8 images and 4 frames per cycle.
  114. :return: list of int
  115. """
  116. return self._metadata.frames
  117. @property
  118. def camera_settings(self):
  119. """
  120. Basic information about the physical cameras used.
  121. :return: dict of {channel_name: model.metadata.CameraSettings}
  122. """
  123. return self._parser.camera_metadata
  124. @property
  125. def date(self):
  126. """
  127. The date and time that the acquisition began. Not guaranteed to have been recorded.
  128. :rtype: datetime.datetime() or None
  129. """
  130. return self._metadata.date
  131. def get_image(self, frame_number, field_of_view, channel_name, z_level):
  132. """
  133. Attempts to return the image with the unique combination of given attributes. None will be returned if a match
  134. is not found.
  135. :type frame_number: int
  136. :param field_of_view: the label for the place in the XY-plane where this image was taken.
  137. :type field_of_view: int
  138. :param channel_name: the name of the color of this image
  139. :type channel_name: str
  140. :param z_level: the label for the location in the Z-plane where this image was taken.
  141. :type z_level: int
  142. :rtype: nd2reader.model.Image() or None
  143. """
  144. return self._parser.driver.get_image_by_attributes(frame_number,
  145. field_of_view,
  146. channel_name,
  147. z_level,
  148. self.height,
  149. self.width)
  150. def close(self):
  151. """
  152. Closes the file handle to the image. This actually sometimes will prevent problems so it's good to do this or
  153. use Nd2 as a context manager.
  154. """
  155. self._fh.close()
  156. def _slice(self, start, stop, step):
  157. """
  158. Allows for iteration over a selection of the entire dataset.
  159. :type start: int
  160. :type stop: int
  161. :type step: int
  162. :rtype: nd2reader.model.Image()
  163. """
  164. start = start if start is not None else 0
  165. step = step if step is not None else 1
  166. stop = stop if stop is not None else len(self)
  167. # This weird thing with the step allows you to iterate backwards over the images
  168. for i in range(start, stop)[::step]:
  169. yield self[i]
  170. def _to_tuple(self, value, default):
  171. """
  172. Idempotently converts a value to a tuple. This allows users to pass in scalar values and iterables to
  173. select(), which is more ergonomic than having to remember to pass in single-member lists
  174. :type value: int or str or tuple or list
  175. :type default: tuple or list
  176. :rtype: tuple
  177. """
  178. value = default if value is None else value
  179. return (value,) if isinstance(value, int) or isinstance(value, six.string_types) else tuple(value)