1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-21 19:33:03 +04:00
Files
Ebrahim Namdari b29ea17666 Merge pull request #28967 from IbrahimNamdari:add-video-context-manager
Python: add context manager compatibility for VideoCapture and VideoWriter #28967

### Description
This PR implements the context manager protocol (`with` statement support) for `cv2.VideoCapture` and `cv2.VideoWriter` objects in Python.

### Problem
Currently, these classes do not support the context manager protocol, leading to a `TypeError: ... object does not support the context manager protocol` when used with a `with` block. As reported in issue #28956, if an exception occurs before an explicit `.release()` call, the video resource or file remains locked in the system[cite: 298, 309].

### Identification & Motivation
By analyzing the issue and the Python binding structure of OpenCV, I identified that while the core logic resides in C++, the Pythonic behavior can be enhanced by injecting `__enter__` and `__exit__` methods during the module initialization. This ensures that resources are automatically and safely released even if the program execution is interrupted by an error[cite: 298, 325].

### Solution
I have modified `modules/python/package/cv2/__init__.py` to dynamically inject the necessary methods:
1. Defined `_video_enter` to return the object itself (standard context manager behavior).
2. Defined `_video_exit` to trigger the `.release()` method automatically.
3. Injected these methods into `VideoCapture` and `VideoWriter` classes immediately after the `bootstrap()` function to ensure the native C++ classes are correctly loaded into the global namespace.

Fixes #28956
2026-05-15 15:41:02 +03:00
..
2025-07-03 13:14:48 +02:00