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.

289 lines
11 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
8 years ago
  1. # -*- coding: utf-8 -*-
  2. import struct
  3. import array
  4. import six
  5. from pims.base_frames import Frame
  6. import numpy as np
  7. from nd2reader.common import get_version, read_chunk
  8. from nd2reader.exceptions import InvalidVersionError, NoImageError
  9. from nd2reader.label_map import LabelMap
  10. from nd2reader.raw_metadata import RawMetadata
  11. class Parser(object):
  12. """Parses ND2 files and creates a Metadata and driver object.
  13. """
  14. CHUNK_HEADER = 0xabeceda
  15. CHUNK_MAP_START = six.b("ND2 FILEMAP SIGNATURE NAME 0001!")
  16. CHUNK_MAP_END = six.b("ND2 CHUNK MAP SIGNATURE 0000001!")
  17. supported_file_versions = {(3, None): True}
  18. def __init__(self, fh):
  19. self._fh = fh
  20. self._label_map = None
  21. self._raw_metadata = None
  22. self.metadata = None
  23. # First check the file version
  24. self.supported = self._check_version_supported()
  25. # Parse the metadata
  26. self._parse_metadata()
  27. def calculate_image_properties(self, index):
  28. """Calculate FOV, channels and z_levels
  29. Args:
  30. index(int): the index (which is simply the order in which the image was acquired)
  31. Returns:
  32. tuple: tuple of the field of view, the channel and the z level
  33. """
  34. field_of_view = self._calculate_field_of_view(index)
  35. channel = self._calculate_channel(index)
  36. z_level = self._calculate_z_level(index)
  37. return field_of_view, channel, z_level
  38. def get_image(self, index):
  39. """
  40. Creates an Image object and adds its metadata, based on the index (which is simply the order in which the image
  41. was acquired). May return None if the ND2 contains multiple channels and not all were taken in each cycle (for
  42. example, if you take bright field images every minute, and GFP images every five minutes, there will be some
  43. indexes that do not contain an image. The reason for this is complicated, but suffice it to say that we hope to
  44. eliminate this possibility in future releases. For now, you'll need to check if your image is None if you're
  45. doing anything out of the ordinary.
  46. Args:
  47. index(int): the index (which is simply the order in which the image was acquired)
  48. Returns:
  49. Frame: the image
  50. """
  51. field_of_view, channel, z_level = self.calculate_image_properties(index)
  52. channel_offset = index % len(self.metadata["channels"])
  53. image_group_number = int(index / len(self.metadata["channels"]))
  54. frame_number = self._calculate_frame_number(image_group_number, field_of_view, z_level)
  55. try:
  56. timestamp, image = self._get_raw_image_data(image_group_number, channel_offset, self.metadata["height"],
  57. self.metadata["width"])
  58. except (TypeError, NoImageError):
  59. return Frame([], frame_no=frame_number, metadata=self._get_frame_metadata())
  60. else:
  61. return image
  62. def get_image_by_attributes(self, frame_number, field_of_view, channel_name, z_level, height, width):
  63. """Gets an image based on its attributes alone
  64. Args:
  65. frame_number: the frame number
  66. field_of_view: the field of view
  67. channel_name: the color channel name
  68. z_level: the z level
  69. height: the height of the image
  70. width: the width of the image
  71. Returns:
  72. Frame: the requested image
  73. """
  74. image_group_number = self._calculate_image_group_number(frame_number, field_of_view, z_level)
  75. try:
  76. timestamp, raw_image_data = self._get_raw_image_data(image_group_number, self._channel_offset[channel_name],
  77. height, width)
  78. except (TypeError, NoImageError):
  79. return Frame([], frame_no=frame_number, metadata=self._get_frame_metadata())
  80. else:
  81. return raw_image_data
  82. @staticmethod
  83. def get_dtype_from_metadata():
  84. """Determine the data type from the metadata.
  85. For now, always use float64 to prevent unexpected overflow errors when manipulating the data (calculating sums/
  86. means/etc.)
  87. """
  88. return np.float64
  89. def _check_version_supported(self):
  90. """Checks if the ND2 file version is supported by this reader.
  91. Returns:
  92. bool: True on supported
  93. Raises:
  94. InvalidVersionError: Raises an error if the version is unsupported
  95. """
  96. major_version, minor_version = get_version(self._fh)
  97. supported = self.supported_file_versions.get((major_version, minor_version)) or \
  98. self.supported_file_versions.get((major_version, None))
  99. if not supported:
  100. raise InvalidVersionError("No parser is available for that version.")
  101. return supported
  102. def _parse_metadata(self):
  103. """Reads all metadata and instantiates the Metadata object.
  104. """
  105. # Retrieve raw metadata from the label mapping
  106. self._label_map = self._build_label_map()
  107. self._raw_metadata = RawMetadata(self._fh, self._label_map)
  108. self.metadata = self._raw_metadata.__dict__
  109. def _build_label_map(self):
  110. """
  111. Every label ends with an exclamation point, however, we can't directly search for those to find all the labels
  112. as some of the bytes contain the value 33, which is the ASCII code for "!". So we iteratively find each label,
  113. grab the subsequent data (always 16 bytes long), advance to the next label and repeat.
  114. Returns:
  115. LabelMap: the computed label map
  116. """
  117. self._fh.seek(-8, 2)
  118. chunk_map_start_location = struct.unpack("Q", self._fh.read(8))[0]
  119. self._fh.seek(chunk_map_start_location)
  120. raw_text = self._fh.read(-1)
  121. return LabelMap(raw_text)
  122. def _calculate_field_of_view(self, index):
  123. """Determines what field of view was being imaged for a given image.
  124. Args:
  125. index(int): the index (which is simply the order in which the image was acquired)
  126. Returns:
  127. int: the field of view
  128. """
  129. images_per_cycle = len(self.metadata["z_levels"]) * len(self.metadata["channels"])
  130. return int((index - (index % images_per_cycle)) / images_per_cycle) % len(self.metadata["fields_of_view"])
  131. def _calculate_channel(self, index):
  132. """Determines what channel a particular image is.
  133. Args:
  134. index(int): the index (which is simply the order in which the image was acquired)
  135. Returns:
  136. string: the name of the color channel
  137. """
  138. return self.metadata["channels"][index % len(self.metadata["channels"])]
  139. def _calculate_z_level(self, index):
  140. """Determines the plane in the z-axis a given image was taken in.
  141. In the future, this will be replaced with the actual offset in micrometers.
  142. Args:
  143. index(int): the index (which is simply the order in which the image was acquired)
  144. Returns:
  145. The z level
  146. """
  147. return self.metadata["z_levels"][int(
  148. ((index - (index % len(self.metadata["channels"]))) / len(self.metadata["channels"])) % len(
  149. self.metadata["z_levels"]))]
  150. def _calculate_image_group_number(self, frame_number, fov, z_level):
  151. """
  152. Images are grouped together if they share the same time index, field of view, and z-level.
  153. Args:
  154. frame_number: the time index
  155. fov: the field of view number
  156. z_level: the z level number
  157. Returns:
  158. int: the image group number
  159. """
  160. z_length = len(self.metadata['z_levels'])
  161. z_length = z_length if z_length > 0 else 1
  162. fields_of_view = len(self.metadata["fields_of_view"])
  163. fields_of_view = fields_of_view if fields_of_view > 0 else 1
  164. return frame_number * fields_of_view * z_length + (fov * z_length + z_level)
  165. def _calculate_frame_number(self, image_group_number, field_of_view, z_level):
  166. """
  167. Images are in the same frame if they share the same group number and field of view and are taken sequentially.
  168. Args:
  169. image_group_number: the image group number (see _calculate_image_group_number)
  170. field_of_view: the field of view number
  171. z_level: the z level number
  172. Returns:
  173. """
  174. return (image_group_number - (field_of_view * len(self.metadata["z_levels"]) + z_level)) / (
  175. len(self.metadata["fields_of_view"]) * len(self.metadata["z_levels"]))
  176. @property
  177. def _channel_offset(self):
  178. """
  179. Image data is interleaved for each image set. That is, if there are four images in a set, the first image
  180. will consist of pixels 1, 5, 9, etc, the second will be pixels 2, 6, 10, and so forth.
  181. Returns:
  182. dict: the channel offset for each channel
  183. """
  184. return {channel: n for n, channel in enumerate(self.metadata["channels"])}
  185. def _get_raw_image_data(self, image_group_number, channel_offset, height, width):
  186. """Reads the raw bytes and the timestamp of an image.
  187. Args:
  188. image_group_number: the image group number (see _calculate_image_group_number)
  189. channel_offset: the number of the color channel
  190. height: the height of the image
  191. width: the width of the image
  192. Returns:
  193. """
  194. chunk = self._label_map.get_image_data_location(image_group_number)
  195. data = read_chunk(self._fh, chunk)
  196. # All images in the same image group share the same timestamp! So if you have complicated image data,
  197. # your timestamps may not be entirely accurate. Practically speaking though, they'll only be off by a few
  198. # seconds unless you're doing something super weird.
  199. timestamp = struct.unpack("d", data[:8])[0]
  200. image_group_data = array.array("H", data)
  201. image_data_start = 4 + channel_offset
  202. # The images for the various channels are interleaved within the same array. For example, the second image
  203. # of a four image group will be composed of bytes 2, 6, 10, etc. If you understand why someone would design
  204. # a data structure that way, please send the author of this library a message.
  205. number_of_true_channels = int((len(image_group_data) - 4) / (height * width))
  206. image_data = np.reshape(image_group_data[image_data_start::number_of_true_channels], (height, width))
  207. # Skip images that are all zeros! This is important, since NIS Elements creates blank "gap" images if you
  208. # don't have the same number of images each cycle. We discovered this because we only took GFP images every
  209. # other cycle to reduce phototoxicity, but NIS Elements still allocated memory as if we were going to take
  210. # them every cycle.
  211. if np.any(image_data):
  212. return timestamp, Frame(image_data, metadata=self._get_frame_metadata())
  213. raise NoImageError
  214. def _get_frame_metadata(self):
  215. """Get the metadata for one frame
  216. Returns:
  217. dict: a dictionary containing the parsed metadata
  218. """
  219. return self.metadata