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.

190 lines
6.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. class Nd2(object):
  5. """ Allows easy access to NIS Elements .nd2 image files. """
  6. def __init__(self, filename):
  7. self._filename = filename
  8. self._fh = open(filename, "rb")
  9. major_version, minor_version = get_version(self._fh)
  10. self._parser = get_parser(self._fh, major_version, minor_version)
  11. self._metadata = self._parser.metadata
  12. def __enter__(self):
  13. return self
  14. def __exit__(self, exc_type, exc_val, exc_tb):
  15. if self._fh is not None:
  16. self._fh.close()
  17. def __repr__(self):
  18. return "\n".join(["<ND2 %s>" % self._filename,
  19. "Created: %s" % (self.date if self.date is not None else "Unknown"),
  20. "Image size: %sx%s (HxW)" % (self.height, self.width),
  21. "Frames: %s" % len(self.frames),
  22. "Channels: %s" % ", ".join(["%s" % str(channel) for channel in self.channels]),
  23. "Fields of View: %s" % len(self.fields_of_view),
  24. "Z-Levels: %s" % len(self.z_levels)
  25. ])
  26. def __len__(self):
  27. """
  28. This should be the total number of images in the ND2, but it may be inaccurate. If the ND2 contains a
  29. different number of images in a cycle (i.e. there are "gap" images) it will be higher than reality.
  30. :rtype: int
  31. """
  32. return self._metadata.total_images_per_channel * len(self.channels)
  33. def __getitem__(self, item):
  34. """
  35. Allows slicing ND2s.
  36. :type item: int or slice
  37. :rtype: nd2reader.model.Image() or generator
  38. """
  39. if isinstance(item, int):
  40. try:
  41. image = self._parser.driver.get_image(item)
  42. except KeyError:
  43. raise IndexError
  44. else:
  45. return image
  46. elif isinstance(item, slice):
  47. return self._slice(item.start, item.stop, item.step)
  48. raise IndexError
  49. def _slice(self, start, stop, step):
  50. """
  51. Allows for iteration over a selection of the entire dataset.
  52. :type start: int
  53. :type stop: int
  54. :type step: int
  55. :rtype: nd2reader.model.Image()
  56. """
  57. start = start if start is not None else 0
  58. step = step if step is not None else 1
  59. stop = stop if stop is not None else len(self)
  60. # This weird thing with the step allows you to iterate backwards over the images
  61. for i in range(start, stop)[::step]:
  62. yield self[i]
  63. @property
  64. def camera_settings(self):
  65. return self._parser.camera_metadata
  66. @property
  67. def date(self):
  68. """
  69. The date and time that the acquisition began. Not guaranteed to have been recorded.
  70. :rtype: datetime.datetime() or None
  71. """
  72. return self._metadata.date
  73. @property
  74. def z_levels(self):
  75. """
  76. A list of integers that represent the different levels on the Z-axis that images were taken. Currently this is
  77. 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
  78. set position would be represented by 0, 1 and 2, respectively. ND2s do store the actual offset of each image
  79. in micrometers and in the future this will hopefully be available. For now, however, you will have to match up
  80. the order yourself.
  81. :return: list of int
  82. """
  83. return self._metadata.z_levels
  84. @property
  85. def fields_of_view(self):
  86. """
  87. A list of integers representing the various stage locations, in the order they were taken in the first round
  88. of acquisition.
  89. :return: list of int
  90. """
  91. return self._metadata.fields_of_view
  92. @property
  93. def channels(self):
  94. """
  95. A list of channel (i.e. wavelength) names. These are set by the user in NIS Elements.
  96. :return: list of str
  97. """
  98. return self._metadata.channels
  99. @property
  100. def frames(self):
  101. """
  102. A list of integers representing groups of images. ND2s consider images to be part of the same frame if they
  103. 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
  104. four different fields of view over and over again, you'll have 8 images and 4 frames per cycle.
  105. :return: list of int
  106. """
  107. return self._metadata.frames
  108. @property
  109. def height(self):
  110. """
  111. The height of each image in pixels.
  112. :rtype: int
  113. """
  114. return self._metadata.height
  115. @property
  116. def width(self):
  117. """
  118. The width of each image in pixels.
  119. :rtype: int
  120. """
  121. return self._metadata.width
  122. def get_image(self, frame_number, field_of_view, channel_name, z_level):
  123. """
  124. Attempts to return the image with the unique combination of given attributes. None will be returned if a match
  125. is not found.
  126. :type frame_number: int
  127. :param field_of_view: the label for the place in the XY-plane where this image was taken.
  128. :type field_of_view: int
  129. :param channel_name: the name of the color of this image
  130. :type channel_name: str
  131. :param z_level: the label for the location in the Z-plane where this image was taken.
  132. :type z_level: int
  133. :rtype: nd2reader.model.Image() or None
  134. """
  135. return self._parser.driver.get_image_by_attributes(frame_number,
  136. field_of_view,
  137. channel_name,
  138. z_level,
  139. self.height,
  140. self.width)
  141. def close(self):
  142. """
  143. Closes the file handle to the image. This actually sometimes will prevent problems so it's good to do this or
  144. use Nd2 as a context manager.
  145. """
  146. self._fh.close()