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.

295 lines
12 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 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
7 years ago
8 years ago
8 years ago
8 years ago
9 years ago
6 years ago
6 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, 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. frame_number = 0 if frame_number is None else frame_number
  75. field_of_view = 0 if field_of_view is None else field_of_view
  76. channel = 0 if channel is None else channel
  77. z_level = 0 if z_level is None else z_level
  78. image_group_number = self._calculate_image_group_number(frame_number, field_of_view, z_level)
  79. try:
  80. timestamp, raw_image_data = self._get_raw_image_data(image_group_number, channel,
  81. height, width)
  82. except (TypeError, NoImageError):
  83. return Frame([], frame_no=frame_number, metadata=self._get_frame_metadata())
  84. else:
  85. return raw_image_data
  86. @staticmethod
  87. def get_dtype_from_metadata():
  88. """Determine the data type from the metadata.
  89. For now, always use float64 to prevent unexpected overflow errors when manipulating the data (calculating sums/
  90. means/etc.)
  91. """
  92. return np.float64
  93. def _check_version_supported(self):
  94. """Checks if the ND2 file version is supported by this reader.
  95. Returns:
  96. bool: True on supported
  97. """
  98. major_version, minor_version = get_version(self._fh)
  99. supported = self.supported_file_versions.get(
  100. (major_version, minor_version)) or self.supported_file_versions.get((major_version, None))
  101. if not supported:
  102. print("Warning: No parser is available for your current ND2 version (%d.%d). " % (
  103. major_version, minor_version) + "This might lead to unexpected behaviour.")
  104. return supported
  105. def _parse_metadata(self):
  106. """Reads all metadata and instantiates the Metadata object.
  107. """
  108. # Retrieve raw metadata from the label mapping
  109. self._label_map = self._build_label_map()
  110. self._raw_metadata = RawMetadata(self._fh, self._label_map)
  111. self.metadata = self._raw_metadata.__dict__
  112. def _build_label_map(self):
  113. """
  114. Every label ends with an exclamation point, however, we can't directly search for those to find all the labels
  115. as some of the bytes contain the value 33, which is the ASCII code for "!". So we iteratively find each label,
  116. grab the subsequent data (always 16 bytes long), advance to the next label and repeat.
  117. Returns:
  118. LabelMap: the computed label map
  119. """
  120. # go 8 bytes back from file end
  121. self._fh.seek(-8, 2)
  122. chunk_map_start_location = struct.unpack("Q", self._fh.read(8))[0]
  123. self._fh.seek(chunk_map_start_location)
  124. raw_text = self._fh.read(-1)
  125. return LabelMap(raw_text)
  126. def _calculate_field_of_view(self, index):
  127. """Determines what field of view was being imaged for a given image.
  128. Args:
  129. index(int): the index (which is simply the order in which the image was acquired)
  130. Returns:
  131. int: the field of view
  132. """
  133. images_per_cycle = len(self.metadata["z_levels"]) * len(self.metadata["channels"])
  134. return int((index - (index % images_per_cycle)) / images_per_cycle) % len(self.metadata["fields_of_view"])
  135. def _calculate_channel(self, index):
  136. """Determines what channel a particular image is.
  137. Args:
  138. index(int): the index (which is simply the order in which the image was acquired)
  139. Returns:
  140. string: the name of the color channel
  141. """
  142. return self.metadata["channels"][index % len(self.metadata["channels"])]
  143. def _calculate_z_level(self, index):
  144. """Determines the plane in the z-axis a given image was taken in.
  145. In the future, this will be replaced with the actual offset in micrometers.
  146. Args:
  147. index(int): the index (which is simply the order in which the image was acquired)
  148. Returns:
  149. The z level
  150. """
  151. return self.metadata["z_levels"][int(
  152. ((index - (index % len(self.metadata["channels"]))) / len(self.metadata["channels"])) % len(
  153. self.metadata["z_levels"]))]
  154. def _calculate_image_group_number(self, frame_number, fov, z_level):
  155. """
  156. Images are grouped together if they share the same time index, field of view, and z-level.
  157. Args:
  158. frame_number: the time index
  159. fov: the field of view number
  160. z_level: the z level number
  161. Returns:
  162. int: the image group number
  163. """
  164. z_length = len(self.metadata['z_levels'])
  165. z_length = z_length if z_length > 0 else 1
  166. fields_of_view = len(self.metadata["fields_of_view"])
  167. fields_of_view = fields_of_view if fields_of_view > 0 else 1
  168. return frame_number * fields_of_view * z_length + (fov * z_length + z_level)
  169. def _calculate_frame_number(self, image_group_number, field_of_view, z_level):
  170. """
  171. Images are in the same frame if they share the same group number and field of view and are taken sequentially.
  172. Args:
  173. image_group_number: the image group number (see _calculate_image_group_number)
  174. field_of_view: the field of view number
  175. z_level: the z level number
  176. Returns:
  177. """
  178. return (image_group_number - (field_of_view * len(self.metadata["z_levels"]) + z_level)) / (
  179. len(self.metadata["fields_of_view"]) * len(self.metadata["z_levels"]))
  180. @property
  181. def _channel_offset(self):
  182. """
  183. Image data is interleaved for each image set. That is, if there are four images in a set, the first image
  184. will consist of pixels 1, 5, 9, etc, the second will be pixels 2, 6, 10, and so forth.
  185. Returns:
  186. dict: the channel offset for each channel
  187. """
  188. return {channel: n for n, channel in enumerate(self.metadata["channels"])}
  189. def _get_raw_image_data(self, image_group_number, channel_offset, height, width):
  190. """Reads the raw bytes and the timestamp of an image.
  191. Args:
  192. image_group_number: the image group number (see _calculate_image_group_number)
  193. channel_offset: the number of the color channel
  194. height: the height of the image
  195. width: the width of the image
  196. Returns:
  197. """
  198. chunk = self._label_map.get_image_data_location(image_group_number)
  199. data = read_chunk(self._fh, chunk)
  200. # All images in the same image group share the same timestamp! So if you have complicated image data,
  201. # your timestamps may not be entirely accurate. Practically speaking though, they'll only be off by a few
  202. # seconds unless you're doing something super weird.
  203. timestamp = struct.unpack("d", data[:8])[0]
  204. image_group_data = array.array("H", data)
  205. image_data_start = 4 + channel_offset
  206. # The images for the various channels are interleaved within the same array. For example, the second image
  207. # of a four image group will be composed of bytes 2, 6, 10, etc. If you understand why someone would design
  208. # a data structure that way, please send the author of this library a message.
  209. number_of_true_channels = int(len(image_group_data[4:]) / (height * width))
  210. try:
  211. image_data = np.reshape(image_group_data[image_data_start::number_of_true_channels], (height, width))
  212. except ValueError:
  213. image_data = np.reshape(image_group_data[image_data_start::number_of_true_channels], (height, int(round(len(image_group_data[image_data_start::number_of_true_channels])/height))))
  214. # Skip images that are all zeros! This is important, since NIS Elements creates blank "gap" images if you
  215. # don't have the same number of images each cycle. We discovered this because we only took GFP images every
  216. # other cycle to reduce phototoxicity, but NIS Elements still allocated memory as if we were going to take
  217. # them every cycle.
  218. if np.any(image_data):
  219. return timestamp, Frame(image_data, metadata=self._get_frame_metadata())
  220. raise NoImageError
  221. def _get_frame_metadata(self):
  222. """Get the metadata for one frame
  223. Returns:
  224. dict: a dictionary containing the parsed metadata
  225. """
  226. return self.metadata