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.

176 lines
5.8 KiB

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. parser = get_parser(self._fh, major_version, minor_version)
  11. self._driver = parser.driver
  12. self._metadata = 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._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 date(self):
  66. """
  67. The date and time that the acquisition began. Not guaranteed to have been recorded.
  68. :rtype: datetime.datetime() or None
  69. """
  70. return self._metadata.date
  71. @property
  72. def z_levels(self):
  73. """
  74. A list of integers that represent the different levels on the Z-axis that images were taken. Currently this is just a list of numbers from 0 to N.
  75. For example, an ND2 where images were taken at -3µm, 0µm, and +5µm from a set position would be represented by 0, 1 and 2, respectively. ND2s do store the actual
  76. offset of each image in micrometers and in the future this will hopefully be available. For now, however, you will have to match up the order yourself.
  77. :return: list of int
  78. """
  79. return self._metadata.z_levels
  80. @property
  81. def fields_of_view(self):
  82. """
  83. A list of integers representing the various stage locations, in the order they were taken in the first round of acquisition.
  84. :return: list of int
  85. """
  86. return self._metadata.fields_of_view
  87. @property
  88. def channels(self):
  89. """
  90. A list of channel (i.e. wavelength) names. These are set by the user in NIS Elements.
  91. :return: list of str
  92. """
  93. return self._metadata.channels
  94. @property
  95. def frames(self):
  96. """
  97. A list of integers representing groups of images. ND2s consider images to be part of the same frame if they are in the same field of view and don't have the same channel.
  98. So if you take a bright field and GFP image at four different fields of view over and over again, you'll have 8 images and 4 frames per cycle.
  99. :return: list of int
  100. """
  101. return self._metadata.frames
  102. @property
  103. def height(self):
  104. """
  105. The height of each image in pixels.
  106. :rtype: int
  107. """
  108. return self._metadata.height
  109. @property
  110. def width(self):
  111. """
  112. The width of each image in pixels.
  113. :rtype: int
  114. """
  115. return self._metadata.width
  116. def get_image(self, frame_number, field_of_view, channel_name, z_level):
  117. """
  118. Attempts to return the image with the unique combination of given attributes. None will be returned if a match is not found.
  119. :type frame_number: int
  120. :param field_of_view: the label for the place in the XY-plane where this image was taken.
  121. :type field_of_view: int
  122. :param channel_name: the name of the color of this image
  123. :type channel_name: str
  124. :param z_level: the label for the location in the Z-plane where this image was taken.
  125. :type z_level: int
  126. :rtype: nd2reader.model.Image() or None
  127. """
  128. return self._driver.get_image_by_attributes(frame_number, field_of_view, channel_name, z_level, self.height, self.width)
  129. def close(self):
  130. """
  131. Closes the file handle to the image. This actually sometimes will prevent problems so it's good to do this or use Nd2 as a context manager.
  132. """
  133. self._fh.close()