Skip to content

Commit 77fe652

Browse files
author
Ben Cipollini
committed
Improve error handling, efficiency, and search more broadly over header extensions.
1 parent e8f8b22 commit 77fe652

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

nibabel/spatialimages.py

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@
137137
except NameError: # python 3
138138
basestring = str
139139

140+
import os.path
140141
import warnings
141142

142143
import numpy as np
@@ -890,18 +891,30 @@ def is_image(klass, filename, sniff=None):
890891
return True, sniff
891892

892893
# Determine the metadata location, then sniff it
893-
ftypes = dict(klass.files_types)
894-
if 'header' not in ftypes:
894+
header_exts = [ft[1] for ft in klass.files_types if ft[0] == 'header']
895+
if len(header_exts) == 0:
895896
metadata_filename = filename
896897
else:
897-
metadata_filename = froot + ftypes['header'] + trailing
898+
# Search for an acceptable existing header;
899+
# could be compressed or not...
900+
for ext in header_exts:
901+
for tr_ext in np.unique([trailing, ''] + list(klass._compressed_exts)):
902+
metadata_filename = froot + ext + tr_ext
903+
if os.path.exists(metadata_filename):
904+
break
898905

899-
sniff_size = 1024 # klass.header_class.sniff_size
900-
if not sniff or len(sniff) < sniff_size:
901-
with BinOpener(metadata_filename, 'rb') as fobj:
902-
sniff = fobj.read(sniff_size)
903-
904-
return klass.header_class.is_header(sniff[:sniff_size]), sniff
906+
try:
907+
if not sniff or len(sniff) < klass.header_class.sniff_size:
908+
# 1024 == large size, for efficiency (could iterate over imageclasses).
909+
sniff_size = np.max([1024, klass.header_class.sniff_size])
910+
with BinOpener(metadata_filename, 'rb') as fobj:
911+
sniff = fobj.read(sniff_size)
912+
return klass.header_class.is_header(sniff[:klass.header_class.sniff_size]), sniff
913+
except Exception as e:
914+
# Can happen if: file doesn't exist,
915+
# filesize < necessary sniff size (this happens!)
916+
# other unexpected errors.
917+
return False, sniff
905918

906919
def __getitem__(self):
907920
''' No slicing or dictionary interface for images

0 commit comments

Comments
 (0)