调用convert_to_grayscale时遇AttributeError: keras.utils无shape属性
问题分析
触发AttributeError: module 'keras.utils' has no attribute 'shape'的核心原因是代码错误地将导入的keras.utils模块(别名image)当成了图像对象,调用了只有图像数组才有的shape属性。从错误栈的第54行可以看到,代码写了if len(image.shape) == 3 and image.shape[2] == 3:,这里的image是模块,不是加载后的图像数据,自然不存在shape属性。
修复方案
修正时只需把对模块的错误引用换成实际的图像数组对象,以下是完整的修正后代码:
def convert_to_grayscale(self): subdirectories = self.list_subdirectories() for subdirectory_name in subdirectories: subdirectory_path = os.path.join(self.base_dir, subdirectory_name) image_files = [os.path.join(subdirectory_path, file) for file in os.listdir(subdirectory_path) if os.path.isfile(os.path.join(subdirectory_path, file))] if image_files: for image_path in image_files: img = image.load_img(image_path) img_array = image.img_to_array(img) # 检查图像数组的维度,而非模块的属性 if len(img_array.shape) == 3 and img_array.shape[2] == 3: img_gray = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY) img_gray = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2BGR) # 确保输出为3通道图像 cv2.imwrite(image_path, img_gray) print("Grayscale conversion and saving completed.")
关键修正说明
- 将错误的
image.shape替换为img_array.shape:img_array是通过image.img_to_array(img)转换得到的图像数组,才具备shape属性,用来判断图像是否为3通道。 - 保留原有灰度转换逻辑:先将3通道图像转为灰度,再转回3通道,确保保存的图像和原图像通道数一致,避免后续处理可能出现的兼容性问题。
内容的提问来源于stack exchange,提问作者RASHEDIN
相关产品推荐
相关产品推荐

