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.

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