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.

290 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(
  98. (major_version, minor_version)) or 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. # go 8 bytes back from file end
  118. self._fh.seek(-8, 2)
  119. chunk_map_start_location = struct.unpack("Q", self._fh.read(8))[0]
  120. self._fh.seek(chunk_map_start_location)
  121. raw_text = self._fh.read(-1)
  122. return LabelMap(raw_text)
  123. def _calculate_field_of_view(self, index):
  124. """Determines what field of view was being imaged for a given image.
  125. Args:
  126. index(int): the index (which is simply the order in which the image was acquired)
  127. Returns:
  128. int: the field of view
  129. """
  130. images_per_cycle = len(self.metadata["z_levels"]) * len(self.metadata["channels"])
  131. return int((index - (index % images_per_cycle)) / images_per_cycle) % len(self.metadata["fields_of_view"])
  132. def _calculate_channel(self, index):
  133. """Determines what channel a particular image is.
  134. Args:
  135. index(int): the index (which is simply the order in which the image was acquired)
  136. Returns:
  137. string: the name of the color channel
  138. """
  139. return self.metadata["channels"][index % len(self.metadata["channels"])]
  140. def _calculate_z_level(self, index):
  141. """Determines the plane in the z-axis a given image was taken in.
  142. In the future, this will be replaced with the actual offset in micrometers.
  143. Args:
  144. index(int): the index (which is simply the order in which the image was acquired)
  145. Returns:
  146. The z level
  147. """
  148. return self.metadata["z_levels"][int(
  149. ((index - (index % len(self.metadata["channels"]))) / len(self.metadata["channels"])) % len(
  150. self.metadata["z_levels"]))]
  151. def _calculate_image_group_number(self, frame_number, fov, z_level):
  152. """
  153. Images are grouped together if they share the same time index, field of view, and z-level.
  154. Args:
  155. frame_number: the time index
  156. fov: the field of view number
  157. z_level: the z level number
  158. Returns:
  159. int: the image group number
  160. """
  161. z_length = len(self.metadata['z_levels'])
  162. z_length = z_length if z_length > 0 else 1
  163. fields_of_view = len(self.metadata["fields_of_view"])
  164. fields_of_view = fields_of_view if fields_of_view > 0 else 1
  165. return frame_number * fields_of_view * z_length + (fov * z_length + z_level)
  166. def _calculate_frame_number(self, image_group_number, field_of_view, z_level):
  167. """
  168. Images are in the same frame if they share the same group number and field of view and are taken sequentially.
  169. Args:
  170. image_group_number: the image group number (see _calculate_image_group_number)
  171. field_of_view: the field of view number
  172. z_level: the z level number
  173. Returns:
  174. """
  175. return (image_group_number - (field_of_view * len(self.metadata["z_levels"]) + z_level)) / (
  176. len(self.metadata["fields_of_view"]) * len(self.metadata["z_levels"]))
  177. @property
  178. def _channel_offset(self):
  179. """
  180. Image data is interleaved for each image set. That is, if there are four images in a set, the first image
  181. will consist of pixels 1, 5, 9, etc, the second will be pixels 2, 6, 10, and so forth.
  182. Returns:
  183. dict: the channel offset for each channel
  184. """
  185. return {channel: n for n, channel in enumerate(self.metadata["channels"])}
  186. def _get_raw_image_data(self, image_group_number, channel_offset, height, width):
  187. """Reads the raw bytes and the timestamp of an image.
  188. Args:
  189. image_group_number: the image group number (see _calculate_image_group_number)
  190. channel_offset: the number of the color channel
  191. height: the height of the image
  192. width: the width of the image
  193. Returns:
  194. """
  195. chunk = self._label_map.get_image_data_location(image_group_number)
  196. data = read_chunk(self._fh, chunk)
  197. # All images in the same image group share the same timestamp! So if you have complicated image data,
  198. # your timestamps may not be entirely accurate. Practically speaking though, they'll only be off by a few
  199. # seconds unless you're doing something super weird.
  200. timestamp = struct.unpack("d", data[:8])[0]
  201. image_group_data = array.array("H", data)
  202. image_data_start = 4 + channel_offset
  203. # The images for the various channels are interleaved within the same array. For example, the second image
  204. # of a four image group will be composed of bytes 2, 6, 10, etc. If you understand why someone would design
  205. # a data structure that way, please send the author of this library a message.
  206. number_of_true_channels = int((len(image_group_data) - 4) / (height * width))
  207. image_data = np.reshape(image_group_data[image_data_start::number_of_true_channels], (height, width))
  208. # Skip images that are all zeros! This is important, since NIS Elements creates blank "gap" images if you
  209. # don't have the same number of images each cycle. We discovered this because we only took GFP images every
  210. # other cycle to reduce phototoxicity, but NIS Elements still allocated memory as if we were going to take
  211. # them every cycle.
  212. if np.any(image_data):
  213. return timestamp, Frame(image_data, metadata=self._get_frame_metadata())
  214. raise NoImageError
  215. def _get_frame_metadata(self):
  216. """Get the metadata for one frame
  217. Returns:
  218. dict: a dictionary containing the parsed metadata
  219. """
  220. return self.metadata