How do I type-hint OpenCV images in Python?

Viewed 82

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?

1 Answers

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
Related