-
Notifications
You must be signed in to change notification settings - Fork 18
Commit 7ac3d45
committed
Fix camera malfunction crashes by implementing "QThread"-based solution
PROBLEM:
Application crashed/froze when camera malfunctioned because
camera I/O operations were blocking the main UI thread using "QTimer".
SOLUTION:
In order to eliminate application freezes when camera malfunctions,
I replaced an existing timer-based camera capture ("QTimer" approach)
with a dedicated background thread (a "VideoThread" class) that:
- Inherits from "QThread" to run camera operations in background thread.
- Uses "pyqtSignal" for thread-safe communication with UI thread.
- Implements proper thread life-cycle management:
- start()
- stop()
- cleanup()
- Provides robust error handling and user feedback.
CORE CHANGES:
- Replaced "self.timer" (a "QTimer" object)
with "self.video_thread" (a "VideoThread" object).
- Moved all camera operations ("cv2.VideoCapture()", "cap.read()",
etc.) to the new background thread.
- Implemented signal-based communication for thread-safe frame/error handling.
- Added comprehensive error handling with user-friendly messages.
TECHNICAL DETAILS:
- Added "VideoThread" class ("QThread" subclass) for
background camera capture.
- Removed "QTimer"-based "view_video()" method
that blocked main thread and unused "QTimer" module import.
- Removed unnecessary "time.sleep(0.1)" camera initialization
delay and unused "time" module import.
- Removed global "timer" & "cap" variables (unsafe across threads)
and an ugly "globals()" usage together with a pending "TODO:" comment.
- Signal-based communication: "frame_captured" and
"error_occurred" signals:
- Thread-safe frame updates via "on_frame_captured()" slot.
- Graceful error handling via "on_video_error()" slot.
- Additionally performed some refactoring, i.e.:
- Modifying a "_read_video_frame()" static method into a
"read_frame()" inner method of the main thread execution
"run()" method, which results in a more clean and Pythonic code.
- Updated the error messages to clearly distinguish between
initialization failures (the camera/video cannot be opened initially)
and runtime failures (the camera/video was working but stopped).
BENEFITS:
- UI remains responsive during camera errors (no more freezing).
- Graceful handling of hardware failures (no more crashes).
- Professional error messages displayed to the user.
- Follows Qt best practices for hardware I/O.
Resolves: #5
Co-authored-by: Cursor AI
Signed-off-by: Pavel Bar <pbar@redhat.com>1 parent 73093f2 commit 7ac3d45Copy full SHA for 7ac3d45
File tree
Expand file treeCollapse file tree
7 files changed
+1650
-72
lines changedOpen diff view settings
Filter options
- QThread_design
Expand file treeCollapse file tree
7 files changed
+1650
-72
lines changedOpen diff view settings
0 commit comments