TensorFlow目标检测API运行报错:无法导入string_int_label_map_pb2
Hey there, I’ve dealt with this exact error a few times when setting up the TensorFlow Object Detection API, so let’s walk through the most common fixes to get you sorted:
1. Verify Protobuf Compilation Worked Correctly
First up, make sure the proto files actually compiled into Python modules. The %%bash cell in Jupyter sometimes has issues with directory switching—try running the compilation command directly in your terminal instead:
# Navigate to your models/research folder first cd /path/to/your/models/research protoc object_detection/protos/*.proto --python_out=.
After running this, check the object_detection/protos directory. You should see .py files like string_int_label_map_pb2.py corresponding to each .proto file. If these files are missing, the compilation failed—double-check your protobuf installation and the command syntax.
2. Add the Correct Paths to Python’s sys.path
Even if you added the protobuf path, you need to ensure the models/research and models/research/slim directories are in your Python path. Add these lines at the very top of your script/notebook:
import sys sys.path.append('/path/to/your/models/research') sys.path.append('/path/to/your/models/research/slim')
Alternatively, set the environment variable in your terminal before running your code:
export PYTHONPATH=$PYTHONPATH:/path/to/your/models/research:/path/to/your/models/research/slim
Replace /path/to/your with the actual directory where your TensorFlow models repo is stored.
3. Match Your Protobuf Version to TensorFlow’s Requirements
Mismatched protobuf versions are a common culprit. The Object Detection API is picky about this—for most TF 2.x setups, protobuf 3.20.x tends to work reliably. Let’s fix that:
pip uninstall protobuf -y pip install protobuf==3.20.3
After reinstalling, re-run the protobuf compilation command from step 1 to make sure everything generates correctly.
4. Test Direct Import of the Problematic Module
To narrow down the issue, try importing the string_int_label_map_pb2 module directly in your notebook/script:
import object_detection.protos.string_int_label_map_pb2
If this throws an error, it confirms the path isn’t set up properly. Go back to step 2 and verify your paths are correct.
Once you’ve worked through these steps, retry your original import statements:
from object_detection.utils import ops as utils_ops from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as vis_util
内容的提问来源于stack exchange,提问作者Sai Krishnadas

