0

I want to switch between cameras connected to the computer. I have PyQt5 list item and all cameras listed in there. So I also have camera indexes. However, I couldn't success switch between cameras interactively. When a new camera selected in the list I press the "REFRESH" button to display the selected camera stream on the PyQt label. How can I switch between cameras?

I use the following code to display stream and switch between them:

-reference: https://stackoverflow.com/a/44404713/13080899

class Stream_Thread(QThread):
changePixmap = pyqtSignal(QImage)

def __init__(self):
    super(Stream_Thread, self).__init__()
    self.ref = False        #refresh flag

def set_index(self, index = 0):
    self.index = index

def refresh(self):
    self.ref = True

def run(self):
    capt = cv2.VideoCapture(self.index, cv2.CAP_DSHOW)

    while(True):
        ret, frame = capt.read()

        if ret:
            rbgImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            h, w, ch = rbgImage.shape
            bytesPerLine = ch*w
            convertToQtFormat = QImage(rbgImage.data, w, h, bytesPerLine, QImage.Format_RGB888)
            p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio)
            self.changePixmap.emit(p)

        if self.ref:
            break

    capt.release()

"REFRESH" button method.

    def button_refresh_clicked(self, th):
    curr_id = self.get_cam_id()
    th.refresh()
    
    th = Stream_Thread()
    th.set_index(curr_id)
    th.start()
Ugurcan
  • 366
  • 1
  • 4
  • 17

1 Answers1

0

I found the correct way. Terminate the current thread, set the video capture index and start the thread again:

def button_refresh_clicked(self, th):
    curr_id = self.get_cam_id()
    th.terminate()

    th.set_index(curr_id)
    th.start()
Ugurcan
  • 366
  • 1
  • 4
  • 17