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.

160 lines
6.3 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
  1. # -*- coding: utf-8 -*-
  2. from nd2reader.model import Image, ImageSet
  3. from nd2reader.parser import Nd2Parser
  4. import six
  5. class Nd2(Nd2Parser):
  6. """
  7. Allows easy access to NIS Elements .nd2 image files.
  8. """
  9. def __init__(self, filename):
  10. super(Nd2, self).__init__(filename)
  11. self._filename = filename
  12. def __repr__(self):
  13. return "\n".join(["<ND2 %s>" % self._filename,
  14. "Created: %s" % self._absolute_start.strftime("%Y-%m-%d %H:%M:%S"),
  15. "Image size: %sx%s (HxW)" % (self.height, self.width),
  16. "Image cycles: %s" % len(self.time_indexes),
  17. "Channels: %s" % ", ".join(["'%s'" % str(channel) for channel in self.channels]),
  18. "Fields of View: %s" % len(self.fields_of_view),
  19. "Z-Levels: %s" % len(self.z_levels)
  20. ])
  21. def __len__(self):
  22. """
  23. This should be the total number of images in the ND2, but it may be inaccurate. If the ND2 contains a
  24. different number of images in a cycle (i.e. there are "gap" images) it will be higher than reality.
  25. :rtype: int
  26. """
  27. return self._image_count * self._channel_count
  28. def __getitem__(self, item):
  29. """
  30. Allows slicing ND2s.
  31. >>> nd2 = Nd2("my_images.nd2")
  32. >>> image = nd2[16] # gets 17th frame
  33. >>> for image in nd2[100:200]: # iterate over the 100th to 200th images
  34. >>> do_something(image.data)
  35. >>> for image in nd2[::-1]: # iterate backwards
  36. >>> do_something(image.data)
  37. >>> for image in nd2[37:422:17]: # do something super weird if you really want to
  38. >>> do_something(image.data)
  39. :type item: int or slice
  40. :rtype: nd2reader.model.Image() or generator
  41. """
  42. if isinstance(item, int):
  43. try:
  44. channel_offset = item % len(self.channels)
  45. fov = self._calculate_field_of_view(item)
  46. channel = self._calculate_channel(item)
  47. z_level = self._calculate_z_level(item)
  48. timestamp, raw_image_data = self._get_raw_image_data(item, channel_offset)
  49. image = Image(timestamp, raw_image_data, fov, channel, z_level, self.height, self.width)
  50. except (TypeError, ValueError):
  51. return None
  52. else:
  53. return image
  54. elif isinstance(item, slice):
  55. return self._slice(item.start, item.stop, item.step)
  56. raise IndexError
  57. def _slice(self, start, stop, step):
  58. """
  59. Allows for iteration over a selection of the entire dataset.
  60. :type start: int
  61. :type stop: int
  62. :type step: int
  63. :rtype: nd2reader.model.Image() or None
  64. """
  65. start = start if start is not None else 0
  66. step = step if step is not None else 1
  67. stop = stop if stop is not None else len(self)
  68. # This weird thing with the step allows you to iterate backwards over the images
  69. for i in range(start, stop)[::step]:
  70. yield self[i]
  71. @property
  72. def image_sets(self):
  73. """
  74. Iterates over groups of related images. This is useful if your ND2 contains multiple fields of view.
  75. A typical use case might be that you have, say, four areas of interest that you're monitoring, and every
  76. minute you take a bright field and GFP image of each one. For each cycle, this method would produce four
  77. ImageSet objects, each containing one bright field and one GFP image.
  78. :return: model.ImageSet()
  79. """
  80. for time_index in self.time_indexes:
  81. image_set = ImageSet()
  82. for fov in self.fields_of_view:
  83. for channel_name in self.channels:
  84. for z_level in self.z_levels:
  85. image = self.get_image(time_index, fov, channel_name, z_level)
  86. if image is not None:
  87. image_set.add(image)
  88. yield image_set
  89. @property
  90. def height(self):
  91. """
  92. :return: height of each image, in pixels
  93. :rtype: int
  94. """
  95. return self.metadata[six.b('ImageAttributes')][six.b('SLxImageAttributes')][six.b('uiHeight')]
  96. @property
  97. def width(self):
  98. """
  99. :return: width of each image, in pixels
  100. :rtype: int
  101. """
  102. return self.metadata[six.b('ImageAttributes')][six.b('SLxImageAttributes')][six.b('uiWidth')]
  103. def _calculate_field_of_view(self, frame_number):
  104. images_per_cycle = len(self.z_levels) * len(self.channels)
  105. return int((frame_number - (frame_number % images_per_cycle)) / images_per_cycle) % len(self.fields_of_view)
  106. def _calculate_channel(self, frame_number):
  107. return self._channels[frame_number % len(self.channels)]
  108. def _calculate_z_level(self, frame_number):
  109. return self.z_levels[int(((frame_number - (frame_number % len(self.channels))) / len(self.channels)) % len(self.z_levels))]
  110. def get_image(self, time_index, field_of_view, channel_name, z_level):
  111. """
  112. Returns an Image if data exists for the given parameters, otherwise returns None. In general, you should avoid
  113. using this method unless you're very familiar with the structure of ND2 files. If you have a use case that
  114. cannot be met by the `__iter__` or `image_sets` methods above, please create an issue on Github.
  115. :param time_index: the frame number
  116. :type time_index: int
  117. :param field_of_view: the label for the place in the XY-plane where this image was taken.
  118. :type field_of_view: int
  119. :param channel_name: the name of the color of this image
  120. :type channel_name: str
  121. :param z_level: the label for the location in the Z-plane where this image was taken.
  122. :type z_level: int
  123. :rtype: nd2reader.model.Image() or None
  124. """
  125. image_group_number = self._calculate_image_group_number(time_index, field_of_view, z_level)
  126. try:
  127. timestamp, raw_image_data = self._get_raw_image_data(image_group_number, self._channel_offset[channel_name])
  128. image = Image(timestamp, raw_image_data, field_of_view, channel_name, z_level, self.height, self.width)
  129. except TypeError:
  130. return None
  131. else:
  132. return image