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.

124 lines
4.7 KiB

10 years ago
10 years ago
  1. # -*- coding: utf-8 -*-
  2. from collections import namedtuple
  3. from nd2reader.model import Channel
  4. import logging
  5. from nd2reader.model import Image, ImageSet
  6. from nd2reader.reader import Nd2FileReader
  7. chunk = namedtuple('Chunk', ['location', 'length'])
  8. field_of_view = namedtuple('FOV', ['number', 'x', 'y', 'z', 'pfs_offset'])
  9. print(__name__)
  10. log = logging.getLogger(__name__)
  11. log.setLevel(logging.WARN)
  12. class Nd2(Nd2FileReader):
  13. def __init__(self, filename):
  14. super(Nd2, self).__init__(filename)
  15. def get_image(self, time_index, fov, channel_name, z_level):
  16. image_set_number = self._calculate_image_set_number(time_index, fov, z_level)
  17. timestamp, raw_image_data = self.get_raw_image_data(image_set_number, self.channel_offset[channel_name])
  18. return Image(timestamp, raw_image_data, fov, channel_name, z_level, self.height, self.width)
  19. def __iter__(self):
  20. """
  21. Just return every image in order (might not be exactly the order that the images were physically taken, but it will
  22. be within a few seconds). A better explanation is probably needed here.
  23. """
  24. for i in range(self._image_count):
  25. for fov in range(self.field_of_view_count):
  26. for z_level in range(self.z_level_count):
  27. for channel in self.channels:
  28. image = self.get_image(i, fov, channel.name, z_level)
  29. if image.is_valid:
  30. yield image
  31. def image_sets(self, field_of_view, time_indices=None, channels=None, z_levels=None):
  32. """
  33. Gets all the images for a given field of view and
  34. """
  35. timepoint_set = xrange(self.time_index_count) if time_indices is None else time_indices
  36. channel_set = [channel.name for channel in self.channels] if channels is None else channels
  37. z_level_set = xrange(self.z_level_count) if z_levels is None else z_levels
  38. for timepoint in timepoint_set:
  39. image_set = ImageSet()
  40. for channel_name in channel_set:
  41. for z_level in z_level_set:
  42. image = self.get_image(timepoint, field_of_view, channel_name, z_level)
  43. if image.is_valid:
  44. image_set.add(image)
  45. yield image_set
  46. self._channel_offset = None
  47. @property
  48. def height(self):
  49. """
  50. :return: height of each image, in pixels
  51. """
  52. return self._metadata['ImageAttributes']['SLxImageAttributes']['uiHeight']
  53. @property
  54. def width(self):
  55. """
  56. :return: width of each image, in pixels
  57. """
  58. return self._metadata['ImageAttributes']['SLxImageAttributes']['uiWidth']
  59. @property
  60. def channels(self):
  61. metadata = self._metadata['ImageMetadataSeq']['SLxPictureMetadata']['sPicturePlanes']
  62. try:
  63. validity = self._metadata['ImageMetadata']['SLxExperiment']['ppNextLevelEx'][''][0]['ppNextLevelEx'][''][0]['pItemValid']
  64. except KeyError:
  65. # If none of the channels have been deleted, there is no validity list, so we just make one
  66. validity = [True for i in metadata]
  67. # Channel information is contained in dictionaries with the keys a0, a1...an where the number
  68. # indicates the order in which the channel is stored. So by sorting the dicts alphabetically
  69. # we get the correct order.
  70. for (label, chan), valid in zip(sorted(metadata['sPlaneNew'].items()), validity):
  71. if not valid:
  72. continue
  73. name = chan['sDescription']
  74. exposure_time = metadata['sSampleSetting'][label]['dExposureTime']
  75. camera = metadata['sSampleSetting'][label]['pCameraSetting']['CameraUserName']
  76. yield Channel(name, camera, exposure_time)
  77. @property
  78. def channel_names(self):
  79. """
  80. A convenience method for getting an alphabetized list of channel names.
  81. :return: list[str]
  82. """
  83. for channel in sorted(self.channels, key=lambda x: x.name):
  84. yield channel.name
  85. @property
  86. def _image_count(self):
  87. return self._metadata['ImageAttributes']['SLxImageAttributes']['uiSequenceCount']
  88. @property
  89. def _sequence_count(self):
  90. return self._metadata['ImageEvents']['RLxExperimentRecord']['uiCount']
  91. @property
  92. def channel_offset(self):
  93. if self._channel_offset is None:
  94. self._channel_offset = {}
  95. for n, channel in enumerate(self.channels):
  96. self._channel_offset[channel.name] = n
  97. return self._channel_offset
  98. def _calculate_image_set_number(self, time_index, fov, z_level):
  99. return time_index * self.field_of_view_count * self.z_level_count + (fov * self.z_level_count + z_level)