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.

177 lines
6.8 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. # -*- coding: utf-8 -*-
  2. import array
  3. from datetime import datetime
  4. import logging
  5. from nd2reader.model import Image, ImageSet
  6. from nd2reader.parser import Nd2Parser
  7. import re
  8. import struct
  9. log = logging.getLogger(__name__)
  10. log.addHandler(logging.StreamHandler())
  11. log.setLevel(logging.DEBUG)
  12. class Nd2(Nd2Parser):
  13. def __init__(self, filename, image_sets=False):
  14. super(Nd2, self).__init__(filename)
  15. self._use_image_sets = image_sets
  16. def __iter__(self):
  17. for i in range(self._image_count):
  18. for fov in range(self.field_of_view_count):
  19. for z_level in range(self.z_level_count):
  20. for channel_name in self.channels:
  21. image = self.get_image(i, fov, channel_name, z_level)
  22. if image.is_valid:
  23. yield image
  24. @property
  25. def image_sets(self):
  26. for time_index in xrange(self.time_index_count):
  27. image_set = ImageSet()
  28. for fov in range(self.field_of_view_count):
  29. for channel_name in self.channels:
  30. for z_level in xrange(self.z_level_count):
  31. image = self.get_image(time_index, fov, channel_name, z_level)
  32. if image.is_valid:
  33. image_set.add(image)
  34. yield image_set
  35. def get_image(self, time_index, fov, channel_name, z_level):
  36. image_set_number = self._calculate_image_set_number(time_index, fov, z_level)
  37. timestamp, raw_image_data = self._get_raw_image_data(image_set_number, self._channel_offset[channel_name])
  38. return Image(timestamp, raw_image_data, fov, channel_name, z_level, self.height, self.width)
  39. @property
  40. def channels(self):
  41. metadata = self.metadata['ImageMetadataSeq']['SLxPictureMetadata']['sPicturePlanes']
  42. try:
  43. validity = self.metadata['ImageMetadata']['SLxExperiment']['ppNextLevelEx'][''][0]['ppNextLevelEx'][''][0]['pItemValid']
  44. except KeyError:
  45. # If none of the channels have been deleted, there is no validity list, so we just make one
  46. validity = [True for _ in metadata]
  47. # Channel information is contained in dictionaries with the keys a0, a1...an where the number
  48. # indicates the order in which the channel is stored. So by sorting the dicts alphabetically
  49. # we get the correct order.
  50. for (label, chan), valid in zip(sorted(metadata['sPlaneNew'].items()), validity):
  51. if not valid:
  52. continue
  53. yield chan['sDescription']
  54. @property
  55. def height(self):
  56. """
  57. :return: height of each image, in pixels
  58. """
  59. return self.metadata['ImageAttributes']['SLxImageAttributes']['uiHeight']
  60. @property
  61. def width(self):
  62. """
  63. :return: width of each image, in pixels
  64. """
  65. return self.metadata['ImageAttributes']['SLxImageAttributes']['uiWidth']
  66. @property
  67. def absolute_start(self):
  68. for line in self.metadata['ImageTextInfo']['SLxImageTextInfo'].values():
  69. absolute_start_12 = None
  70. absolute_start_24 = None
  71. # ND2s seem to randomly switch between 12- and 24-hour representations.
  72. try:
  73. absolute_start_24 = datetime.strptime(line, "%m/%d/%Y %H:%M:%S")
  74. except ValueError:
  75. pass
  76. try:
  77. absolute_start_12 = datetime.strptime(line, "%m/%d/%Y %I:%M:%S %p")
  78. except ValueError:
  79. pass
  80. if not absolute_start_12 and not absolute_start_24:
  81. continue
  82. return absolute_start_12 if absolute_start_12 else absolute_start_24
  83. raise ValueError("This ND2 has no recorded start time. This is probably a bug.")
  84. @property
  85. def channel_count(self):
  86. pattern = r""".*?λ\((\d+)\).*?"""
  87. try:
  88. count = int(re.match(pattern, self._dimensions).group(1))
  89. except AttributeError:
  90. return 1
  91. else:
  92. return count
  93. @property
  94. def field_of_view_count(self):
  95. """
  96. The metadata contains information about fields of view, but it contains it even if some fields
  97. of view were cropped. We can't find anything that states which fields of view are actually
  98. in the image data, so we have to calculate it. There probably is something somewhere, since
  99. NIS Elements can figure it out, but we haven't found it yet.
  100. """
  101. pattern = r""".*?XY\((\d+)\).*?"""
  102. try:
  103. count = int(re.match(pattern, self._dimensions).group(1))
  104. except AttributeError:
  105. return 1
  106. else:
  107. return count
  108. @property
  109. def time_index_count(self):
  110. """
  111. The number of image sets. If images were acquired using some kind of cycle, all images at each step in the
  112. program will have the same timestamp (even though they may have varied by a few seconds in reality). For example,
  113. if you have four fields of view that you're constantly monitoring, and you take a bright field and GFP image of
  114. each, and you repeat that process 100 times, you'll have 800 individual images. But there will only be 400
  115. time indexes.
  116. :rtype: int
  117. """
  118. pattern = r""".*?T'\((\d+)\).*?"""
  119. try:
  120. count = int(re.match(pattern, self._dimensions).group(1))
  121. except AttributeError:
  122. return 1
  123. else:
  124. return count
  125. @property
  126. def z_level_count(self):
  127. pattern = r""".*?Z\((\d+)\).*?"""
  128. try:
  129. count = int(re.match(pattern, self._dimensions).group(1))
  130. except AttributeError:
  131. return 1
  132. else:
  133. return count
  134. @property
  135. def _channel_offset(self):
  136. """
  137. Image data is interleaved for each image set. That is, if there are four images in a set, the first image
  138. will consist of pixels 1, 5, 9, etc, the second will be pixels 2, 6, 10, and so forth. Why this would be the
  139. case is beyond me, but that's how it works.
  140. """
  141. channel_offset = {}
  142. for n, channel in enumerate(self.channels):
  143. channel_offset[channel] = n
  144. return channel_offset
  145. def _get_raw_image_data(self, image_set_number, channel_offset):
  146. chunk = self._label_map["ImageDataSeq|%d!" % image_set_number]
  147. data = self._read_chunk(chunk)
  148. timestamp = struct.unpack("d", data[:8])[0]
  149. # The images for the various channels are interleaved within each other.
  150. image_data = array.array("H", data)
  151. image_data_start = 4 + channel_offset
  152. return timestamp, image_data[image_data_start::self.channel_count]
  153. def _calculate_image_set_number(self, time_index, fov, z_level):
  154. return time_index * self.field_of_view_count * self.z_level_count + (fov * self.z_level_count + z_level)