'How to specify python type hints for complex package as opencv or tensorflow?
I am building a python library and I writing a function like this:
def addimg(image) -> None:
now I want to specify the type of image as an OpenCV image (e.g., the result of cv2.readimg()). Is there an elegant way to do that?
The same question for PyTorch or TensorFlow tensors.
Otherwise, my library ends up with every second variable having no specified type and I think this looks really ugly.
Thank you very much! Best, Bernhard
Solution 1:[1]
The type of an OpenCV image is a Numpy array (named ndarray
):
>>> image = cv2.imread("my_image.png")
>>> type(image)
numpy.ndarray
So you can use:
from numpy import ndarray
def addimg(image: ndarray) -> None:
...
Update:
Numpy version 1.21 introduced numpy.typing.NDArray
, a generic version of ndarray
that allows specifying the data type.
For example, if the image uses uint8
:
from numpy import uint8
from numpy.typing import NDArray
def addimg(image: NDArray[uint8]) -> None:
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |