From dec31340395b2578ef2b36435757897c9617ac1b Mon Sep 17 00:00:00 2001 From: Tim Huff <89954856+timmarkhuff@users.noreply.github.com> Date: Mon, 29 Jul 2024 10:58:47 -0700 Subject: [PATCH] Better logic for updating cv2.VideoCapture resolution (#52) * adding some better logic for updating resolution * bumping version and refactoring function * Automatically reformatting code with black and isort * one more refactor --------- Co-authored-by: Auto-format Bot --- pyproject.toml | 2 +- src/framegrab/grabber.py | 27 +++++++++++++++++++-------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index e7ed37c..8b9e54a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "framegrab" -version = "0.6.3" +version = "0.6.4" description = "Easily grab frames from cameras or streams" authors = ["Groundlight "] license = "MIT" diff --git a/src/framegrab/grabber.py b/src/framegrab/grabber.py index 765ed94..cceb5a9 100644 --- a/src/framegrab/grabber.py +++ b/src/framegrab/grabber.py @@ -473,15 +473,26 @@ def _set_cv2_resolution(self) -> None: """Set the resolution of the cv2.VideoCapture object based on the FrameGrabber's config. If the FrameGrabber lacks both of these properties (height and width), this method will do nothing. + + Similarly, if the specified resolution equals the existing resolution, this function will + do nothing. This is because setting the resolution of a cv2.VideoCapture object is non-trivial and + can take multiple seconds, so we should only do it when something has changed. """ - resolution = self.config.get("options", {}).get("resolution", {}) - height = resolution.get("height") - width = resolution.get("width") - - if width: - self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, width) - if height: - self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height) + resolution = self.config.get("options", {}).get("resolution") + if resolution is None: + return + + new_height = resolution.get("height") + new_width = resolution.get("width") + + if new_width: + current_width = int(self.capture.get(cv2.CAP_PROP_FRAME_WIDTH)) + if new_width != current_width: + self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, new_width) + if new_height: + current_height = int(self.capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) + if new_height != current_height: + self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, new_height) def apply_options(self, options: dict) -> None: """Update generic options such as crop and zoom as well as