From e702320dc7f4f3047bda04b6be6b2d2c392aabe9 Mon Sep 17 00:00:00 2001 From: William Silversmith Date: Tue, 23 Jul 2024 02:55:30 -0400 Subject: [PATCH] feat+refactor: add astype function --- crackle/__init__.py | 1 + crackle/array.py | 6 +++++- crackle/operations.py | 13 +++++++++++-- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/crackle/__init__.py b/crackle/__init__.py index 328f1f0..67e8b2b 100644 --- a/crackle/__init__.py +++ b/crackle/__init__.py @@ -48,6 +48,7 @@ header, contains, crack_codes, num_labels, ) from .operations import ( + astype, remap, refit, renumber, min, max, zstack, zsplit, diff --git a/crackle/array.py b/crackle/array.py index c6c7dde..3a5f639 100644 --- a/crackle/array.py +++ b/crackle/array.py @@ -8,6 +8,7 @@ components, ) from .operations import ( + astype, refit, renumber, zstack, zsplit, @@ -70,9 +71,12 @@ def max(self): def remap(self, buf, mapping, preserve_missing_labels=False): return CrackleArray(remap(buf, mapping, preserve_missing_labels)) - def refit(self) -> bytes: + def refit(self): return CrackleArray(refit(self.binary)) + def astype(self, dtype): + return CrackleArray(astype(self.binary, dtype)) + def renumber(self, start:int = 0) -> bytes: return CrackleArray(renumber(self.binary, start)) diff --git a/crackle/operations.py b/crackle/operations.py index 3047dad..ccff140 100644 --- a/crackle/operations.py +++ b/crackle/operations.py @@ -110,20 +110,29 @@ def remap(binary:bytes, mapping:dict, preserve_missing_labels:bool = False): binary[offset:offset+uniq_bytes] = list(all_labels.view(np.uint8)) return bytes(binary) -def refit(binary:bytes) -> bytes: +def astype(binary:bytes, dtype) -> bytes: """ Change the rendered dtype to the smallest dtype needed to render the image without loss of precision. """ head = header(binary) - dtype = fastremap.fit_dtype(head.dtype, max(binary)) head.data_width = np.dtype(dtype).itemsize return b''.join([ head.tobytes(), binary[CrackleHeader.HEADER_BYTES:] ]) +def refit(binary:bytes) -> bytes: + """ + Change the rendered dtype to the smallest + dtype needed to render the image without + loss of precision. + """ + head = header(binary) + dtype = fastremap.fit_dtype(head.dtype, max(binary)) + return astype(binary, dtype) + def renumber(binary:bytes, start=0) -> Tuple[bytes, dict]: """ Renumber the array and resize the data type