Created
March 21, 2019 20:13
-
-
Save arokem/280cb41ba67be7282b3f2d445e50e0c3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"execution_count": 1, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"import nibabel as nib\n", | |
"import numpy as np\n", | |
"import s3fs\n", | |
"from io import BytesIO\n", | |
"import gzip\n", | |
"\n", | |
"data = np.random.randn(100, 100, 100)\n", | |
"orig_img = nib.Nifti1Image(data, np.eye(4))\n", | |
"\n", | |
"fname = 'bucket_name/fname.nii.gz'" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 2, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"\n", | |
"def s3fs_nifti_write(img, fname):\n", | |
" fs = s3fs.S3FileSystem()\n", | |
" bio = BytesIO()\n", | |
" file_map = img.make_file_map({'image': bio, 'header': bio})\n", | |
" img.to_file_map(file_map)\n", | |
" data = gzip.compress(bio.getvalue())\n", | |
"\n", | |
" with fs.open(fname, 'wb') as f:\n", | |
" f.write(data)\n", | |
"\n", | |
"def s3fs_nifti_read(fname):\n", | |
" fs = s3fs.S3FileSystem()\n", | |
" with fs.open(fname) as f:\n", | |
" zz = gzip.open(f)\n", | |
" rr = zz.read()\n", | |
" bb = BytesIO(rr)\n", | |
" fh = nib.FileHolder(fileobj=bb)\n", | |
" img = nib.Nifti1Image.from_file_map({'header': fh, 'image': fh})\n", | |
"\n", | |
" return img" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 3, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"s3fs_nifti_write(orig_img, fname)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 4, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"new_img = s3fs_nifti_read(fname)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 5, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": [ | |
"True" | |
] | |
}, | |
"execution_count": 5, | |
"metadata": {}, | |
"output_type": "execute_result" | |
} | |
], | |
"source": [ | |
"np.all(new_img.get_fdata() == orig_img.get_fdata())" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": null, | |
"metadata": {}, | |
"outputs": [], | |
"source": [] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Python 3", | |
"language": "python", | |
"name": "python3" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython3", | |
"version": "3.7.0" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment