Skip to content

Wrong python type hints for imread #26811

@scamille

Description

@scamille

System Information

OpenCV python version 4.10.0.84 / Fails also on OpenCV python version 4.11.0.86
Operating System / Platform: Ubuntu 24.04
python version 3.10.14

Detailed description

I would like to report that the function cv2.imread reports a return type cv2.typing.MatLike when according to documentation, it should report cv2.typing.MatLike | None.

Documentation:

The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).

Note: In OpenCV for python, this translates into returning None.

Additional notes:

  • Correctly reporting through the typing system that the function cv2.imread can return None in case the image cannot be read allows users to be forced through static type checkers to explicitly handle (or at least log) the case where a image can not be read. This adds value.
  • This issue might apply to other functions. cv2.imdecode is one example.

Steps to reproduce

import tempfile

import cv2

with tempfile.TemporaryFile() as temp_file:
    temp_file.write(b"Corrupted binary data. Not a image")
    temp_file.seek(0)
    image = cv2.imread(str(temp_file.name))
    assert image is None

This code passes, showing that the type hint (no None returned) doesn't match the actual behavior.

Issue submission checklist

  • I report the issue, it's not a question
  • I checked the problem with documentation, FAQ, open issues, forum.opencv.org, Stack Overflow, etc and have not found any solution
  • I updated to the latest OpenCV version and the issue is still there
  • There is reproducer code and related data files (videos, images, onnx, etc)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions