Skip to content
TheChatArchiveThe Chat Archive
o4-mini-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

add a labels on top of the preview windows with average time (ms) needed for processing…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with DeepSeekdeepseek-r1-0528’s answer.
  1. User

    add a labels on top of the preview windows with average time (ms) needed for processing frame

  2. Assistant

    Here’s the updated version. It no longer tries to set any resolution—you simply grab whatever the camera is currently using—and it displays, above each video, an evolving average processing time (ms) for that camera.

    Key changes:
    • CameraWorker now measures per‐frame process+convert time and maintains a running average.
    • A new processing_time signal sends (cam_id, avg_ms).
    • The GUI creates a small QLabel above each video to show “Avg: XX.X ms” and updates it live.

    import sys, time, ctypes
    import numpy as np
    import mvsdk
    from PyQt5.QtCore   import Qt, QThread, QObject, pyqtSignal, pyqtSlot
    from PyQt5.QtGui    import QImage, QPixmap
    from PyQt5.QtWidgets import (QApplication, QLabel, QWidget, QHBoxLayout,
                                 QVBoxLayout, QMainWindow, QPushButton, QMessageBox)
    
    # --- USER CONFIGURATION ---
    TARGET_FPS = 3  # 3 or 5 fps
    
    # ─────────────────────────────────────────────────────────────────────
    class CameraWorker(QObject):
        """Captures from one MindVision camera and reports avg processing time."""
        image_ready      = pyqtSignal(int, QImage)  # cam_id, QImage
        processing_time  = pyqtSignal(int, float)   # cam_id, avg_ms
        error            = pyqtSignal(int, str)     # cam_id, msg
        finished         = pyqtSignal(int)          # cam_id
    
        def __init__(self, cam_id, dev_info):
            super().__init__()
            self.cam_id      = cam_id
            self.dev_info    = dev_info
            self.h_cam       = 0
            self.buf         = None
            self.buf_size    = 0
            self.channels    = 3
            self.running     = False
            self.frame_intv  = 1.0 / TARGET_FPS
    
            # for avg time
            self.time_sum    = 0.0
            self.time_count  = 0
    
        @pyqtSlot()
        def run(self):
            # 1) Init camera
            try:
                self.h_cam = mvsdk.CameraInit(self.dev_info, -1, -1)
            except mvsdk.CameraException as e:
                self.error.emit(self.cam_id, f"Init failed: {e.message}")
                self.finished.emit(self.cam_id)
                return
    
            # 2) Configure output format & get actual resolution
            try:
                cap      = mvsdk.CameraGetCapability(self.h_cam)
                is_mono  = cap.sIspCapacity.bMonoSensor != 0
                fmt      = (mvsdk.CAMERA_MEDIA_TYPE_MONO8 if is_mono
                            else mvsdk.CAMERA_MEDIA_TYPE_RGB8)
                self.channels = 1 if is_mono else 3
    
                mvsdk.CameraSetIspOutFormat(self.h_cam, fmt)
                mvsdk.CameraSetTriggerMode(self.h_cam, 0)  # continuous
    
                # read resolution from camera
                try:
                    res = mvsdk.CameraGetImageResolution(self.h_cam)
                    w, h = res.iWidth, res.iHeight
                except:
                    # fallback: use max from capabilities
                    w = cap.sResolutionRange.iWidthMax
                    h = cap.sResolutionRange.iHeightMax
    
                # allocate buffer
                self.buf_size = w * h * self.channels
                self.buf = mvsdk.CameraAlignMalloc(self.buf_size, 16)
    
                mvsdk.CameraPlay(self.h_cam)
    
            except mvsdk.CameraException as e:
                self.error.emit(self.cam_id, f"Config failed: {e.message}")
                self._cleanup()
                return
    
            # 3) Grab loop with FPS throttling & time measurement
            self.running = True
            last_emit = 0.0
    
            while self.running:
                try:
                    raw, head = mvsdk.CameraGetImageBuffer(self.h_cam, 1000)
                    start = time.time()
                    mvsdk.CameraImageProcess(self.h_cam, raw, self.buf, head)
                    mvsdk.CameraReleaseImageBuffer(self.h_cam, raw)
    
                    # convert to QImage
                    h, w = head.iHeight, head.iWidth
                    arrtype = ctypes.c_ubyte * (h * w * self.channels)
                    cbuf    = arrtype.from_address(self.buf)
                    frame   = np.frombuffer(cbuf, dtype=np.uint8)
    
                    if self.channels == 3:
                        frame = frame.reshape((h, w, 3))
                        img = QImage(frame.data, w, h, w*3, QImage.Format_RGB888).copy()
                    else:
                        frame = frame.reshape((h, w))
                        img = QImage(frame.data, w, h, w , QImage.Format_Grayscale8).copy()
    
                    # timing
                    proc_ms = (time.time() - start) * 1000.0
                    self.time_sum  += proc_ms
                    self.time_count+= 1
                    avg_ms = self.time_sum / self.time_count
    
                    # FPS throttle + emit
                    now = time.time()
                    if now - last_emit >= self.frame_intv:
                        last_emit = now
                        self.image_ready.emit(self.cam_id, img)
                        self.processing_time.emit(self.cam_id, avg_ms)
    
                except mvsdk.CameraException as e:
                    if e.error_code == mvsdk.CAMERA_STATUS_TIME_OUT:
                        continue
                    self.error.emit(self.cam_id, f"Capture error: {e.message}")
                    break
                except Exception as e:
                    self.error.emit(self.cam_id, f"Unexpected: {str(e)}")
                    break
    
            # cleanup
            self._cleanup()
    
        @pyqtSlot()
        def stop(self):
            self.running = False
    
        def _cleanup(self):
            if self.h_cam:
                try:
                    mvsdk.CameraStop(self.h_cam)
                    mvsdk.CameraUnInit(self.h_cam)
                except:
                    pass
            if self.buf:
                mvsdk.CameraAlignFree(self.buf)
            self.finished.emit(self.cam_id)
    
    # ─────────────────────────────────────────────────────────────────────
    class DualCamWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            self.setWindowTitle(f"DualCam @ {TARGET_FPS} FPS")
            self.resize(1200, 600)
    
            self.labels   = []
            self.time_lbl = []
    
            hl = QHBoxLayout()
            for i in (0,1):
                tl = QLabel(f"Cam{i}: Avg -- ms", alignment=Qt.AlignCenter)
                vl = QLabel(f"Camera {i}\nClick START", alignment=Qt.AlignCenter)
                vl.setMinimumSize(560,420)
                vl.setStyleSheet("background:#eee; border:1px solid #666;")
    
                self.time_lbl.append(tl)
                self.labels.append(vl)
    
                box = QVBoxLayout()
                box.addWidget(tl)
                box.addWidget(vl)
                hl.addLayout(box)
    
            self.btn = QPushButton("START")
            self.btn.clicked.connect(self.toggle)
    
            main = QVBoxLayout()
            main.addLayout(hl)
            main.addWidget(self.btn)
    
            cw = QWidget()
            cw.setLayout(main)
            self.setCentralWidget(cw)
    
            self.threads = []
            self.workers = []
            self.running = False
    
        @pyqtSlot()
        def toggle(self):
            if self.running: 
                self.stop_all()
            else:           
                self.start_all()
    
        def start_all(self):
            devs = mvsdk.CameraEnumerateDevice()
            if len(devs)<2:
                QMessageBox.critical(self, "Error", "Need 2 MindVision cameras.")
                return
    
            for i in (0,1):
                th = QThread()
                wk = CameraWorker(i, devs[i])
                wk.moveToThread(th)
    
                th.started.connect(wk.run)
                wk.image_ready.connect(self._update_image)
                wk.processing_time.connect(self._update_time)
                wk.error.connect(self._on_error)
                wk.finished.connect(th.quit)
                wk.finished.connect(wk.deleteLater)
                th.finished.connect(th.deleteLater)
    
                th.start()
                self.threads.append(th)
                self.workers.append(wk)
    
            self.running = True
            self.btn.setText("STOP")
    
        def stop_all(self):
            for wk in self.workers:
                wk.stop()
            for th in self.threads:
                th.wait(2000)
    
            self.threads.clear()
            self.workers.clear()
            self.running = False
            self.btn.setText("START")
            for i in (0,1):
                self.labels[i].setText(f"Camera {i}\nClick START")
                self.time_lbl[i].setText(f"Cam{i}: Avg -- ms")
    
        @pyqtSlot(int, QImage)
        def _update_image(self, cam_id, img):
            pix = QPixmap.fromImage(img).scaled(
                self.labels[cam_id].size(),
                Qt.KeepAspectRatio,
                Qt.SmoothTransformation
            )
            self.labels[cam_id].setPixmap(pix)
    
        @pyqtSlot(int, float)
        def _update_time(self, cam_id, avg_ms):
            self.time_lbl[cam_id].setText(f"Cam{cam_id}: Avg {avg_ms:.1f} ms")
    
        @pyqtSlot(int, str)
        def _on_error(self, cam_id, msg):
            QMessageBox.critical(self, f"Cam{cam_id} Error", msg)
            self.stop_all()
    
        def closeEvent(self, e):
            self.stop_all()
            e.accept()
    
    # ─────────────────────────────────────────────────────────────────────
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        w = DualCamWindow()
        w.show()
        sys.exit(app.exec_())
    

    How it works:

    • CameraWorker

    • Measures only the processing+conversion time each frame (start … end).
    • Keeps a running average (time_sum / time_count).
    • Emits processing_time(cam_id, avg_ms) along with the frame.

    • GUI

    • Above each video widget is a small label initialized to “Avg -- ms.”
    • Connected to processing_time—updates to “Avg XX.X ms” in real time.

    Enjoy!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.