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.

409 lines
16 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
4 years ago
7 years ago
4 years ago
7 years ago
7 years ago
4 years ago
6 years ago
4 years ago
4 years ago
8 years ago
7 years ago
4 years ago
  1. # -*- coding: utf-8 -*-
  2. import struct
  3. import array
  4. import six
  5. import warnings
  6. from pims.base_frames import Frame
  7. import numpy as np
  8. from nd2reader2.common import get_version, read_chunk
  9. from nd2reader2.label_map import LabelMap
  10. from nd2reader2.raw_metadata import RawMetadata
  11. from nd2reader2 import stitched
  12. class Parser(object):
  13. """Parses ND2 files and creates a Metadata and driver object.
  14. """
  15. CHUNK_HEADER = 0xabeceda
  16. CHUNK_MAP_START = six.b("ND2 FILEMAP SIGNATURE NAME 0001!")
  17. CHUNK_MAP_END = six.b("ND2 CHUNK MAP SIGNATURE 0000001!")
  18. supported_file_versions = {(3, None): True}
  19. def __init__(self, fh):
  20. self._fh = fh
  21. self._label_map = None
  22. self._raw_metadata = None
  23. self.metadata = None
  24. # First check the file version
  25. self.supported = self._check_version_supported()
  26. # Parse the metadata
  27. self._parse_metadata()
  28. def calculate_image_properties(self, index):
  29. """Calculate FOV, channels and z_levels
  30. Args:
  31. index(int): the index (which is simply the order in which the image was acquired)
  32. Returns:
  33. tuple: tuple of the field of view, the channel and the z level
  34. """
  35. field_of_view = self._calculate_field_of_view(index)
  36. channel = self._calculate_channel(index)
  37. z_level = self._calculate_z_level(index)
  38. return field_of_view, channel, z_level
  39. def get_image(self, index):
  40. """
  41. Creates an Image object and adds its metadata, based on the index (which is simply the order in which the image
  42. was acquired). May return None if the ND2 contains multiple channels and not all were taken in each cycle (for
  43. example, if you take bright field images every minute, and GFP images every five minutes, there will be some
  44. indexes that do not contain an image. The reason for this is complicated, but suffice it to say that we hope to
  45. eliminate this possibility in future releases. For now, you'll need to check if your image is None if you're
  46. doing anything out of the ordinary.
  47. Args:
  48. index(int): the index (which is simply the order in which the image was acquired)
  49. Returns:
  50. Frame: the image
  51. """
  52. field_of_view, channel, z_level = self.calculate_image_properties(index)
  53. channel_offset = index % len(self.metadata["channels"])
  54. image_group_number = int(index / len(self.metadata["channels"]))
  55. frame_number = self._calculate_frame_number(image_group_number, field_of_view, z_level)
  56. try:
  57. timestamp, image = self._get_raw_image_data(image_group_number, channel_offset, self.metadata["height"],
  58. self.metadata["width"])
  59. except (TypeError):
  60. return Frame([], frame_no=frame_number, metadata=self._get_frame_metadata())
  61. else:
  62. return Frame(image, frame_no=frame_number, metadata=self._get_frame_metadata())
  63. def get_slice_by_attributes(self, xywh, frame_number, field_of_view, channel, z_level, height, width):
  64. """Gets a rectangular slice of an image based on its attributes alone
  65. Args:
  66. xywh: tuples containing (x, y, w, h) values of the
  67. rectangular region to load
  68. frame_number: the frame number
  69. field_of_view: the field of view
  70. channel_name: the color channel name
  71. z_level: the z level
  72. height: the height of the image
  73. width: the width of the image
  74. Returns:
  75. Frame: the requested image
  76. """
  77. frame_number = 0 if frame_number is None else frame_number
  78. field_of_view = 0 if field_of_view is None else field_of_view
  79. channel = 0 if channel is None else channel
  80. z_level = 0 if z_level is None else z_level
  81. image_group_number = self._calculate_image_group_number(frame_number, field_of_view, z_level)
  82. try:
  83. timestamp, raw_image_data = self._get_raw_slice_data(
  84. xywh, image_group_number, channel, height, width
  85. )
  86. except (TypeError):
  87. return Frame([], frame_no=frame_number, metadata=self._get_frame_metadata())
  88. else:
  89. return Frame(raw_image_data, frame_no=frame_number, metadata=self._get_frame_metadata())
  90. def get_image_by_attributes(self, frame_number, field_of_view, channel, z_level, height, width):
  91. """Gets an image based on its attributes alone
  92. Args:
  93. frame_number: the frame number
  94. field_of_view: the field of view
  95. channel_name: the color channel name
  96. z_level: the z level
  97. height: the height of the image
  98. width: the width of the image
  99. Returns:
  100. Frame: the requested image
  101. """
  102. frame_number = 0 if frame_number is None else frame_number
  103. field_of_view = 0 if field_of_view is None else field_of_view
  104. channel = 0 if channel is None else channel
  105. z_level = 0 if z_level is None else z_level
  106. image_group_number = self._calculate_image_group_number(frame_number, field_of_view, z_level)
  107. try:
  108. timestamp, raw_image_data = self._get_raw_image_data(image_group_number, channel,
  109. height, width)
  110. except (TypeError):
  111. return Frame([], frame_no=frame_number, metadata=self._get_frame_metadata())
  112. else:
  113. return Frame(raw_image_data, frame_no=frame_number, metadata=self._get_frame_metadata())
  114. @staticmethod
  115. def get_dtype_from_metadata():
  116. """Determine the data type from the metadata.
  117. For now, always use float64 to prevent unexpected overflow errors when manipulating the data (calculating sums/
  118. means/etc.)
  119. """
  120. return np.float64
  121. def _check_version_supported(self):
  122. """Checks if the ND2 file version is supported by this reader.
  123. Returns:
  124. bool: True on supported
  125. """
  126. major_version, minor_version = get_version(self._fh)
  127. supported = self.supported_file_versions.get(
  128. (major_version, minor_version)) or self.supported_file_versions.get((major_version, None))
  129. if not supported:
  130. print("Warning: No parser is available for your current ND2 version (%d.%d). " % (
  131. major_version, minor_version) + "This might lead to unexpected behaviour.")
  132. return supported
  133. def _parse_metadata(self):
  134. """Reads all metadata and instantiates the Metadata object.
  135. """
  136. # Retrieve raw metadata from the label mapping
  137. self._label_map = self._build_label_map()
  138. self._raw_metadata = RawMetadata(self._fh, self._label_map)
  139. self.metadata = self._raw_metadata.__dict__
  140. self.acquisition_times = self._raw_metadata.acquisition_times
  141. def _build_label_map(self):
  142. """
  143. Every label ends with an exclamation point, however, we can't directly search for those to find all the labels
  144. as some of the bytes contain the value 33, which is the ASCII code for "!". So we iteratively find each label,
  145. grab the subsequent data (always 16 bytes long), advance to the next label and repeat.
  146. Returns:
  147. LabelMap: the computed label map
  148. """
  149. # go 8 bytes back from file end
  150. self._fh.seek(-8, 2)
  151. chunk_map_start_location = struct.unpack("Q", self._fh.read(8))[0]
  152. self._fh.seek(chunk_map_start_location)
  153. raw_text = self._fh.read(-1)
  154. return LabelMap(raw_text)
  155. def _calculate_field_of_view(self, index):
  156. """Determines what field of view was being imaged for a given image.
  157. Args:
  158. index(int): the index (which is simply the order in which the image was acquired)
  159. Returns:
  160. int: the field of view
  161. """
  162. images_per_cycle = len(self.metadata["z_levels"]) * len(self.metadata["channels"])
  163. return int((index - (index % images_per_cycle)) / images_per_cycle) % len(self.metadata["fields_of_view"])
  164. def _calculate_channel(self, index):
  165. """Determines what channel a particular image is.
  166. Args:
  167. index(int): the index (which is simply the order in which the image was acquired)
  168. Returns:
  169. string: the name of the color channel
  170. """
  171. return self.metadata["channels"][index % len(self.metadata["channels"])]
  172. def _calculate_z_level(self, index):
  173. """Determines the plane in the z-axis a given image was taken in.
  174. In the future, this will be replaced with the actual offset in micrometers.
  175. Args:
  176. index(int): the index (which is simply the order in which the image was acquired)
  177. Returns:
  178. The z level
  179. """
  180. return self.metadata["z_levels"][int(
  181. ((index - (index % len(self.metadata["channels"]))) / len(self.metadata["channels"])) % len(
  182. self.metadata["z_levels"]))]
  183. def _calculate_image_group_number(self, frame_number, fov, z_level):
  184. """
  185. Images are grouped together if they share the same time index, field of view, and z-level.
  186. Args:
  187. frame_number: the time index
  188. fov: the field of view number
  189. z_level: the z level number
  190. Returns:
  191. int: the image group number
  192. """
  193. z_length = len(self.metadata['z_levels'])
  194. z_length = z_length if z_length > 0 else 1
  195. fields_of_view = len(self.metadata["fields_of_view"])
  196. fields_of_view = fields_of_view if fields_of_view > 0 else 1
  197. return frame_number * fields_of_view * z_length + (fov * z_length + z_level)
  198. def _calculate_frame_number(self, image_group_number, field_of_view, z_level):
  199. """
  200. Images are in the same frame if they share the same group number and field of view and are taken sequentially.
  201. Args:
  202. image_group_number: the image group number (see _calculate_image_group_number)
  203. field_of_view: the field of view number
  204. z_level: the z level number
  205. Returns:
  206. """
  207. return (image_group_number - (field_of_view * len(self.metadata["z_levels"]) + z_level)) / (len(self.metadata["fields_of_view"]) * len(self.metadata["z_levels"]))
  208. @property
  209. def _channel_offset(self):
  210. """
  211. Image data is interleaved for each image set. That is, if there are four images in a set, the first image
  212. will consist of pixels 1, 5, 9, etc, the second will be pixels 2, 6, 10, and so forth.
  213. Returns:
  214. dict: the channel offset for each channel
  215. """
  216. return {channel: n for n, channel in enumerate(self.metadata["channels"])}
  217. def _get_raw_slice_data(self, xywh, image_group_number, channel, height, width):
  218. """Reads the raw bytes and the timestamp of a rectangular slice
  219. of an image.
  220. Args:
  221. xywh: tuples containing (x, y, w, h) values of the
  222. rectangular region to load
  223. image_group_number: the image group number (see _calculate_image_group_number)
  224. channel: the position (int) of the channel to load
  225. height: the height of the image
  226. width: the width of the image
  227. Returns:
  228. """
  229. size_c = len(self.metadata["channels"])
  230. x0, y0, w, h = xywh
  231. chunk_location = self._label_map.get_image_data_location(image_group_number)
  232. fh = self._fh
  233. if chunk_location is None or fh is None:
  234. return None
  235. fh.seek(chunk_location)
  236. # The chunk metadata is always 16 bytes long
  237. chunk_metadata = fh.read(16)
  238. header, relative_offset, data_length = struct.unpack("IIQ", chunk_metadata)
  239. if header != 0xabeceda:
  240. raise ValueError("The ND2 file seems to be corrupted.")
  241. # We start at the location of the chunk metadata, skip over the metadata, and then proceed to the
  242. # start of the actual data field, which is at some arbitrary place after the metadata.
  243. fh.seek(chunk_location + 16 + relative_offset)
  244. # Read timestamp (8 bytes)
  245. timestamp = struct.unpack("d", fh.read(8))[0]
  246. # Stitched Images: evaluate number of bytes to strip
  247. # (with stitched images sometimes after each row we have a regular number of extra bytes)
  248. n_unwanted_bytes = (data_length-8) % (height*width)
  249. assert 0 == n_unwanted_bytes % height
  250. rowskip = n_unwanted_bytes // height
  251. # Read ROI: row-by-row
  252. image_start_pos = chunk_location + 16 + relative_offset + 8
  253. line_bytemask = np.zeros(size_c, dtype=np.bool)
  254. line_bytemask[channel] = True
  255. line_bytemask = np.tile(line_bytemask.repeat(2),w)
  256. def get_line(y):
  257. fh.seek(image_start_pos + size_c*2*((width)*y+x0) + y*rowskip)
  258. return np.frombuffer(fh.read(size_c*2*w), np.byte)[line_bytemask]
  259. data = [get_line(y) for y in range(y0, y0+h)]
  260. data = bytes().join(data)
  261. image_group_data = array.array("H", data)
  262. true_channels_no = int(len(image_group_data) / (h * w))
  263. image_data = np.reshape(image_group_data, (h, w, true_channels_no))
  264. missing_channels = ~np.any(image_data, axis=(0, 1))
  265. image_data[..., missing_channels] = np.full(
  266. (h, w, missing_channels.sum()), np.nan)
  267. if np.any(missing_channels):
  268. warnings.warn(
  269. "ND2 file contains gap frames which are represented by "
  270. + "np.nan-filled arrays; to convert to zeros use e.g. "
  271. + "np.nan_to_num(array)")
  272. return timestamp, image_data[...,0]
  273. def _get_raw_image_data(self, image_group_number, channel_offset, height, width):
  274. """Reads the raw bytes and the timestamp of an image.
  275. Args:
  276. image_group_number: the image group number (see _calculate_image_group_number)
  277. channel_offset: the number of the color channel
  278. height: the height of the image
  279. width: the width of the image
  280. Returns:
  281. """
  282. chunk = self._label_map.get_image_data_location(image_group_number)
  283. data = read_chunk(self._fh, chunk)
  284. # All images in the same image group share the same timestamp! So if you have complicated image data,
  285. # your timestamps may not be entirely accurate. Practically speaking though, they'll only be off by a few
  286. # seconds unless you're doing something super weird.
  287. timestamp = struct.unpack("d", data[:8])[0]
  288. image_group_data = array.array("H", data)
  289. image_data_start = 4 + channel_offset
  290. image_group_data = stitched.remove_parsed_unwanted_bytes(image_group_data, image_data_start, height, width)
  291. # The images for the various channels are interleaved within the same array. For example, the second image
  292. # of a four image group will be composed of bytes 2, 6, 10, etc. If you understand why someone would design
  293. # a data structure that way, please send the author of this library a message.
  294. number_of_true_channels = int(len(image_group_data[4:]) / (height * width))
  295. try:
  296. image_data = np.reshape(image_group_data[image_data_start::number_of_true_channels], (height, width))
  297. except ValueError:
  298. new_width = len(image_group_data[image_data_start::number_of_true_channels]) // height
  299. image_data = np.reshape(image_group_data[image_data_start::number_of_true_channels], (height, new_width))
  300. # Skip images that are all zeros! This is important, since NIS Elements creates blank "gap" images if you
  301. # don't have the same number of images each cycle. We discovered this because we only took GFP images every
  302. # other cycle to reduce phototoxicity, but NIS Elements still allocated memory as if we were going to take
  303. # them every cycle.
  304. if np.any(image_data):
  305. return timestamp, image_data
  306. # If a blank "gap" image is encountered, generate an array of corresponding height and width to avoid
  307. # errors with ND2-files with missing frames. Array is filled with nan to reflect that data is missing.
  308. else:
  309. empty_frame = np.full((height, width), np.nan)
  310. warnings.warn(
  311. "ND2 file contains gap frames which are represented by np.nan-filled arrays; to convert to zeros use e.g. np.nan_to_num(array)")
  312. return timestamp, image_data
  313. def _get_frame_metadata(self):
  314. """Get the metadata for one frame
  315. Returns:
  316. dict: a dictionary containing the parsed metadata
  317. """
  318. return self.metadata