close

 

利用timer每秒更新一次檢查目前的FPS,如果FPS==0,則 counter_NG+1
當counter_NG >= 3,試圖重新連線,一直到成功為止

D:\python\pyside6\yolov8_wafer_shift\IC-Imaging-Control-Samples\Python\tisgrabber\samples

import sys
from PySide6.QtGui import QImage, QPixmap
from PySide6.QtCore import QTimer, QTime, Qt
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton, QVBoxLayout, QWidget
import ctypes
import tisgrabber as tis
import numpy as np
import cv2
 
class CallbackUserdata(ctypes.Structure):
    """ Example for user data passed to the callback function. """
    def __init__(self):
        self.Value1 = 0
        self.Value2 = 0
        self.camera = None      # Reference to a camera/grabber object

class TimerApp(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("TIS Camera App")
        self.image_info_label = QLabel()
        self.image_label = QLabel()    
        self.image_label.setGeometry(0, 0, 640, 480)
        # Create a label to display the timer value
        self.timer_label = QLabel("00:00:00")
        self.timer_label.setAlignment(Qt.AlignCenter)
        self.setCentralWidget(self.timer_label)

        # Create start and stop buttons
        self.start_button = QPushButton("Start")
        self.stop_button = QPushButton("Stop")
        self.stop_button.setEnabled(False)  # Initially disable stop button

        # Create a layout and add buttons to it
        layout = QVBoxLayout()
        layout.addWidget(self.image_label)
        layout.addWidget(self.image_info_label)
        layout.addWidget(self.timer_label)
        layout.addWidget(self.start_button)
        layout.addWidget(self.stop_button)

        # Create a central widget and set the layout
        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        # Connect button signals to slots
        self.start_button.clicked.connect(self.start_timer)
        self.stop_button.clicked.connect(self.stop_timer)

        # Create a QTimer object
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_timer)

        self.time_elapsed = QTime(0, 0)

        # initialize tis camera
        self.ic = ctypes.cdll.LoadLibrary("./tisgrabber_x64.dll")
        tis.declareFunctions(self.ic)
        self.counter = 0
        self.fps = 0
        self.counter_NG = 0
        self.ic.IC_InitLibrary(0)
       
    def FrameCallback(self, hGrabber, pBuffer, framenumber, pData):
        """ This is an example callback function
            The image is saved in test.jpg and the pData.Value1 is
            incremented by one.

        :param: hGrabber: This is the real pointer to the grabber object. Do not use.
        :param: pBuffer : Pointer to the first pixel's first byte
        :param: framenumber : Number of the frame since the stream started
        :param: pData : Pointer to additional user data structure
        """
        Width = ctypes.c_long()
        Height = ctypes.c_long()
        BitsPerPixel = ctypes.c_int()
        colorformat = ctypes.c_int()

        # Query the image description values
        self.ic.IC_GetImageDescription(hGrabber, Width, Height, BitsPerPixel,
                                colorformat)

        # Calculate the buffer size
        bpp = int(BitsPerPixel.value/8.0)
        buffer_size = Width.value * Height.value * bpp

        if buffer_size > 0:
            image = ctypes.cast(pBuffer,
                                ctypes.POINTER(
                                    ctypes.c_ubyte * buffer_size))

            cvMat = np.ndarray(buffer=image.contents,
                            dtype=np.uint8,
                            shape=(Height.value,
                                    Width.value,
                                    bpp))
           
            height, width, channels = cvMat.shape
            bytes_per_line = width * channels
           
            qimage = QImage(cvMat.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
           
            # rescale qimage to a customed size
            custom_width = 640
            custom_height = 480

            scaled_image = qimage.scaled(custom_width, custom_height, Qt.AspectRatioMode.KeepAspectRatio)
            self.image_label.setPixmap(QPixmap.fromImage(scaled_image))

        pData.Value1 += 1
        self.Value1 = pData.Value1
        self.counter += 1
        self.image_info_label.setText( f'影像解析: {width}x{height} 楨數: {self.Value1}')
        # print("Callback called", pData.Value1)
       

    def start_timer(self):
        self.start_button.setEnabled(False)
        self.stop_button.setEnabled(True)
        self.timer.start(1000)  # Start timer with 1-second interval
        self.hGrabber = self.ic.IC_CreateGrabber()
        self.ic.IC_OpenVideoCaptureDevice(self.hGrabber, tis.T("DMK 72AUC02"))
        self.ic.IC_SetVideoFormat(self.hGrabber, tis.T("RGB32 (2592x1944)"))
        self.ic.IC_SetFrameRate(self.hGrabber, ctypes.c_float(30.0))
        self.Userdata = CallbackUserdata()
        self.Callbackfuncptr = self.ic.FRAMEREADYCALLBACK(self.FrameCallback)

        self.ic.IC_SetFrameReadyCallback(self.hGrabber, self.Callbackfuncptr, self.Userdata)
        self.ic.IC_SetContinuousMode(self.hGrabber, 0)
        if(self.ic.IC_IsDevValid(self.hGrabber)):
            self.ic.IC_StartLive(self.hGrabber, 0)

    def stop_timer(self):
        self.start_button.setEnabled(True)
        self.stop_button.setEnabled(False)
        self.timer.stop()
        if(self.ic.IC_IsDevValid(self.hGrabber)):  
            self.ic.IC_StopLive(self.hGrabber)
            self.ic.IC_ReleaseGrabber(self.hGrabber)
            cv2.destroyAllWindows()
            self.counter_NG = 0

    def update_timer(self):
        self.time_elapsed = self.time_elapsed.addSecs(1)
        self.fps = self.counter
        self.counter = 0
        if self.fps == 0:
            self.counter_NG += 1
        else:
            self.counter_NG = 0

        if self.counter_NG >= 3:
            self.stop_timer()
            self.start_timer()

        time_str = self.time_elapsed.toString("hh:mm:ss")
        self.timer_label.setText( f'連線時間: {time_str} FPS: {self.fps} 斷線: {self.counter_NG}' )

if __name__ == "__main__":
    app = QApplication(sys.argv)
    timer_app = TimerApp()
    timer_app.show()
    sys.exit(app.exec())

 

故意將USB斷線,當counter_NG計數器>=3會自動偵測並嘗試重新連線

 

 

 

 

 

 

 

 

 

 

 

 

 

arrow
arrow
    全站熱搜

    me1237guy 發表在 痞客邦 留言(0) 人氣()