Skip to content

fix wrong python type hints for imread#26890

Merged
asmorkalov merged 1 commit intoopencv:4.xfrom
shyama7004:type-hint
Feb 8, 2025
Merged

fix wrong python type hints for imread#26890
asmorkalov merged 1 commit intoopencv:4.xfrom
shyama7004:type-hint

Conversation

@shyama7004
Copy link
Copy Markdown
Contributor

Fixes : #26811

Updated api_refinement.py to refine the return type of cv2.imread and cv2.imdecode.

  • Previously, these functions were typed to always return a valid image.
  • Now, they are correctly annotated as MatLike | None, ensuring static type checkers like mypy detect cases where the function might return None.
Fix details

Before Fix

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))
    print(image.shape)
mypy test.py
# output : Success: no issues found in 1 source file

After Fix

Now, mypy correctly flags None access:

test.py:8: error: Item "None" of "ndarray[Any, dtype[...]] | None" has no attribute "shape"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

  • I agree to contribute to the project under Apache 2 License.
  • To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
  • The PR is proposed to the proper branch
  • There is a reference to the original bug report and related work
  • There is accuracy test, performance test and test data in opencv_extra repository, if applicable
    Patch to opencv_extra has the same branch name.
  • The feature is well documented and sample code can be built with the project CMake

@asmorkalov asmorkalov self-assigned this Feb 8, 2025
@asmorkalov asmorkalov added this to the 4.12.0 milestone Feb 8, 2025
@asmorkalov asmorkalov merged commit 0e17a87 into opencv:4.x Feb 8, 2025
@shyama7004 shyama7004 deleted the type-hint branch February 8, 2025 08:20
@asmorkalov asmorkalov mentioned this pull request Feb 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Wrong python type hints for imread

2 participants