Ubuntu下VS Code中OpenCV代码补全失效问题求助
Hey there, I’ve run into exactly the same problem before—after compiling OpenCV from source to get those non-free algorithms like SURF and SIFT, the code completion in VS Code goes haywire, showing random functions like bootstrap() instead of proper OpenCV methods. Here are a few tried-and-true fixes that worked for me:
1. Verify OpenCV Compilation Flags for Python Bindings
When you compiled OpenCV, you might have missed flags that generate the necessary type hint files for VS Code. Double-check these options were enabled during the CMake configuration:
BUILD_opencv_python3: Ensures Python 3 bindings are builtBUILD_opencv_python_bindings_generator: Generates the binding code and type stubsINSTALL_CREATE_DISTRIB: Helps package the Python bindings correctly
If any of these were off, recompile OpenCV with them enabled. After installation, head to your OpenCV Python directory (typically /usr/local/lib/python3.6/site-packages/cv2) and confirm there’s a cv2.pyi or __init__.pyi file alongside the main .so library—this is the type hint file VS Code needs.
2. Point VS Code to the Correct Python Environment
Make sure VS Code is using the exact Python interpreter where your compiled OpenCV is installed:
- Press
Ctrl+Shift+Pto open the command panel, then selectPython: Select Interpreterand pick your system’s Python 3.6 (or the virtual environment if you used one) - Add the OpenCV installation path to VS Code’s extra completion paths in
settings.json:"python.autoComplete.extraPaths": ["/usr/local/lib/python3.6/site-packages"]
3. Manually Generate Type Hint Files
If your compilation didn’t produce the .pyi file, you can generate it manually using stubgen (part of the mypy tool):
- Install mypy first:
pip install mypy - Run stubgen on your OpenCV library file:
stubgen -o . /usr/local/lib/python3.6/site-packages/cv2/cv2.cpython-36m-x86_64-linux-gnu.so - Move the generated
cv2.pyifile into thecv2directory—VS Code will pick it up immediately for code completion.
4. Clear VS Code Cache and Restart
Sometimes VS Code’s language server caches old data. Try:
- Fully closing VS Code (make sure no background processes are running)
- Or press
Ctrl+Shift+Pand runPython: Restart Language Serverto refresh the completion engine
After trying these steps, your OpenCV code completion should be back to normal, showing all the methods you expect—including the SURF/SIFT functions you compiled in.
内容的提问来源于stack exchange,提问作者Abady

