def get_image(self): if self.is_contiguous: if self.planar_config==1: start = self.strip_offsets[0] + self.sample_offset stop = self.strip_offsets[-1] + self.strip_nbytes[-1] image =self.ifd.tiff.data[start:stop].view(dtype=self.pixel_dtype) image = image[self.sample_name].reshape (self.shape) return image else: if self.sample_index is None: start = self.strip_offsets[0] else: start = self.strip_offsets[0] + self.sample_index * self.bytes_per_sample_image stop = start + self.bytes_per_sample_image image = self.ifd.tiff.data[start:stop] image = image.view(dtype=self.dtype).reshape(self.shape) return image else: image = numpy.empty((self.bytes_per_sample_image,), dtype=numpy.uint8) offset = 0 for strip_index in range (len (self.strip_offsets)): start = self.strip_offsets[strip_index] stop = start + self.strip_nbytes[strip_index] if self.compression==1: strip = self.ifd.tiff.data[start:stop] else: compressed_strip = self.ifd.tiff.data[start:stop] if self.compression==5: # lzw strip = tif_lzw.decode(compressed_strip, self.uncompressed_bytes_per_strip) else: raise NotImplementedError (`self.compression`) image[offset:offset + strip.nbytes] = strip offset += strip.nbytes image = image.view(dtype=self.dtype).reshape(self.shape) return image
def get_row(self, index, subindex=None): if index < 0: index += self.shape[0] if index > self.shape[0] or index < 0: raise IndexError('Row index %r out of bounds [0,%r]' % (index, self.shape[0] - 1)) if self.planar_config == 1: # RGBRGB.. strip_index, row_index = divmod(index, self.rows_per_strip) else: # RR..GG..BB.. index2 = self.sample_index * self.shape[0] + index strip_index, row_index = divmod(index2, self.rows_per_strip) start = self.strip_offsets[strip_index] stop = start + self.strip_nbytes[strip_index] if self.compression == 1: strip = self.ifd.tiff.data[start:stop] else: compressed_strip = self.ifd.tiff.data[start:stop] if self.compression == 5: # lzw strip = tif_lzw.decode(compressed_strip, self.uncompressed_bytes_per_strip) else: raise NotImplementedError( ` self.compression `) start = row_index * self.bytes_per_sample_row + self.sample_offset stop = start + self.bytes_per_sample_row + self.sample_offset if isinstance(subindex, tuple): if len(subindex) == 1: subindex = subindex[0] if self.planar_config == 1: if isinstance(subindex, (int, long)): start = start + subindex * self.bytes_per_pixel stop = start + self.bytes_per_pixel return strip[start:stop].view( dtype=self.pixel_dtype)[self.sample_name][0] row = strip[start:stop].view( dtype=self.pixel_dtype)[self.sample_name] if not row.size: print self.get_topology() else: row = strip[start:stop].view(dtype=self.dtype) if subindex is not None: return row[subindex] return row
def get_image(self): if self.is_contiguous: if self.planar_config == 1: start = self.strip_offsets[0] + self.sample_offset stop = self.strip_offsets[-1] + self.strip_nbytes[-1] image = self.ifd.tiff.data[start:stop].view( dtype=self.pixel_dtype) image = image[self.sample_name].reshape(self.shape) return image else: if self.sample_index is None: start = self.strip_offsets[0] else: start = self.strip_offsets[ 0] + self.sample_index * self.bytes_per_sample_image stop = start + self.bytes_per_sample_image image = self.ifd.tiff.data[start:stop] image = image.view(dtype=self.dtype).reshape(self.shape) return image else: image = numpy.empty((self.bytes_per_sample_image, ), dtype=numpy.uint8) offset = 0 for strip_index in range(len(self.strip_offsets)): start = self.strip_offsets[strip_index] stop = start + self.strip_nbytes[strip_index] if self.compression == 1: strip = self.ifd.tiff.data[start:stop] else: compressed_strip = self.ifd.tiff.data[start:stop] if self.compression == 5: # lzw strip = tif_lzw.decode( compressed_strip, self.uncompressed_bytes_per_strip) else: raise NotImplementedError(repr(self.compression)) target = image[offset:offset + strip.nbytes] if target.nbytes < strip.nbytes: print( '%s.get_image warning: tiff data contains %s extra bytes (compression=%r) that are ignored' % (self.__class__.__name__, strip.nbytes - target.nbytes, self.compression)) image[offset:offset + strip.nbytes] = strip[:target.nbytes] offset += strip.nbytes image = image.view(dtype=self.dtype).reshape(self.shape) return image
def get_row(self, index, subindex=None): if index < 0: index += self.shape[0] if index > self.shape[0] or index < 0: raise IndexError("Row index %r out of bounds [0,%r]" % (index, self.shape[0] - 1)) if self.planar_config == 1: # RGBRGB.. strip_index, row_index = divmod(index, self.rows_per_strip) else: # RR..GG..BB.. index2 = self.sample_index * self.shape[0] + index strip_index, row_index = divmod(index2, self.rows_per_strip) start = self.strip_offsets[strip_index] stop = start + self.strip_nbytes[strip_index] if self.compression == 1: strip = self.ifd.tiff.data[start:stop] else: compressed_strip = self.ifd.tiff.data[start:stop] if self.compression == 5: # lzw strip = tif_lzw.decode(compressed_strip, self.uncompressed_bytes_per_strip) else: raise NotImplementedError(repr(self.compression)) start = row_index * self.bytes_per_sample_row + self.sample_offset stop = start + self.bytes_per_sample_row + self.sample_offset if isinstance(subindex, tuple): if len(subindex) == 1: subindex = subindex[0] if self.planar_config == 1: if isinstance(subindex, int): start = start + subindex * self.bytes_per_pixel stop = start + self.bytes_per_pixel return strip[start:stop].view(dtype=self.pixel_dtype)[self.sample_name][0] row = strip[start:stop].view(dtype=self.pixel_dtype)[self.sample_name] if not row.size: print(self.get_topology()) else: row = strip[start:stop].view(dtype=self.dtype) if subindex is not None: return row[subindex] return row
def get_image(self): if self.is_contiguous: if self.planar_config == 1: start = self.strip_offsets[0] + self.sample_offset stop = self.strip_offsets[-1] + self.strip_nbytes[-1] image = self.ifd.tiff.data[start:stop].view(dtype=self.pixel_dtype) image = image[self.sample_name].reshape(self.shape) return image else: if self.sample_index is None: start = self.strip_offsets[0] else: start = self.strip_offsets[0] + self.sample_index * self.bytes_per_sample_image stop = start + self.bytes_per_sample_image image = self.ifd.tiff.data[start:stop] image = image.view(dtype=self.dtype).reshape(self.shape) return image else: image = numpy.empty((self.bytes_per_sample_image,), dtype=numpy.uint8) offset = 0 for strip_index in range(len(self.strip_offsets)): start = self.strip_offsets[strip_index] stop = start + self.strip_nbytes[strip_index] if self.compression == 1: strip = self.ifd.tiff.data[start:stop] else: compressed_strip = self.ifd.tiff.data[start:stop] if self.compression == 5: # lzw strip = tif_lzw.decode(compressed_strip, self.uncompressed_bytes_per_strip) else: raise NotImplementedError(` self.compression `) target = image[offset : offset + strip.nbytes] if target.nbytes < strip.nbytes: print "%s.get_image warning: tiff data contains %s extra bytes (compression=%r) that are ignored" % ( self.__class__.__name__, strip.nbytes - target.nbytes, self.compression, ) image[offset : offset + strip.nbytes] = strip[: target.nbytes] offset += strip.nbytes image = image.view(dtype=self.dtype).reshape(self.shape) return image
def get_samples(self, subfile_type=0, verbose=False): """ Return samples and sample names. Parameters ---------- subfile_type : {0, 1} Specify subfile type. Subfile type 1 corresponds to reduced resolution image. verbose : bool When True the print out information about samples Returns ------- samples : list List of numpy.memmap arrays of samples sample_names : list List of the corresponding sample names """ l = [] i = 0 step = 0 can_return_memmap = True ifd_lst = [ifd for ifd in self.IFD if ifd.get_value('NewSubfileType')==subfile_type] depth = len(ifd_lst) full_l = [] for ifd in ifd_lst: if not ifd.is_contiguous(): raise NotImplementedError('none contiguous strips') strip_offsets = ifd.get_value('StripOffsets') strip_nbytes = ifd.get_value('StripByteCounts') l.append((strip_offsets[0], strip_offsets[-1]+strip_nbytes[-1])) for off, nb in zip (strip_offsets, strip_nbytes): full_l.append ((off, off+nb)) if i==0: compression = ifd.get_value('Compression') if compression!=1: can_return_memmap = False #raise ValueError('Unable to get contiguous samples from compressed data (compression=%s)' % (compression)) width = ifd.get_value('ImageWidth') length = ifd.get_value('ImageLength') samples_per_pixel = ifd.get_value('SamplesPerPixel') planar_config = ifd.get_value('PlanarConfiguration') bits_per_sample = ifd.get_value('BitsPerSample') sample_format = ifd.get_value('SampleFormat')[0] photometric_interpretation = ifd.get_value('PhotometricInterpretation') if self.is_lsm or not isinstance(strip_offsets, numpy.ndarray): strips_per_image = 1 else: strips_per_image = len(strip_offsets) format = sample_format_map.get(sample_format) if format is None: print 'Warning(TIFFfile.get_samples): unsupported sample_format=%s is mapped to uint' % (sample_format) format = 'uint' dtype_lst = [] bits_per_pixel = 0 for j in range(samples_per_pixel): bits = bits_per_sample[j] bits_per_pixel += bits dtype = getattr (self.dtypes, '%s%s' % (format, bits)) dtype_lst.append(dtype) bytes_per_pixel = bits_per_pixel // 8 assert 8*bytes_per_pixel == bits_per_pixel,`bits_per_pixel` bytes_per_row = width * bytes_per_pixel strip_length = l[-1][1] - l[-1][0] strip_length_str = bytes2str(strip_length) bytes_per_image = length * bytes_per_row rows_per_strip = bytes_per_image // (bytes_per_row * strips_per_image) if bytes_per_image % (bytes_per_row * strips_per_image): rows_per_strip += 1 assert rows_per_strip == ifd.get_value('RowsPerStrip', rows_per_strip), `rows_per_strip, ifd.get_value('RowsPerStrip'), bytes_per_image, bytes_per_row, strips_per_image, self.filename` else: assert width == ifd.get_value('ImageWidth', width), `width, ifd.get_value('ImageWidth')` assert length == ifd.get_value('ImageLength', length),` length, ifd.get_value('ImageLength')` #assert samples_per_pixel == ifd.get('SamplesPerPixel').value, `samples_per_pixel, ifd.get('SamplesPerPixel').value` assert planar_config == ifd.get_value('PlanarConfiguration', planar_config) if can_return_memmap: assert strip_length == l[-1][1] - l[-1][0], `strip_length, l[-1][1] - l[-1][0]` else: strip_length = max (strip_length, l[-1][1] - l[-1][0]) strip_length_str = ' < ' + bytes2str(strip_length) assert (bits_per_sample == ifd.get_value('BitsPerSample', bits_per_sample)).all(),`bits_per_sample, ifd.get_value('BitsPerSample')` if i>0: if i==1: step = l[-1][0] - l[-2][1] assert step>=0,`step, l[-2], l[-1]` else: if step != l[-1][0] - l[-2][1]: can_return_memmap = False #assert step == l[-1][0] - l[-2][1],`step, l[-2], l[-1], (l[-1][0] - l[-2][1]), i` i += 1 if verbose: bytes_per_image_str = bytes2str(bytes_per_image) print ''' width : %(width)s length : %(length)s depth : %(depth)s sample_format : %(format)s samples_per_pixel : %(samples_per_pixel)s planar_config : %(planar_config)s bits_per_sample : %(bits_per_sample)s bits_per_pixel : %(bits_per_pixel)s bytes_per_pixel : %(bytes_per_pixel)s bytes_per_row : %(bytes_per_row)s bytes_per_image : %(bytes_per_image_str)s strips_per_image : %(strips_per_image)s rows_per_strip : %(rows_per_strip)s strip_length : %(strip_length_str)s ''' % (locals ()) if photometric_interpretation==2: assert samples_per_pixel==3, `samples_per_pixel` sample_names = ['red', 'green', 'blue'] else: sample_names = ['sample%s' % (j) for j in range (samples_per_pixel)] depth = i if not can_return_memmap: if planar_config==1: if samples_per_pixel==1: i = 0 arr = numpy.empty(depth * bytes_per_image, dtype=self.dtypes.uint8) bytes_per_strip = rows_per_strip * bytes_per_row for start, end in full_l: #sys.stdout.write ("%s:%s," % (start, end)); sys.stdout.flush () if compression==1: # none d = self.data[start:end] elif compression==5: # lzw d = self.data[start:end] d = tif_lzw.decode(d, bytes_per_strip) arr[i:i+d.nbytes] = d i += d.nbytes arr = arr.view(dtype=dtype_lst[0]).reshape((depth, length, width)) return [arr], sample_names else: i = 0 arr = numpy.empty(depth * bytes_per_image, dtype=self.dtypes.uint8) bytes_per_strip = rows_per_strip * bytes_per_row for start, end in full_l: sys.stdout.write ("%s:%s," % (start, end)); sys.stdout.flush () if compression==1: # none d = self.data[start:end] elif compression==5: # lzw d = self.data[start:end] d = tif_lzw.decode(d, bytes_per_strip) arr[i:i+d.nbytes] = d i += d.nbytes dt = numpy.dtype(dict(names=sample_names, formats=dtype_lst)) arr = arr.view(dtype=dt).reshape((depth, length, width)) return [arr[n] for n in arr.dtype.names], arr.dtype.names raise NotImplementedError(`depth, bytes_per_image, samples_per_pixel`) else: raise NotImplementedError (`planar_config`) start = l[0][0] end = l[-1][1] if start > step: arr = self.data[start - step: end].reshape((depth, strip_length + step)) k = step elif end <= self.data.size - step: arr = self.data[start: end+step].reshape((depth, strip_length + step)) k = 0 else: raise NotImplementedError (`start, end, step`) sys.stdout.flush() if planar_config==2: if self.is_lsm: # LSM510: one strip per image plane channel if subfile_type==0: sample_names = self.lsminfo.get('data channel name') elif subfile_type==1: sample_names = ['red', 'green', 'blue'] assert samples_per_pixel==3,`samples_per_pixel` else: raise NotImplementedError (`subfile_type`) samples = [] for j in range(samples_per_pixel): bytes = bits_per_sample[j] // 8 * width * length tmp = arr[:,k:k+bytes] tmp = tmp.view(dtype=dtype_lst[j]) tmp = tmp.reshape((depth, length, width)) samples.append(tmp) k += bytes return samples, sample_names raise NotImplementedError (`planar_config, self.is_lsm`) elif planar_config==1: samples = [] bytes = sum(bits_per_sample[:samples_per_pixel]) // 8 * width * length bytes_per_sample = bits_per_sample // 8 for j in range(samples_per_pixel): i0 = k+j*bytes_per_sample[j] #print j, i0, i0+bytes, samples_per_pixel, arr.shape tmp = arr[:,i0:i0+bytes:samples_per_pixel] tmp = numpy.array(tmp.reshape((tmp.size,))) tmp = tmp.view(dtype=dtype_lst[j]) tmp = tmp.reshape((depth, length, width)) samples.append(tmp) #k += bytes return samples, sample_names else: raise NotImplementedError (`planar_config`)
def get_samples(self, subfile_type=0, verbose=False): """ Return samples and sample names. Parameters ---------- subfile_type : {0, 1} Specify subfile type. Subfile type 1 corresponds to reduced resolution image. verbose : bool When True the print out information about samples Returns ------- samples : list List of numpy.memmap arrays of samples sample_names : list List of the corresponding sample names """ l = [] i = 0 step = 0 can_return_memmap = True ifd_lst = [ ifd for ifd in self.IFD if ifd.get_value('NewSubfileType') == subfile_type ] depth = len(ifd_lst) full_l = [] for ifd in ifd_lst: if not ifd.is_contiguous(): raise NotImplementedError('none contiguous strips') strip_offsets = ifd.get_value('StripOffsets') strip_nbytes = ifd.get_value('StripByteCounts') l.append((strip_offsets[0], strip_offsets[-1] + strip_nbytes[-1])) for off, nb in zip(strip_offsets, strip_nbytes): full_l.append((off, off + nb)) if i == 0: compression = ifd.get_value('Compression') if compression != 1: can_return_memmap = False #raise ValueError('Unable to get contiguous samples from compressed data (compression=%s)' % (compression)) width = ifd.get_value('ImageWidth') length = ifd.get_value('ImageLength') samples_per_pixel = ifd.get_value('SamplesPerPixel') planar_config = ifd.get_value('PlanarConfiguration') bits_per_sample = ifd.get_value('BitsPerSample') sample_format = ifd.get_value('SampleFormat')[0] photometric_interpretation = ifd.get_value( 'PhotometricInterpretation') if self.is_lsm or not isinstance(strip_offsets, numpy.ndarray): strips_per_image = 1 else: strips_per_image = len(strip_offsets) format = sample_format_map.get(sample_format) if format is None: print 'Warning(TIFFfile.get_samples): unsupported sample_format=%s is mapped to uint' % ( sample_format) format = 'uint' dtype_lst = [] bits_per_pixel = 0 for j in range(samples_per_pixel): bits = bits_per_sample[j] bits_per_pixel += bits dtype = getattr(self.dtypes, '%s%s' % (format, bits)) dtype_lst.append(dtype) bytes_per_pixel = bits_per_pixel // 8 assert 8 * bytes_per_pixel == bits_per_pixel, ` bits_per_pixel ` bytes_per_row = width * bytes_per_pixel strip_length = l[-1][1] - l[-1][0] strip_length_str = bytes2str(strip_length) bytes_per_image = length * bytes_per_row rows_per_strip = bytes_per_image // (bytes_per_row * strips_per_image) if bytes_per_image % (bytes_per_row * strips_per_image): rows_per_strip += 1 assert rows_per_strip == ifd.get_value( 'RowsPerStrip', rows_per_strip ), ` rows_per_strip, ifd.get_value( 'RowsPerStrip' ), bytes_per_image, bytes_per_row, strips_per_image, self.filename ` else: assert width == ifd.get_value( 'ImageWidth', width), ` width, ifd.get_value('ImageWidth') ` assert length == ifd.get_value( 'ImageLength', length), ` length, ifd.get_value('ImageLength') ` #assert samples_per_pixel == ifd.get('SamplesPerPixel').value, `samples_per_pixel, ifd.get('SamplesPerPixel').value` assert planar_config == ifd.get_value('PlanarConfiguration', planar_config) if can_return_memmap: assert strip_length == l[-1][1] - l[-1][ 0], ` strip_length, l[-1][1] - l[-1][0] ` else: strip_length = max(strip_length, l[-1][1] - l[-1][0]) strip_length_str = ' < ' + bytes2str(strip_length) assert (bits_per_sample == ifd.get_value( 'BitsPerSample', bits_per_sample)).all(), ` bits_per_sample, ifd.get_value( 'BitsPerSample') ` if i > 0: if i == 1: step = l[-1][0] - l[-2][1] assert step >= 0, ` step, l[-2], l[-1] ` else: if step != l[-1][0] - l[-2][1]: can_return_memmap = False #assert step == l[-1][0] - l[-2][1],`step, l[-2], l[-1], (l[-1][0] - l[-2][1]), i` i += 1 if verbose: bytes_per_image_str = bytes2str(bytes_per_image) print ''' width : %(width)s length : %(length)s depth : %(depth)s sample_format : %(format)s samples_per_pixel : %(samples_per_pixel)s planar_config : %(planar_config)s bits_per_sample : %(bits_per_sample)s bits_per_pixel : %(bits_per_pixel)s bytes_per_pixel : %(bytes_per_pixel)s bytes_per_row : %(bytes_per_row)s bytes_per_image : %(bytes_per_image_str)s strips_per_image : %(strips_per_image)s rows_per_strip : %(rows_per_strip)s strip_length : %(strip_length_str)s ''' % (locals()) if photometric_interpretation == 2: assert samples_per_pixel == 3, ` samples_per_pixel ` sample_names = ['red', 'green', 'blue'] else: sample_names = ['sample%s' % (j) for j in range(samples_per_pixel)] depth = i if not can_return_memmap: if planar_config == 1: if samples_per_pixel == 1: i = 0 arr = numpy.empty(depth * bytes_per_image, dtype=self.dtypes.uint8) bytes_per_strip = rows_per_strip * bytes_per_row for start, end in full_l: #sys.stdout.write ("%s:%s," % (start, end)); sys.stdout.flush () if compression == 1: # none d = self.data[start:end] elif compression == 5: # lzw d = self.data[start:end] d = tif_lzw.decode(d, bytes_per_strip) arr[i:i + d.nbytes] = d i += d.nbytes arr = arr.view(dtype=dtype_lst[0]).reshape( (depth, length, width)) return [arr], sample_names else: i = 0 arr = numpy.empty(depth * bytes_per_image, dtype=self.dtypes.uint8) bytes_per_strip = rows_per_strip * bytes_per_row for start, end in full_l: sys.stdout.write("%s:%s," % (start, end)) sys.stdout.flush() if compression == 1: # none d = self.data[start:end] elif compression == 5: # lzw d = self.data[start:end] d = tif_lzw.decode(d, bytes_per_strip) arr[i:i + d.nbytes] = d i += d.nbytes dt = numpy.dtype( dict(names=sample_names, formats=dtype_lst)) arr = arr.view(dtype=dt).reshape((depth, length, width)) return [arr[n] for n in arr.dtype.names], arr.dtype.names raise NotImplementedError( ` depth, bytes_per_image, samples_per_pixel `) else: raise NotImplementedError( ` planar_config `) start = l[0][0] end = l[-1][1] if start > step: arr = self.data[start - step:end].reshape( (depth, strip_length + step)) k = step elif end <= self.data.size - step: arr = self.data[start:end + step].reshape( (depth, strip_length + step)) k = 0 else: raise NotImplementedError( ` start, end, step `) sys.stdout.flush() if planar_config == 2: if self.is_lsm: # LSM510: one strip per image plane channel if subfile_type == 0: sample_names = self.lsminfo.get('data channel name') elif subfile_type == 1: sample_names = ['red', 'green', 'blue'] assert samples_per_pixel == 3, ` samples_per_pixel ` else: raise NotImplementedError( ` subfile_type `) samples = [] for j in range(samples_per_pixel): bytes = bits_per_sample[j] // 8 * width * length tmp = arr[:, k:k + bytes] tmp = tmp.view(dtype=dtype_lst[j]) tmp = tmp.reshape((depth, length, width)) samples.append(tmp) k += bytes return samples, sample_names raise NotImplementedError( ` planar_config, self.is_lsm `) elif planar_config == 1: samples = [] bytes = sum( bits_per_sample[:samples_per_pixel]) // 8 * width * length bytes_per_sample = bits_per_sample // 8 for j in range(samples_per_pixel): i0 = k + j * bytes_per_sample[j] #print j, i0, i0+bytes, samples_per_pixel, arr.shape tmp = arr[:, i0:i0 + bytes:samples_per_pixel] tmp = numpy.array(tmp.reshape((tmp.size, ))) tmp = tmp.view(dtype=dtype_lst[j]) tmp = tmp.reshape((depth, length, width)) samples.append(tmp) #k += bytes return samples, sample_names else: raise NotImplementedError( ` planar_config `)