Skip to main content
  1. Posts/

How to Enable Method Autocompletion for OpenCV

·238 words·2 mins·
Table of Contents

Introduction
#

In Python, some packages are written mainly or partially in C++, and the Python interfaces are just wrappers around the binary C++ module. Among these packages, there is OpenCV.

When I use python-lsp-server or pyright with Neovim1, I can not get method completion for the OpenCV package. This is because the OpenCV projects is developed using C++ and does not have stub files2 shipped yet.

Using stub file from project python-type-stubs
#

Fortunately, the project python-type-stubs provides stub files for several projects including OpenCV. To use the stub file, first find where OpenCV is installed on your system:

python -c 'import os, cv2; print(os.path.dirname(cv2.__file__))'

Then download the stub file and put it in the same directory as OpenCV.

curl -sSL https://raw.githubusercontent.com/microsoft/python-type-stubs/main/cv2/__init__.pyi \
    -o path/to/opencv/directory/__init__.pyi

Then restart nvim, the auto-completion for OpenCV should work as expected.

Using stubgen
#

We can also use stubgen to generate the stub files, like this:

# stubgen is installed via mypy package
pip install -U mypy

stubgen -m cv2

The stub file will be saved under the out/ directory. However, the stub file generated by stubgen lacks doc and is not as good as stub file provided by project python-type-stubs.

For more info on using stubgen, visit its page.

References
#

Related

Convert Python Script to Exe on Windows with Pyinstaller
·439 words·3 mins
JPEG Image Quality in PIL
··298 words·2 mins
Convert PIL or OpenCV Image to Bytes without Saving to Disk
··409 words·2 mins