Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: support pickle and deepcopy for images #658

Merged
merged 1 commit into from
May 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion ants/core/ants_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -565,7 +565,26 @@ def __repr__(self):
'\t {:<10} : {}\n'.format('Origin', tuple([round(o,4) for o in self.origin]))+\
'\t {:<10} : {}\n'.format('Direction', np.round(self.direction.flatten(),4))
return s


def __getstate__(self):
"""
import ants
import pickle
import numpy as np
from copy import deepcopy
img = ants.image_read( ants.get_ants_data("r16"))
img_pickled = pickle.dumps(img)
img2 = pickle.loads(img_pickled)
img3 = deepcopy(img)
img += 10
print(img.mean(), img3.mean())
"""
return self.numpy(), self.origin, self.spacing, self.direction, self.has_components, self.is_rgb

def __setstate__(self, state):
data, origin, spacing, direction, has_components, is_rgb = state
image = ants.from_numpy(np.copy(data), origin=origin, spacing=spacing, direction=direction, has_components=has_components, is_rgb=is_rgb)
self.__dict__ = image.__dict__

def copy_image_info(reference, target):
"""
Expand Down
17 changes: 17 additions & 0 deletions tests/test_core_ants_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,23 @@ def test_allclose(self):
self.assertTrue(ants.allclose(img,img2))
self.assertTrue(ants.allclose(img*6.9, img2*6.9))
self.assertTrue(not ants.allclose(img, img2*6.9))

def test_pickle(self):
import ants
import pickle
img = ants.image_read( ants.get_ants_data("mni"))
img_pickled = pickle.dumps(img)
img2 = pickle.loads(img_pickled)

self.assertTrue(ants.allclose(img, img2))
self.assertTrue(ants.image_physical_space_consistency(img, img2))

img = ants.image_read( ants.get_ants_data("r16"))
img_pickled = pickle.dumps(img)
img2 = pickle.loads(img_pickled)

self.assertTrue(ants.allclose(img, img2))
self.assertTrue(ants.image_physical_space_consistency(img, img2))


if __name__ == '__main__':
Expand Down