Ejemplo n.º 1
0
    def read_oct_volume(self):
        """ Reads OCT data.

            Returns:
                obj:OCTVolumeWithMetaData
        """
        if b'@IMG_SCAN_03' not in self.chunk_dict:
            raise ValueError(
                'Could not find OCT header @IMG_SCAN_03 in chunk list')
        with open(self.filepath, 'rb') as f:
            chunk_location, chunk_size = self.chunk_dict[b'@IMG_SCAN_03']
            f.seek(chunk_location)
            raw = f.read(22)
            oct_header = self.oct_header.parse(raw)
            number_pixels = oct_header.width * oct_header.height * oct_header.number_slices
            raw_volume = np.fromstring(f.read(number_pixels * 2),
                                       dtype=np.uint16)
            volume = np.array(raw_volume)
            volume = volume.reshape(oct_header.width,
                                    oct_header.height,
                                    oct_header.number_slices,
                                    order='F')
            volume = np.transpose(volume, [1, 0, 2])
        oct_volume = OCTVolumeWithMetaData(
            [volume[:, :, i] for i in range(volume.shape[2])])
        return oct_volume
Ejemplo n.º 2
0
    def read_oct_volume(self, interlaced=False):
        """ Reads OCT data.
        Args:
            interlaced (bool): Determines whether data needs to be de-interlaced.

            Returns:
                obj:OCTVolumeWithMetaData
        """
        with open(self.filepath, 'rb') as f:
            volume = np.frombuffer(
                f.read(), dtype=np.uint8
            )  # np.fromstring() gives numpy depreciation warning
            num_slices = len(volume) // (1024 * 512)
            volume = volume.reshape((1024, 512, num_slices), order='F')
            if interlaced:
                shape = volume.shape
                interlaced = np.zeros(
                    (int(shape[0] / 2), shape[1], shape[2] * 2))
                interlaced[..., 0::2] = volume[:512, ...]
                interlaced[..., 1::2] = volume[512:, ...]
                interlaced = np.rot90(interlaced, axes=(0, 1))
                volume = interlaced

        oct_volume = OCTVolumeWithMetaData(
            [volume[:, :, i] for i in range(volume.shape[2])])
        return oct_volume
Ejemplo n.º 3
0
    def read_oct_volume(self):
        """ Reads OCT data.

            Returns:
                obj:OCTVolumeWithMetaData
        """

        if b'@IMG_JPEG' not in self.chunk_dict:
            raise ValueError(
                'Could not find OCT header @IMG_JPEG in chunk list')
        with open(self.filepath, 'rb') as f:
            chunk_location, chunk_size = self.chunk_dict[b'@IMG_JPEG']
            f.seek(chunk_location)  # Set the chunk’s current position.
            raw = f.read(25)
            oct_header = self.oct_header.parse(raw)
            volume = np.zeros((oct_header.height, oct_header.width,
                               oct_header.number_slices))
            for i in range(oct_header.number_slices):
                size = np.frombuffer(f.read(4), dtype=np.int32)[0]
                raw_slice = f.read(size)
                slice = decode(raw_slice)
                volume[:, :, i] = slice
        oct_volume = OCTVolumeWithMetaData(
            [volume[:, :, i] for i in range(volume.shape[2])])
        return oct_volume
Ejemplo n.º 4
0
    def read_oct_volume(self):
        """ Reads OCT data.

            Returns:
                obj:OCTVolumeWithMetaData
        """
        import pydicom
        dicom_data = pydicom.dcmread(self.filepath)
        pixel_data = dicom_data.pixel_array
        oct_volume = OCTVolumeWithMetaData(volume=pixel_data)
        return oct_volume
Ejemplo n.º 5
0
 def load_oct_volume(self):
     volFrames = np.reshape(self.frames.data, self.vol_frames_shape)
     try:
         with open(self.filepath, 'rb') as f:
             for t, v in enumerate(volFrames):
                 for z, frame in enumerate(v):
                     self.vol[t, z, :, :] = frame.load(f, self.frames.geom)
         self.loaded = True
     except Exception as e:
         print(e)
         print('Stopping load')
     return [
         OCTVolumeWithMetaData(self.vol[t, :, :, :])
         for t in range(self.vol.shape[0])
     ]
Ejemplo n.º 6
0
    def read_oct_volume(self):
        """ Reads OCT data.

            Returns:
                obj:OCTVolumeWithMetaData
        """
        with open(self.filepath, 'rb') as f:
            volume = np.fromstring(f.read(), dtype=np.uint8)
            volume = volume.reshape((1024, 512, 128), order='F')
            shape = volume.shape
            # volume = np.transpose(volume, [2, 1, 0])

            interlaced = np.zeros((int(shape[0] / 2), shape[1], shape[2] * 2))
            interlaced[..., 0::2] = volume[:512, ...]
            interlaced[..., 1::2] = volume[512:, ...]
            interlaced = np.rot90(interlaced, axes=(0, 1))
        oct_volume = OCTVolumeWithMetaData([interlaced[:, :, i] for i in range(interlaced.shape[2])])
        return oct_volume
Ejemplo n.º 7
0
    def read_oct_volume(self):
        """ Reads OCT data.

            Returns:
                obj:OCTVolumeWithMetaData
        """
        with open(self.filepath, 'rb') as f:
            raw = f.read(36)
            header = self.header_structure.parse(raw)

            raw = f.read(52)
            main_directory = self.main_directory_structure.parse(raw)

            # traverse list of main directories in first pass
            directory_stack = []

            current = main_directory.current
            while current != 0:
                directory_stack.append(current)
                f.seek(current)
                raw = f.read(52)
                directory_chunk = self.main_directory_structure.parse(raw)
                current = directory_chunk.prev

            # traverse in second pass and  get all subdirectories
            chunk_stack = []
            volume_dict = {}
            for position in directory_stack:
                f.seek(position)
                raw = f.read(52)
                directory_chunk = self.main_directory_structure.parse(raw)

                for ii in range(directory_chunk.num_entries):
                    raw = f.read(44)
                    chunk = self.sub_directory_structure.parse(raw)
                    volume_string = '{}_{}_{}'.format(chunk.patient_id,
                                                      chunk.study_id,
                                                      chunk.series_id)
                    if volume_string not in volume_dict.keys():
                        volume_dict[volume_string] = chunk.slice_id / 2
                    elif chunk.slice_id / 2 > volume_dict[volume_string]:
                        volume_dict[volume_string] = chunk.slice_id / 2

                    if chunk.start > chunk.pos:
                        chunk_stack.append([chunk.start, chunk.size])

            # initalise dict to hold all the image volumes
            volume_array_dict = {}
            for volume, num_slices in volume_dict.items():
                if num_slices > 0:
                    volume_array_dict[volume] = [0] * int(num_slices)

            # traverse all chunks and extract slices
            for start, pos in chunk_stack:
                f.seek(start)
                raw = f.read(60)
                chunk = self.chunk_structure.parse(raw)

                if chunk.type == 1073741824:  # image data
                    raw = f.read(20)
                    image_data = self.image_structure.parse(raw)

                    if chunk.ind == 0:  # fundus data
                        pass
                        # raw_volume = [struct.unpack('H', f.read(2))[0] for pixel in range(height*width)]
                        # image = np.array(raw_volume).reshape(height,width)
                        # plt.imshow(image)
                    elif chunk.ind == 1:  # oct data
                        all_bits = [
                            f.read(2) for i in range(image_data.height *
                                                     image_data.width)
                        ]
                        raw_volume = list(map(self.read_custom_float,
                                              all_bits))
                        image = np.array(raw_volume).reshape(
                            image_data.width, image_data.height)
                        image = 256 * pow(image, 1.0 / 2.4)
                        volume_string = '{}_{}_{}'.format(
                            chunk.patient_id, chunk.study_id, chunk.series_id)
                        if volume_string in volume_array_dict.keys():
                            volume_array_dict[volume_string][
                                int(chunk.slice_id / 2) - 1] = image
                        else:
                            print('Failed to save image data for volume {}'.
                                  format(volume_string))

            oct_volumes = []
            for key, volume in volume_array_dict.items():
                oct_volumes.append(
                    OCTVolumeWithMetaData(volume=volume, patient_id=key))

        return oct_volumes
