@@ -1231,17 +1231,26 @@ class NumpyReader(ImageReader):
12311231 npz_keys: if loading npz file, only load the specified keys, if None, load all the items.
12321232 stack the loaded items together to construct a new first dimension.
12331233 channel_dim: if not None, explicitly specify the channel dim, otherwise, treat the array as no channel.
1234+ allow_pickle: if True, allows loading pickled contents from NPY/NPZ files. Note that the default value of False
1235+ prevents the risk of remote code execution, set this to True only for loading known trusted data. If this
1236+ argument is False and pickled data is loaded, a ValueError will be raised.
12341237 kwargs: additional args for `numpy.load` API except `allow_pickle`. more details about available args:
12351238 https://numpy.org/doc/stable/reference/generated/numpy.load.html
1236-
12371239 """
12381240
1239- def __init__ (self , npz_keys : KeysCollection | None = None , channel_dim : str | int | None = None , ** kwargs ):
1241+ def __init__ (
1242+ self ,
1243+ npz_keys : KeysCollection | None = None ,
1244+ channel_dim : str | int | None = None ,
1245+ allow_pickle : bool = False ,
1246+ ** kwargs ,
1247+ ):
12401248 super ().__init__ ()
12411249 if npz_keys is not None :
12421250 npz_keys = ensure_tuple (npz_keys )
12431251 self .npz_keys = npz_keys
12441252 self .channel_dim = float ("nan" ) if channel_dim == "no_channel" else channel_dim
1253+ self .allow_pickle = allow_pickle
12451254 self .kwargs = kwargs
12461255
12471256 def verify_suffix (self , filename : Sequence [PathLike ] | PathLike ) -> bool :
@@ -1267,14 +1276,25 @@ def read(self, data: Sequence[PathLike] | PathLike, **kwargs):
12671276 More details about available args:
12681277 https://numpy.org/doc/stable/reference/generated/numpy.load.html
12691278
1279+ Raises:
1280+ ValueError: when `self.allow_pickle` is False but loaded data contains pickled objects.
12701281 """
12711282 img_ : list [Nifti1Image ] = []
12721283
12731284 filenames : Sequence [PathLike ] = ensure_tuple (data )
12741285 kwargs_ = self .kwargs .copy ()
12751286 kwargs_ .update (kwargs )
12761287 for name in filenames :
1277- img = np .load (name , allow_pickle = True , ** kwargs_ )
1288+ try :
1289+ img = np .load (name , allow_pickle = self .allow_pickle , ** kwargs_ )
1290+ except ValueError as e :
1291+ # if a ValueError is raised, this is likely about pickle loading so raise an exception about this
1292+ raise ValueError (
1293+ "MONAI default value for argument `allow_pickle` of `np.load` changed to `False`, "
1294+ "explicitly pass `allow_pickle=True` as a constructor argument to NumpyReader "
1295+ "to enable pickle loading."
1296+ ) from e
1297+
12781298 if Path (name ).name .endswith (".npz" ):
12791299 # load expected items from NPZ file
12801300 npz_keys = list (img .keys ()) if self .npz_keys is None else self .npz_keys
0 commit comments