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.

214 lines
7.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 __enter__(self):
  14. return self
  15. def __exit__(self, exc_type, exc_val, exc_tb):
  16. if self._fh is not None:
  17. self._fh.close()
  18. def __repr__(self):
  19. return "\n".join(["<ND2 %s>" % self._filename,
  20. "Created: %s" % (self.date if self.date is not None else "Unknown"),
  21. "Image size: %sx%s (HxW)" % (self.height, self.width),
  22. "Frames: %s" % len(self.frames),
  23. "Channels: %s" % ", ".join(["%s" % str(channel) for channel in self.channels]),
  24. "Fields of View: %s" % len(self.fields_of_view),
  25. "Z-Levels: %s" % len(self.z_levels)
  26. ])
  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 _slice(self, start, stop, step):
  51. """
  52. Allows for iteration over a selection of the entire dataset.
  53. :type start: int
  54. :type stop: int
  55. :type step: int
  56. :rtype: nd2reader.model.Image()
  57. """
  58. start = start if start is not None else 0
  59. step = step if step is not None else 1
  60. stop = stop if stop is not None else len(self)
  61. # This weird thing with the step allows you to iterate backwards over the images
  62. for i in range(start, stop)[::step]:
  63. yield self[i]
  64. @property
  65. def camera_settings(self):
  66. return self._parser.camera_metadata
  67. @property
  68. def date(self):
  69. """
  70. The date and time that the acquisition began. Not guaranteed to have been recorded.
  71. :rtype: datetime.datetime() or None
  72. """
  73. return self._metadata.date
  74. @property
  75. def z_levels(self):
  76. """
  77. A list of integers that represent the different levels on the Z-axis that images were taken. Currently this is
  78. 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
  79. set position would be represented by 0, 1 and 2, respectively. ND2s do store the actual offset of each image
  80. in micrometers and in the future this will hopefully be available. For now, however, you will have to match up
  81. the order yourself.
  82. :return: list of int
  83. """
  84. return self._metadata.z_levels
  85. @property
  86. def fields_of_view(self):
  87. """
  88. A list of integers representing the various stage locations, in the order they were taken in the first round
  89. of acquisition.
  90. :return: list of int
  91. """
  92. return self._metadata.fields_of_view
  93. @property
  94. def channels(self):
  95. """
  96. A list of channel (i.e. wavelength) names. These are set by the user in NIS Elements.
  97. :return: list of str
  98. """
  99. return self._metadata.channels
  100. @property
  101. def frames(self):
  102. """
  103. A list of integers representing groups of images. ND2s consider images to be part of the same frame if they
  104. 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
  105. four different fields of view over and over again, you'll have 8 images and 4 frames per cycle.
  106. :return: list of int
  107. """
  108. return self._metadata.frames
  109. @property
  110. def height(self):
  111. """
  112. The height of each image in pixels.
  113. :rtype: int
  114. """
  115. return self._metadata.height
  116. @property
  117. def width(self):
  118. """
  119. The width of each image in pixels.
  120. :rtype: int
  121. """
  122. return self._metadata.width
  123. def get_image(self, frame_number, field_of_view, channel_name, z_level):
  124. """
  125. Attempts to return the image with the unique combination of given attributes. None will be returned if a match
  126. is not found.
  127. :type frame_number: int
  128. :param field_of_view: the label for the place in the XY-plane where this image was taken.
  129. :type field_of_view: int
  130. :param channel_name: the name of the color of this image
  131. :type channel_name: str
  132. :param z_level: the label for the location in the Z-plane where this image was taken.
  133. :type z_level: int
  134. :rtype: nd2reader.model.Image() or None
  135. """
  136. return self._parser.driver.get_image_by_attributes(frame_number,
  137. field_of_view,
  138. channel_name,
  139. z_level,
  140. self.height,
  141. self.width)
  142. def filter(self, fields_of_view=None, channels=None, z_levels=None):
  143. """
  144. Iterates over images matching the given criteria. This can be 2-10 times faster than manually iterating over
  145. the Nd2 and checking the attributes of each image, as this method will not read from disk until a valid image is
  146. found.
  147. """
  148. fields_of_view = self._to_list(fields_of_view, self.fields_of_view)
  149. channels = self._to_list(channels, self.channels)
  150. z_levels = self._to_list(z_levels, self.z_levels)
  151. for frame in self.frames:
  152. for f in fields_of_view:
  153. for z in z_levels:
  154. for c in channels:
  155. image = self.get_image(frame, f, c, z)
  156. if image is not None:
  157. yield image
  158. def _to_list(self, value, default):
  159. value = default if value is None else value
  160. return [value] if isinstance(value, int) or isinstance(value, six.string_types) else value
  161. def close(self):
  162. """
  163. Closes the file handle to the image. This actually sometimes will prevent problems so it's good to do this or
  164. use Nd2 as a context manager.
  165. """
  166. self._fh.close()
  167. 1