Search code examples
pythonnumpyopencvpython-typing

How do I type-hint OpenCV images in Python?


I get that in Python OpenCV images are numpy arrays, that correspond to cv::Mat in c++.

This question is about what type-hint to put into python functions to properly restrict for OpenCV images (maybe even for a specific kind of OpenCV image).

What I do now is:

import numpy as np
import cv2

Mat = np.ndarray

def my_fun(image: Mat):
    cv2.imshow('display', image)
    cv2.waitKey()

Is there any better way to add typing information for OpenCV images in python?


Solution

  • UPD: As mentioned in another answer, now, OpenCV has cv2.typing.MatLike. Then, the code would be:

    import cv2
    
    
    def my_fun(img: cv2.typing.MatLike) -> None:
        pass
    

    You can specify it as numpy.typing.NDArray with an entry type. For example,

    import numpy as np
    
    Mat = np.typing.NDArray[np.uint8]
    
    def my_fun(img: Mat):
        pass