Mask R-CNN代码运行报错:ModuleNotFoundError: No module named 'keras.engine'
导入Mask R-CNN的model模块时出现ModuleNotFoundError: No module named 'keras.engine'
我编写了一段基于Mask R-CNN的图像训练代码,已安装TensorFlow、Keras及所有相关依赖,但运行时始终报错。报错信息显示,在导入mrcnn的model模块时,找不到keras.engine模块。
我的代码
import os import cv2 from mrcnn.config import Config # Import the Config class from mrcnn import model as modellib from mrcnn import utils # Define configuration parameters class MyConfig(Config): NAME = "my_config" IMAGES_PER_GPU = 1 DETECTION_MIN_CONFIDENCE = 0.9 IMAGE_MAX_DIM = 1024 # Adjust this value based on your requirements # Rest of your code... # Load the dataset dataset_dir = "output/histogram_equalization" image_subdirs = os.listdir(dataset_dir) # Create a list of image paths and corresponding class IDs image_paths = [] class_ids = [] for image_subdir in image_subdirs: image_dir = os.path.join(dataset_dir, image_subdir) for image_filename in os.listdir(image_dir): image_path = os.path.join(image_dir, image_filename) image_paths.append(image_path) class_ids.append(int(image_subdir)) # Load and preprocess images images = [] for image_path in image_paths: image = cv2.imread(image_path) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = cv2.resize(image, (MyConfig.IMAGE_MAX_DIM, MyConfig.IMAGE_MAX_DIM)) images.append(image) # Generate bounding boxes and masks bboxes = [] masks = [] for image_id in range(len(images)): class_id = class_ids[image_id] bbox = utils.generate_bbox(images[image_id], class_id) masks.append(utils.generate_mask_for_bbox(images[image_id], bbox)) bboxes.append(bbox) # Convert data into a format suitable for Mask R-CNN training dataset = { "images": images, "class_ids": class_ids, "bboxes": bboxes, "masks": masks } # Train the Mask R-CNN model model = modellib.MaskRCNN(config=MyConfig(), model_dir="./") # model.load_weights("mask_rcnn_weights.h5", by_name=True) # Load pre-trained weights if available model.train(dataset, dataset, epochs=20, layers="all") # Adjust layers based on your needs # Save the trained model model.keras_model.save("mask_rcnn_model.h5")
报错堆栈
C:\Users\mhlim\OneDrive\Desktop\Image_processing\venv\Scripts\python.exe C:\Users\mhlim\OneDrive\Desktop\Image_processing\RCNN.py Traceback (most recent call last): File "C:\Users\mhlim\OneDrive\Desktop\Image_processing\RCNN.py", line 4, in <module> from mrcnn import model as modellib File "C:\Users\mhlim\OneDrive\Desktop\Image_processing\venv\Lib\site-packages\mrcnn\model.py", line 24, in <module> import keras.engine as KE ModuleNotFoundError: No module named 'keras.engine'
问题原因与解决办法
这个问题核心是Keras版本不兼容:
- 原版Mask R-CNN(如matterport/Mask_RCNN)基于Keras 2.x开发,依赖
keras.engine模块,但Keras 3.x或TensorFlow自带的tf.keras已重构模块结构,不再保留该路径。 - 同时安装独立Keras包和TensorFlow会引发冲突,因为TensorFlow内置的tf.keras和独立Keras版本不兼容。
解决步骤
清理冲突环境
先卸载独立安装的Keras(如果有):pip uninstall keras -y选以下方案之一适配环境:
方案一:使用适配tf.keras的Mask R-CNN分支
若想继续用新版TensorFlow(2.x+),安装适配tf.keras的Mask R-CNN:pip install git+https://github.com/ahmedfgad/Mask-RCNN-TF2.git方案二:降级到兼容版本
安装和原版Mask R-CNN兼容的旧版TensorFlow和Keras(TensorFlow 2.10.0是最后一个自带独立Keras的版本):pip install tensorflow==2.10.0 keras==2.10.0
验证修复
打开Python终端运行以下代码,无报错则说明环境正常:import keras print(keras.__version__) from keras import engine
额外代码注意事项
- Mask R-CNN的
model.train()方法要求传入继承自utils.Dataset的数据集对象,当前用字典格式会导致训练报错,建议参考官方文档实现自定义数据集类。 utils.generate_bbox和utils.generate_mask_for_bbox并非Mask R-CNN自带方法,需要自行实现,否则后续也会触发报错。
内容的提问来源于stack exchange,提问作者Mh Limon
相关产品推荐
相关产品推荐