Ejemplo n.º 8
0
    def read_oct_volume(self):
        """ Reads OCT data.

            Returns:
                obj:OCTVolumeWithMetaData
        """
        with open(self.filepath, 'rb') as f:
            raw = f.read(36)
            header = self.header_structure.parse(raw)

            raw = f.read(52)
            main_directory = self.main_directory_structure.parse(raw)

            # traverse list of main directories in first pass
            directory_stack = []

            current = main_directory.current
            while current != 0:
                directory_stack.append(current)
                f.seek(current)
                raw = f.read(52)
                directory_chunk = self.main_directory_structure.parse(raw)
                current = directory_chunk.prev

            # traverse in second pass and  get all subdirectories
            chunk_stack = []
            volume_dict = {}
            for position in directory_stack:
                f.seek(position)
                raw = f.read(52)
                directory_chunk = self.main_directory_structure.parse(raw)

                for ii in range(directory_chunk.num_entries):
                    raw = f.read(44)
                    chunk = self.sub_directory_structure.parse(raw)
                    volume_string = '{}_{}_{}'.format(chunk.patient_id,
                                                      chunk.study_id,
                                                      chunk.series_id)
                    if volume_string not in volume_dict.keys():
                        volume_dict[volume_string] = chunk.slice_id / 2
                    elif chunk.slice_id / 2 > volume_dict[volume_string]:
                        volume_dict[volume_string] = chunk.slice_id / 2

                    if chunk.start > chunk.pos:
                        chunk_stack.append([chunk.start, chunk.size])

            # initalise dict to hold all the image volumes
            volume_array_dict = {}
            volume_array_dict_additional = {
            }  # for storage of slices not caught by extraction
            for volume, num_slices in volume_dict.items():
                if num_slices > 0:
                    # num_slices + 1 here due to evidence that a slice was being missed off the end in extraction
                    volume_array_dict[volume] = [0] * int(num_slices + 1)

            # traverse all chunks and extract slices
            for start, pos in chunk_stack:
                f.seek(start)
                raw = f.read(60)
                chunk = self.chunk_structure.parse(raw)

                if chunk.type == 11:  # laterality data
                    raw = f.read(20)
                    try:
                        laterality_data = self.lat_structure.parse(raw)
                        if laterality_data.laterality == 82:
                            self.laterality = 'R'
                        elif laterality_data.laterality == 76:
                            self.laterality = 'L'
                    except:
                        self.laterality = None

                if chunk.type == 1073741824:  # image data
                    raw = f.read(20)
                    image_data = self.image_structure.parse(raw)

                    if chunk.ind == 1:  # oct data
                        all_bits = [
                            f.read(2) for i in range(image_data.height *
                                                     image_data.width)
                        ]
                        raw_volume = list(map(self.read_custom_float,
                                              all_bits))
                        image = np.array(raw_volume).reshape(
                            image_data.width, image_data.height)
                        image = 256 * pow(image, 1.0 / 2.4)
                        volume_string = '{}_{}_{}'.format(
                            chunk.patient_id, chunk.study_id, chunk.series_id)
                        if volume_string in volume_array_dict.keys():
                            volume_array_dict[volume_string][
                                int(chunk.slice_id / 2) - 1] = image
                        else:
                            # try to capture these additional images
                            if volume_string in volume_array_dict_additional.keys(
                            ):
                                volume_array_dict_additional[
                                    volume_string].append(image)
                            else:
                                volume_array_dict_additional[volume_string] = [
                                    image
                                ]
                            #print('Failed to save image data for volume {}'.format(volume_string))

            oct_volumes = []
            for key, volume in volume_array_dict.items():
                oct_volumes.append(
                    OCTVolumeWithMetaData(volume=volume,
                                          patient_id=key,
                                          laterality=self.laterality))
            for key, volume in volume_array_dict_additional.items():
                oct_volumes.append(
                    OCTVolumeWithMetaData(volume=volume,
                                          patient_id=key,
                                          laterality=self.laterality))

        return oct_volumes