Keras数据增强中出现SciPy未定义的NameError问题求助
问题
在Conda环境miniconda3/envs/tf中已成功安装SciPy,Python脚本开头也执行了import scipy,但使用Keras的ImageDataGenerator做数据增强时,调用gen_img[0]触发NameError,提示name 'scipy' is not defined。已确认SciPy安装状态正常,但错误持续。
相关代码:
import scipy gen = ImageDataGenerator(rotation_range=10) img = np.array(cv2.imread(img_path)) gen_img = gen.flow(np.expand_dims(img, axis=0)) plt.imshow(gen_img[0])
报错栈追踪:
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[52], line 1 ----> 1 gen_img[0] File c:\Users\ADMIN\miniconda3\envs\tf\lib\site-packages\keras\preprocessing\image.py:116, in Iterator.__getitem__(self, idx) 112 self._set_index_array() 113 index_array = self.index_array[ 114 self.batch_size * idx : self.batch_size * (idx + 1) 115 ] --> 116 return self._get_batches_of_transformed_samples(index_array) File c:\Users\ADMIN\miniconda3\envs\tf\lib\site-packages\keras\preprocessing\image.py:801, in NumpyArrayIterator._get_batches_of_transformed_samples(self, index_array) 799 x = self.x[j] 800 params = self.image_data_generator.get_random_transform(x.shape) --> 801 x = self.image_data_generator.apply_transform( 802 x.astype(self.dtype), params 803 ) 804 x = self.image_data_generator.standardize(x) 805 batch_x[i] = x File c:\Users\ADMIN\miniconda3\envs\tf\lib\site-packages\keras\preprocessing\image.py:2013, in ImageDataGenerator.apply_transform(self, x, transform_parameters) 2010 img_col_axis = self.col_axis - 1 2011 img_channel_axis = self.channel_axis - 1 --> 2013 x = apply_affine_transform( 2014 x, 2015 transform_parameters.get("theta", 0), 2016 transform_parameters.get("tx", 0), 2017 transform_parameters.get("ty", 0), 2018 transform_parameters.get("shear", 0), 2019 transform_parameters.get("zx", 1), 2020 transform_parameters.get("zy", 1), 2021 row_axis=img_row_axis, 2022 col_axis=img_col_axis, 2023 channel_axis=img_channel_axis, 2024 fill_mode=self.fill_mode, 2025 cval=self.cval, 2026 order=self.interpolation_order, 2027 ) 2029 if transform_parameters.get("channel_shift_intensity") is not None: 2030 x = apply_channel_shift( 2031 x, 2032 transform_parameters["channel_shift_intensity"], 2033 img_channel_axis, 2034 ) File c:\Users\ADMIN\miniconda3\envs\tf\lib\site-packages\keras\preprocessing\image.py:2529, in apply_affine_transform(x, theta, tx, ty, shear, zx, zy, row_axis, col_axis, channel_axis, fill_mode, cval, order) 2485 @keras_export("keras.preprocessing.image.apply_affine_transform") 2486 def apply_affine_transform( 2487 x, (...) 2499 order=1, 2500 ): 2501 """Applies an affine transformation specified by the parameters given. 2502 2503 Args: (...) 2527 ImportError: if SciPy is not available. 2528 """ --> 2529 if scipy is None: 2530 raise ImportError( 2531 "Image transformations require SciPy. " "Install SciPy." 2532 ) 2534 # Input sanity checks: 2535 # 1. x must 2D image with one or more channels (i.e., a 3D tensor) 2536 # 2. channels must be either first or last dimension NameError: name 'scipy' is not defined
原因分析
这个错误并非你的代码问题,而是Keras内部的apply_affine_transform函数存在导入bug:
- 函数内部直接使用了
scipy变量,但既没有在函数内部导入SciPy,也没有在模块顶部完成正确导入; - 你自己脚本里的
import scipy仅在当前脚本的命名空间生效,无法被Keras内部函数访问。
解决方法
方法1:降级Keras到无bug的稳定版本
该bug常见于部分较新的Keras 2.x版本,可降级到经过验证的稳定版本:
conda activate tf pip install keras==2.10.0
方法2:手动修改Keras源码(临时应急)
找到报错文件c:\Users\ADMIN\miniconda3\envs\tf\lib\site-packages\keras\preprocessing\image.py,在apply_affine_transform函数开头添加SciPy导入:
def apply_affine_transform(...): import scipy # 添加此行 if scipy is None: raise ImportError(...) # 函数其余代码保持不变
方法3:改用TensorFlow官方图像增强API
放弃Keras旧版ImageDataGenerator,使用TensorFlow原生的增强模块,无需依赖SciPy:
import tensorflow as tf import cv2 import matplotlib.pyplot as plt import numpy as np # 定义增强层 data_augmentation = tf.keras.Sequential([ tf.keras.layers.RandomRotation(factor=0.1) # 对应原rotation_range=10 ]) img = np.array(cv2.imread(img_path)) img = tf.expand_dims(img, 0) # 增加batch维度 gen_img = data_augmentation(img) plt.imshow(gen_img[0].numpy().astype("uint8")) plt.show()
内容的提问来源于stack exchange,提问作者pragateesh
相关产品推荐
相关产品推荐

