Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 757
Barney Szabolcs Avatar asked Feb 12 '26 04:02

Barney Szabolcs


1 Answers

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
like image 147
user1635327 Avatar answered Feb 13 '26 17:02

user1635327



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!