def data(self, raw=False, bgr2rgb=True, resize=True, order=1):
"""Read image data from file and return as numpy array."""
self._fh.seek(self.data_offset)
if raw:
return self._fh.read(self.data_size)
elif self.compression and self.compression < RAW_COMPRESSION_VALUE:
if self.compression not in DECOMPRESS:
raise ValueError("compression unknown or not supported")
# TODO: iotest this
data = self._fh.read(self.data_size)
data = DECOMPRESS[self.compression](data)
if self.compression == 2:
# LZW
data = numpy.fromstring(data, self.dtype)
else:
dtype = numpy.dtype(self.dtype)
data = self._fh.read_array(dtype, self.data_size // dtype.itemsize)
data = data.reshape(self.stored_shape)
if self.stored_shape == self.shape or not resize:
if bgr2rgb and self.stored_shape[-1] in (3, 4):
tmp = data[..., 0].copy()
data[..., 0] = data[..., 2]
data[..., 2] = tmp
return data
# sub / supersampling
factors = [j / i for i, j in zip(self.stored_shape, self.shape)]
factors = [(1.0 if abs(1.0-f) < 0.0001 else f) for f in factors]
shape = list(self.stored_shape)
# remove leading dimensions with factor 1.0 for speed
for factor in factors:
if factor != 1.0:
break
shape = shape[1:]
factors = factors[1:]
data.shape = shape
# resize RGB components separately for speed
if shape[-1] in (3, 4) and factors[-1] == 1.0:
factors = factors[:-1]
old = data
data = numpy.empty(self.shape, self.dtype[-2:])
for i in range(shape[-1]):
j = {0: 2, 1: 1, 2: 0, 3: 3}[i] if bgr2rgb else i
data[..., i] = zoom(old[..., j], zoom=factors, order=order)
else:
data = zoom(data, zoom=factors, order=order)
data.shape = self.shape
return data
评论列表
文章目录