def read_png_images(path_prefix: str, bbox: BoundingBox, volume_offset: tuple = (0, 0, 0), voxel_size: tuple = (1, 1, 1), digit_num: int = 5, dtype: np.dtype = np.uint8): chunk = Chunk.from_bbox( bbox, dtype=dtype, pattern='zero', voxel_size=voxel_size ) assert len(bbox.minpt) == 3 assert len(volume_offset) == 3 for z in tqdm( range(bbox.minpt[0], bbox.maxpt[0]) ): file_name = f'{path_prefix}{z:0>{digit_num}d}.png' file_name = path.expanduser(file_name) if path.exists(file_name): with open(file_name, "rb") as f: img = pyspng.load(f.read()) img = np.expand_dims(img, axis=0) img_chunk = Chunk( img, voxel_offset=( z+volume_offset[0], volume_offset[1], volume_offset[2]), voxel_size=voxel_size ) chunk.blend(img_chunk) else: logging.warning(f'image file do not exist: {file_name}') return chunk
def _load_raw_image(self, raw_idx): fname = self._image_fnames[raw_idx] with self._open_file(fname) as f: if pyspng is not None and self._file_ext(fname) == '.png': image = pyspng.load(f.read()) else: image = np.array(PIL.Image.open(f)) if image.ndim == 2: image = image[:, :, np.newaxis] # HW => HWC image = image.transpose(2, 0, 1) # HWC => CHW return image
def benchmark(title='', content='noise', width=1024, height=1024, compress_level=0, loader='spng', num_repeats=10, num_calls=10): if content == 'noise': img = np.random.randint(0, 256, size=[height, width, 3], dtype=np.uint8) if content == 'gradient': x, y, _c = np.mgrid[:height, :width, :1] img = np.concatenate([y * 255 / height, x * 255 / width, x * 0], axis=2).astype(np.uint8) stream = io.BytesIO() PIL.Image.fromarray(img, 'RGB').save(stream, format='png', compress_level=compress_level) bytes = stream.getvalue() lowest_ms = float('inf') for _repeat_idx in range(num_repeats): start_time = time.time() for _call_idx in range(num_calls): if loader == 'pil': out = np.asarray(PIL.Image.open(io.BytesIO(bytes))) if loader == 'spng': out = pyspng.load(bytes) cur_ms = (time.time() - start_time) * 1e3 lowest_ms = min(lowest_ms, cur_ms) print(f'{title} {lowest_ms:.2f}ms') assert np.all(out == img)
def decode_png(bytestring: bytes, shape, dtype): img = pyspng.load(bytestring).reshape(-1) img = img.astype(dtype, copy=False) return img.reshape(shape, order='F')