Of course. Let's strip this down to a much simpler, more reliable version.
This code removes all GUI controls for resolution and FPS. You now configure these settings by changing variables at the top of the script. This eliminates the complex UI logic and potential points of failure, making the code much easier to run and debug.
The core logic for correctly finding the resolution index from the SDK is still present, as it's essential for the camera to work, but it now uses the hardcoded values you provide.
Simplified and Working Code
Just change the TARGET_RESOLUTION and TARGET_FPS variables, save, and run.
import sys
import numpy as np
import mvsdk
import ctypes
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel, QPushButton,
QVBoxLayout, QHBoxLayout, QWidget, QMessageBox)
from PyQt5.QtCore import (QThread, QObject, pyqtSignal, pyqtSlot, Qt)
from PyQt5.QtGui import QImage, QPixmap
# ====================================================================
# --- CONFIGURATION VARIABLES ---
# --- Change these values to configure the cameras before running ---
# ====================================================================
# Set your desired resolution here. This MUST be a resolution
# that your camera actually supports.
TARGET_RESOLUTION = (1600, 1200) # (width, height)
# Set your desired frames per second.
TARGET_FPS = 5 # Recommended: 3 or 5
# --- End of Configuration ---
class CameraConfig:
"""A simple data class to hold camera settings."""
def __init__(self, cam_id: int, fps: int, target_res_tuple: tuple):
self.cam_id = cam_id
self.fps = fps
self.target_res_w, self.target_res_h = target_res_tuple
# --- Camera Worker (The Core Logic) ---
class CameraWorker(QObject):
"""Handles all SDK interaction for ONE camera in a separate thread."""
image_updated = pyqtSignal(int, QImage)
error_occurred = pyqtSignal(int, str)
finished = pyqtSignal(int)
def __init__(self, config: CameraConfig):
super().__init__()
self.config = config
self._is_running = False
self.h_cam = 0
self.frame_buffer = None
self.buffer_size = 0
@pyqtSlot()
def run_capture(self):
"""Main capture loop using the predefined configuration."""
self._is_running = True
cam_id = self.config.cam_id
try:
dev_list = mvsdk.CameraEnumerateDevice()
if cam_id >= len(dev_list):
raise RuntimeError(f"Camera {cam_id+1} not found.")
self.h_cam = mvsdk.CameraInit(dev_list[cam_id], -1, -1)
# Get camera's supported resolutions to find the index of our target.
cap = mvsdk.CameraGetCapability(self.h_cam)
sdk_resolutions = self._get_sdk_resolutions(cap)
res_index = self._find_resolution_index(sdk_resolutions)
if res_index == -1:
supported_str = ", ".join([f"{r[0]}x{r[1]}" for r in sdk_resolutions])
raise RuntimeError(
f"Resolution {self.config.target_res_w}x{self.config.target_res_h} not supported by Camera {cam_id+1}.\n"
f"Supported resolutions are: {supported_str}"
)
# This is the critical step: Set resolution BY INDEX.
mvsdk.CameraSetImageResolution(self.h_cam, res_index)
mvsdk.CameraSetFrameSpeed(self.h_cam, self.config.fps)
mvsdk.CameraSetIspOutFormat(self.h_cam, mvsdk.CAMERA_MEDIA_TYPE_RGB8)
active_res_w, active_res_h = sdk_resolutions[res_index]
self.buffer_size = active_res_w * active_res_h * 3 # RGB
self.frame_buffer = mvsdk.CameraAlignMalloc(self.buffer_size, 16)
mvsdk.CameraPlay(self.h_cam)
except Exception as e:
self.error_occurred.emit(cam_id, f"Setup Failed: {e}")
self._cleanup()
return
# Main Capture Loop
while self._is_running:
try:
raw_data, frame_head = mvsdk.CameraGetImageBuffer(self.h_cam, 1000)
mvsdk.CameraImageProcess(self.h_cam, raw_data, self.frame_buffer, frame_head)
mvsdk.CameraReleaseImageBuffer(self.h_cam, raw_data)
img = self._buffer_to_qimage(frame_head)
if img:
self.image_updated.emit(cam_id, img)
except mvsdk.CameraException as e:
if e.error_code == mvsdk.CAMERA_STATUS_TIME_OUT:
continue
self.error_occurred.emit(cam_id, f"Capture Error: {e.message}")
self._is_running = False
self._cleanup()
def _get_sdk_resolutions(self, cap) -> list[tuple]:
"""Gets a list of (width, height) tuples from the camera's capabilities."""
return [(res.iWidth, res.iHeight) for res in cap.pResolutionInfo if res.iWidth > 0]
def _find_resolution_index(self, sdk_resolutions: list[tuple]) -> int:
"""Finds the SDK index for our hardcoded target resolution."""
target_w, target_h = self.config.target_res_w, self.config.target_res_h
for idx, (w, h) in enumerate(sdk_resolutions):
if w == target_w and h == target_h:
return idx
return -1
def _buffer_to_qimage(self, frame_head) -> QImage:
"""Converts the SDK's C-pointer buffer to a safe Qt QImage."""
data_ptr = (ctypes.c_ubyte * self.buffer_size).from_address(self.frame_buffer)
arr = np.frombuffer(data_ptr, dtype=np.uint8).reshape((frame_head.iHeight, frame_head.iWidth, 3))
# .copy() is critical to detach the data from the SDK buffer
return QImage(arr.data, frame_head.iWidth, frame_head.iHeight, 3 * frame_head.iWidth, QImage.Format_RGB888).copy()
def _cleanup(self):
"""Releases all SDK resources."""
if self.h_cam:
try:
mvsdk.CameraStop(self.h_cam)
mvsdk.CameraUnInit(self.h_cam)
except Exception: pass
self.h_cam = 0
if self.frame_buffer:
mvsdk.CameraAlignFree(self.frame_buffer)
self.frame_buffer = None
self.finished.emit(self.config.cam_id)
@pyqtSlot()
def stop(self):
self._is_running = False
# --- Main GUI Window ---
class DualCameraWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle(f"Dual Camera Viewer ({TARGET_RESOLUTION[0]}x{TARGET_RESOLUTION[1]} @ {TARGET_FPS} FPS)")
self.setGeometry(100, 100, 1400, 600)
self.camera_count = 2
self.threads = {}
self.workers = {}
self.is_capturing = False
# --- UI Setup (Simplified) ---
central = QWidget()
self.setCentralWidget(central)
layout = QVBoxLayout(central)
self.displays = [QLabel(f"Camera {i+1}\n(Stopped)", alignment=Qt.AlignCenter) for i in range(self.camera_count)]
display_layout = QHBoxLayout()
for display in self.displays:
display.setStyleSheet("border: 1px solid #555; background: #eee; min-height: 480px;")
display_layout.addWidget(display)
layout.addLayout(display_layout)
self.start_btn = QPushButton("START")
self.start_btn.clicked.connect(self.toggle_capture)
layout.addWidget(self.start_btn)
def toggle_capture(self):
if self.is_capturing: self.stop_capture()
else: self.start_capture()
def start_capture(self):
if self.is_capturing: return
# Configure and start both cameras using top-level variables
for cam_id in range(self.camera_count):
config = CameraConfig(cam_id, TARGET_FPS, TARGET_RESOLUTION)
self._start_worker(config)
self.is_capturing = True
self.start_btn.setText("STOP")
def _start_worker(self, config: CameraConfig):
cam_id = config.cam_id
thread = QThread()
worker = CameraWorker(config)
worker.moveToThread(thread)
thread.started.connect(worker.run_capture)
worker.image_updated.connect(self._update_display)
worker.error_occurred.connect(self._handle_error)
worker.finished.connect(thread.quit)
worker.finished.connect(worker.deleteLater)
thread.finished.connect(thread.deleteLater)
thread.finished.connect(lambda cid=cam_id: self._on_thread_finish(cid))
self.threads[cam_id] = thread
self.workers[cam_id] = worker
thread.start()
def stop_capture(self):
for worker in self.workers.values():
worker.stop()
for thread in self.threads.values():
thread.wait(2000)
self._reset_ui_state()
@pyqtSlot(int, QImage)
def _update_display(self, cam_id: int, image: QImage):
pixmap = QPixmap.fromImage(image).scaled(self.displays[cam_id].size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.displays[cam_id].setPixmap(pixmap)
@pyqtSlot(int, str)
def _handle_error(self, cam_id: int, error: str):
QMessageBox.critical(self, f"Camera {cam_id+1} Error", error)
if cam_id in self.workers:
self.workers[cam_id].stop()
def _on_thread_finish(self, cam_id: int):
self.threads.pop(cam_id, None)
self.workers.pop(cam_id, None)
if not self.threads:
self._reset_ui_state()
def _reset_ui_state(self):
self.is_capturing = False
self.start_btn.setText("START")
for i, display in enumerate(self.displays):
display.setText(f"Camera {i+1}\n(Stopped)")
def closeEvent(self, event):
self.stop_capture()
event.accept()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = DualCameraWindow()
window.show()
sys.exit(app.exec_())