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.

236 lines
8.2 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, start=0, stop=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. :type start: int
  59. :type stop: int
  60. """
  61. fields_of_view = self._to_tuple(fields_of_view, self.fields_of_view)
  62. channels = self._to_tuple(channels, self.channels)
  63. z_levels = self._to_tuple(z_levels, self.z_levels)
  64. # By default, we stop after the last image. Otherwise we make sure the user-provided value is valid
  65. stop = len(self) if stop is None else max(0, min(stop, len(self)))
  66. for frame in range(start, stop):
  67. field_of_view, channel, z_level = self._parser.driver.calculate_image_properties(frame)
  68. if field_of_view in fields_of_view and channel in channels and z_level in z_levels:
  69. image = self._parser.driver.get_image(frame)
  70. if image is not None:
  71. yield image
  72. @property
  73. def height(self):
  74. """
  75. The height of each image in pixels.
  76. :rtype: int
  77. """
  78. return self._metadata.height
  79. @property
  80. def width(self):
  81. """
  82. The width of each image in pixels.
  83. :rtype: int
  84. """
  85. return self._metadata.width
  86. @property
  87. def z_levels(self):
  88. """
  89. A list of integers that represent the different levels on the Z-axis that images were taken. Currently this is
  90. 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
  91. set position would be represented by 0, 1 and 2, respectively. ND2s do store the actual offset of each image
  92. in micrometers and in the future this will hopefully be available. For now, however, you will have to match up
  93. the order yourself.
  94. :return: list of int
  95. """
  96. return self._metadata.z_levels
  97. @property
  98. def fields_of_view(self):
  99. """
  100. A list of integers representing the various stage locations, in the order they were taken in the first round
  101. of acquisition.
  102. :return: list of int
  103. """
  104. return self._metadata.fields_of_view
  105. @property
  106. def channels(self):
  107. """
  108. A list of channel (i.e. wavelength) names. These are set by the user in NIS Elements.
  109. :return: list of str
  110. """
  111. return self._metadata.channels
  112. @property
  113. def frames(self):
  114. """
  115. A list of integers representing groups of images. ND2s consider images to be part of the same frame if they
  116. 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
  117. four different fields of view over and over again, you'll have 8 images and 4 frames per cycle.
  118. :return: list of int
  119. """
  120. return self._metadata.frames
  121. @property
  122. def date(self):
  123. """
  124. The date and time that the acquisition began. Not guaranteed to have been recorded.
  125. :rtype: datetime.datetime() or None
  126. """
  127. return self._metadata.date
  128. @property
  129. def pixel_microns(self):
  130. """
  131. The width of a pixel in microns. Note that the user can override this in NIS Elements so it may not reflect reality.
  132. :rtype: float
  133. """
  134. return self._metadata.pixel_microns
  135. def get_image(self, frame_number, field_of_view, channel_name, z_level):
  136. """
  137. Attempts to return the image with the unique combination of given attributes. None will be returned if a match
  138. is not found.
  139. :type frame_number: int
  140. :param field_of_view: the label for the place in the XY-plane where this image was taken.
  141. :type field_of_view: int
  142. :param channel_name: the name of the color of this image
  143. :type channel_name: str
  144. :param z_level: the label for the location in the Z-plane where this image was taken.
  145. :type z_level: int
  146. :rtype: nd2reader.model.Image() or None
  147. """
  148. return self._parser.driver.get_image_by_attributes(frame_number,
  149. field_of_view,
  150. channel_name,
  151. z_level,
  152. self.height,
  153. self.width)
  154. def close(self):
  155. """
  156. Closes the file handle to the image. This actually sometimes will prevent problems so it's good to do this or
  157. use Nd2 as a context manager.
  158. """
  159. self._fh.close()
  160. def _slice(self, start, stop, step):
  161. """
  162. Allows for iteration over a selection of the entire dataset.
  163. :type start: int
  164. :type stop: int
  165. :type step: int
  166. :rtype: nd2reader.model.Image()
  167. """
  168. start = start if start is not None else 0
  169. step = step if step is not None else 1
  170. stop = stop if stop is not None else len(self)
  171. # This weird thing with the step allows you to iterate backwards over the images
  172. for i in range(start, stop)[::step]:
  173. yield self[i]
  174. def _to_tuple(self, value, default):
  175. """
  176. Idempotently converts a value to a tuple. This allows users to pass in scalar values and iterables to
  177. select(), which is more ergonomic than having to remember to pass in single-member lists
  178. :type value: int or str or tuple or list
  179. :type default: tuple or list
  180. :rtype: tuple
  181. """
  182. value = default if value is None else value
  183. return (value,) if isinstance(value, int) or isinstance(value, six.string_types) else tuple(value)