Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. Segmentation fault while working with QThreads
Forum Updated to NodeBB v4.3 + New Features

Segmentation fault while working with QThreads

Scheduled Pinned Locked Moved Unsolved Qt for Python
2 Posts 2 Posters 989 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Offline
    K Offline
    Kolappan
    wrote on last edited by
    #1

    I am getting Segmentation fault (core dumped) error when I try to run my code. It is not always but most of the times, but when the code runs, it does smoothly without any errors.
    The code basically gets the camera feed and displays it in one window and in another window it is being processed and displayed. After debugging it, I can see that the code throws in an error after the line im_I=np.copy(self.window.last_frame). I think this might be the issue because 1) There were no print statements were printed after this line.

    The op was

    hello
    hey
    Hellooo
    camera 1
    heyyy
    started processing image
    dolp_process: 1
    heyyy
    started processing image
    dolp_process: 2
    heyyy
    started processing image
    dolp_process: 3
    heyyy
    started processing image
    dolp_process: 4
    heyyy
    started processing image
    dolp_process: 5
    dolp_process_enter: 5

    samplecode.text

    from PyQt5.QtGui import QImage, QPixmap, qRgb
    import numpy as np
    import cv2
    from PyQt5.QtCore import Qt, QThread, QTimer, pyqtSignal
    from PyQt5.QtWidgets import QLabel, QMainWindow, QSpinBox, QWidget, QPushButton, QVBoxLayout, QApplication, QSlider, QGridLayout
    import time
    import sys
    
    stop_stream= True
    gray_color_table = [qRgb(i, i, i) for i in range(256)]
    path='C:\\Users\\VLV\\Desktop\\frame.png'
    
    def process_dolp(camera):
        while(True):
           print("heyyaa")
    
    class StartWindow(QMainWindow):
    
        save_image=False
        def __init__(self, camera = None):
            super(StartWindow,self).__init__()
            self.camera = camera
            self.last_frame=None 
            self.started = False
            self.central_widget = QWidget()
            self.button_frame = QPushButton('Acquire Frame', self.central_widget)
            self.button_start = QPushButton('Start Stream', self.central_widget)
            self.button_stop = QPushButton('Stop Stream', self.central_widget)
            self.image_view = QLabel()
            self.dolp_image_view = QLabel()
            self.brightness=QLabel()
            self.sp=QSpinBox()
            self.sp.setRange(0,1000000)
            self.sp.setValue(self.camera.pixel_tol_val)
            self.brightness.setText("Tolerance level")
            # self.ex=QSpinBox()
            # self.exposure.setText("Exposure level")
            self.fps_box=QLabel() 
            self.fps_box.setText('Fps : '+str(self.camera.fps))
    
            self.layout = QGridLayout(self.central_widget)
            self.layout.addWidget(self.button_frame,1,3)
            self.layout.addWidget(self.button_start,1,1)
            self.layout.addWidget(self.button_stop,1,5)
            self.layout.addWidget(self.image_view,6,6)
            self.layout.addWidget(self.dolp_image_view,9,9)
            self.layout.addWidget(self.brightness,3,1)
            # self.layout.addWidget(self.exposure,3,2)
            self.layout.addWidget(self.sp,4,1)
            self.layout.addWidget(self.fps_box, 4, 2)
            # self.layout.addWidget(self.ex,4,2)
            self.setCentralWidget(self.central_widget)
    
            self.button_frame.clicked.connect(self.save_images)
            self.button_start.clicked.connect(self.start_stream)
            self.button_stop.clicked.connect(self.stop_stream)
            self.sp.valueChanged.connect(self.update_pixel_tol)
            self.thread = QThread()
            self.worker = MovieThread(self, self.camera)
            self.worker.moveToThread(self.thread)
            self.worker.image_update.connect(self.update_image)
    
            self.thread.started.connect(self.worker.run)
            self.thread.start()
            time.sleep(2)
            self.thread1 = QThread()
            self.worker1 = ProcessThread(self, self.camera,True)
            self.worker1.moveToThread(self.thread1)
            self.worker1.image_update_dolp.connect(self.update_image_dolp)
    
            self.thread1.started.connect(self.worker1.run)
            self.thread1.start()
            self.start_stream()
    
        def save_images(self):
            if not stop_stream:
                self.camera.save_img=True
            else:
                print("First you need to start the stream")
    
        def update_image(self, Image):
    
            self.image_view.setPixmap(QPixmap.fromImage(Image))
            #self.last_frame=Image
    
        def update_image_dolp(self, Image):
            print("Inside heree")
            print(type(Image))
            self.dolp_image_view.setPixmap(QPixmap.fromImage(Image))
            #self.last_frame=Image
    
    
        def update_movie(self):
            self.image_view.setImage(self.camera.last_frame.T)
    
        def update_pixel_tol(self, value):  
            self.camera.set_pixel_tol(value)
    
        def start_stream(self):
            global stop_stream
            stop_stream=False
            self.button_start.setStyleSheet("background-color: yellow")
    
    
        def stop_stream(self):
            global stop_stream
            stop_stream=True
    
            # self.update_timer.start(30)
    
            while not stop_stream:
                self.update_image(self)
                
        def update_fps(self):
            self.fps_box.setText('Fps : '+str(self.camera.fps))
    
    
    class MovieThread(QThread):
        image_update=pyqtSignal(QImage)
        image_update_dolp=pyqtSignal(QImage)
        def __init__(self, window1, camera, dolp_process=False):
            super(MovieThread,self).__init__()
            self.camera = camera
            self.window=window1
            self.dolp_process = dolp_process
            self.frame_count=0
            
    
        def run(self):
            print("hello")
            cur_time=time.time()
    
            while True:
                if not stop_stream:
                   if not self.dolp_process:
                      with self.camera.cap.start_stream(1):
                        print("Hellooo")
                        start=time.time()
                        self.window.update_fps()
                        image_buffer = self.camera.cap.get_buffer()
                        nparray_reshaped = np.ctypeslib.as_array(image_buffer.pdata,(image_buffer.height,image_buffer.width))
                        output= nparray_reshaped[0::3,0::2]
                        frame = output
                    
                        #if len(self.camera.buffer)<self.camera.num_of_img:
                        #    self.camera.buffer.append(nparray_reshaped)
                        #else:
                        #    for iter in range(len(self.camera.buffer)-1):
                        #        self.camera.buffer[iter]=self.camera.buffer[iter+1]
                        #    self.camera.buffer[self.camera.num_of_img-1]=(nparray_reshaped)
                        #self.camera.save_image()
    
                          #frame=nparray_reshaped
                       
                        self.window.updated_frame_flag = False
                    #frame=cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
                        self.window.last_frame = frame
                        self.window.updated_frame_flag = True
                        self.frame_count+=1
                        print("camera",self.frame_count)
                        # print(type(frame))
                        # print("Storing frame of size : ", np.shape(frame))
                        frame=nparray_reshaped                      
                        flipped_img=frame
                    #flipped_img = cv2.flip(frame,1)
                        convert_to_qt_fmt= QImage(flipped_img.data, flipped_img.shape[1], flipped_img.shape[0],QImage.Format_Grayscale8)
                        Pic=convert_to_qt_fmt.scaled(640, 480, Qt.KeepAspectRatio)
                        self.window.last_Pic=Pic
                        self.window.started=True
                    # Pic.setColorTable(gray_color_table)
    
                        self.image_update.emit(Pic)
                        time_taken=time.time()-start
                        self.camera.fps=int(1/time_taken)
    
    class ProcessThread(QThread):
        image_update=pyqtSignal(QImage)
        image_update_dolp=pyqtSignal(QImage)
        def __init__(self, window1, camera, dolp_process=False):
            super(ProcessThread,self).__init__()
            self.camera = camera
            self.window=window1
            self.dolp_process = dolp_process
            self.frame_count=0
            
    
        def run(self):
            print("hey")
            cur_time=time.time()
    
            while True:
                if not stop_stream:
                   if self.dolp_process:
                     if self.window.started:
                        if not self.window.updated_frame_flag:
                            # print("waitingg")
                            pass
                        else:          
                            print("heyyy")
                            print("started processing image")
                            if self.frame_count < sys.maxsize:
                                self.frame_count+=1
                                print("dolp_process:",self.frame_count)
                            else:
                                self.frame_count==0
                            
                            if self.frame_count %5==0:
                                print("dolp_process_enter:",self.frame_count)    
                                try:
                                    print("printstillhere")
                                    im_I=np.copy(self.window.last_frame)
                                except:
                                    print("Some fault happening")
                                    # print("Frame got is: ", self.window.last_frame)
                                    continue
                                # print(self.window.last_frame)
                                self.window.updated_frame_flag=False
                                m,n = np.shape(im_I)
                                print(m,"  ",n)
                          
                                
                                im_I= im_I[0::3,0::2]
                             
                                print("check0")
                                x=len(im_I) - 1
                                y=len(im_I[0]) -1
                                print("x ",x, "y ", y, " m ",m, "n ",n)
    
            #### save the DOLP image
    
    
                                DOLP=np.array(DOLP*255, dtype=(np.uint8))
    
                                
    		
                                height,width,channel = np.shape(DOLP)
                                bytesPerLine= channel*width
    
                                convert_to_qt_fmt = QImage(DOLP.data, width, height, bytesPerLine, QImage.Format_RGB888)
                        
                                Pic=convert_to_qt_fmt.scaled(640, 480, Qt.KeepAspectRatio)
                                self.image_update_dolp.emit(Pic)
    
    if __name__ == '__main__':
        app = QApplication([])
        window = StartWindow()
        window.show()
        app.exit(app.exec_())
    
    jsulmJ 1 Reply Last reply
    0
    • K Kolappan

      I am getting Segmentation fault (core dumped) error when I try to run my code. It is not always but most of the times, but when the code runs, it does smoothly without any errors.
      The code basically gets the camera feed and displays it in one window and in another window it is being processed and displayed. After debugging it, I can see that the code throws in an error after the line im_I=np.copy(self.window.last_frame). I think this might be the issue because 1) There were no print statements were printed after this line.

      The op was

      hello
      hey
      Hellooo
      camera 1
      heyyy
      started processing image
      dolp_process: 1
      heyyy
      started processing image
      dolp_process: 2
      heyyy
      started processing image
      dolp_process: 3
      heyyy
      started processing image
      dolp_process: 4
      heyyy
      started processing image
      dolp_process: 5
      dolp_process_enter: 5

      samplecode.text

      from PyQt5.QtGui import QImage, QPixmap, qRgb
      import numpy as np
      import cv2
      from PyQt5.QtCore import Qt, QThread, QTimer, pyqtSignal
      from PyQt5.QtWidgets import QLabel, QMainWindow, QSpinBox, QWidget, QPushButton, QVBoxLayout, QApplication, QSlider, QGridLayout
      import time
      import sys
      
      stop_stream= True
      gray_color_table = [qRgb(i, i, i) for i in range(256)]
      path='C:\\Users\\VLV\\Desktop\\frame.png'
      
      def process_dolp(camera):
          while(True):
             print("heyyaa")
      
      class StartWindow(QMainWindow):
      
          save_image=False
          def __init__(self, camera = None):
              super(StartWindow,self).__init__()
              self.camera = camera
              self.last_frame=None 
              self.started = False
              self.central_widget = QWidget()
              self.button_frame = QPushButton('Acquire Frame', self.central_widget)
              self.button_start = QPushButton('Start Stream', self.central_widget)
              self.button_stop = QPushButton('Stop Stream', self.central_widget)
              self.image_view = QLabel()
              self.dolp_image_view = QLabel()
              self.brightness=QLabel()
              self.sp=QSpinBox()
              self.sp.setRange(0,1000000)
              self.sp.setValue(self.camera.pixel_tol_val)
              self.brightness.setText("Tolerance level")
              # self.ex=QSpinBox()
              # self.exposure.setText("Exposure level")
              self.fps_box=QLabel() 
              self.fps_box.setText('Fps : '+str(self.camera.fps))
      
              self.layout = QGridLayout(self.central_widget)
              self.layout.addWidget(self.button_frame,1,3)
              self.layout.addWidget(self.button_start,1,1)
              self.layout.addWidget(self.button_stop,1,5)
              self.layout.addWidget(self.image_view,6,6)
              self.layout.addWidget(self.dolp_image_view,9,9)
              self.layout.addWidget(self.brightness,3,1)
              # self.layout.addWidget(self.exposure,3,2)
              self.layout.addWidget(self.sp,4,1)
              self.layout.addWidget(self.fps_box, 4, 2)
              # self.layout.addWidget(self.ex,4,2)
              self.setCentralWidget(self.central_widget)
      
              self.button_frame.clicked.connect(self.save_images)
              self.button_start.clicked.connect(self.start_stream)
              self.button_stop.clicked.connect(self.stop_stream)
              self.sp.valueChanged.connect(self.update_pixel_tol)
              self.thread = QThread()
              self.worker = MovieThread(self, self.camera)
              self.worker.moveToThread(self.thread)
              self.worker.image_update.connect(self.update_image)
      
              self.thread.started.connect(self.worker.run)
              self.thread.start()
              time.sleep(2)
              self.thread1 = QThread()
              self.worker1 = ProcessThread(self, self.camera,True)
              self.worker1.moveToThread(self.thread1)
              self.worker1.image_update_dolp.connect(self.update_image_dolp)
      
              self.thread1.started.connect(self.worker1.run)
              self.thread1.start()
              self.start_stream()
      
          def save_images(self):
              if not stop_stream:
                  self.camera.save_img=True
              else:
                  print("First you need to start the stream")
      
          def update_image(self, Image):
      
              self.image_view.setPixmap(QPixmap.fromImage(Image))
              #self.last_frame=Image
      
          def update_image_dolp(self, Image):
              print("Inside heree")
              print(type(Image))
              self.dolp_image_view.setPixmap(QPixmap.fromImage(Image))
              #self.last_frame=Image
      
      
          def update_movie(self):
              self.image_view.setImage(self.camera.last_frame.T)
      
          def update_pixel_tol(self, value):  
              self.camera.set_pixel_tol(value)
      
          def start_stream(self):
              global stop_stream
              stop_stream=False
              self.button_start.setStyleSheet("background-color: yellow")
      
      
          def stop_stream(self):
              global stop_stream
              stop_stream=True
      
              # self.update_timer.start(30)
      
              while not stop_stream:
                  self.update_image(self)
                  
          def update_fps(self):
              self.fps_box.setText('Fps : '+str(self.camera.fps))
      
      
      class MovieThread(QThread):
          image_update=pyqtSignal(QImage)
          image_update_dolp=pyqtSignal(QImage)
          def __init__(self, window1, camera, dolp_process=False):
              super(MovieThread,self).__init__()
              self.camera = camera
              self.window=window1
              self.dolp_process = dolp_process
              self.frame_count=0
              
      
          def run(self):
              print("hello")
              cur_time=time.time()
      
              while True:
                  if not stop_stream:
                     if not self.dolp_process:
                        with self.camera.cap.start_stream(1):
                          print("Hellooo")
                          start=time.time()
                          self.window.update_fps()
                          image_buffer = self.camera.cap.get_buffer()
                          nparray_reshaped = np.ctypeslib.as_array(image_buffer.pdata,(image_buffer.height,image_buffer.width))
                          output= nparray_reshaped[0::3,0::2]
                          frame = output
                      
                          #if len(self.camera.buffer)<self.camera.num_of_img:
                          #    self.camera.buffer.append(nparray_reshaped)
                          #else:
                          #    for iter in range(len(self.camera.buffer)-1):
                          #        self.camera.buffer[iter]=self.camera.buffer[iter+1]
                          #    self.camera.buffer[self.camera.num_of_img-1]=(nparray_reshaped)
                          #self.camera.save_image()
      
                            #frame=nparray_reshaped
                         
                          self.window.updated_frame_flag = False
                      #frame=cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
                          self.window.last_frame = frame
                          self.window.updated_frame_flag = True
                          self.frame_count+=1
                          print("camera",self.frame_count)
                          # print(type(frame))
                          # print("Storing frame of size : ", np.shape(frame))
                          frame=nparray_reshaped                      
                          flipped_img=frame
                      #flipped_img = cv2.flip(frame,1)
                          convert_to_qt_fmt= QImage(flipped_img.data, flipped_img.shape[1], flipped_img.shape[0],QImage.Format_Grayscale8)
                          Pic=convert_to_qt_fmt.scaled(640, 480, Qt.KeepAspectRatio)
                          self.window.last_Pic=Pic
                          self.window.started=True
                      # Pic.setColorTable(gray_color_table)
      
                          self.image_update.emit(Pic)
                          time_taken=time.time()-start
                          self.camera.fps=int(1/time_taken)
      
      class ProcessThread(QThread):
          image_update=pyqtSignal(QImage)
          image_update_dolp=pyqtSignal(QImage)
          def __init__(self, window1, camera, dolp_process=False):
              super(ProcessThread,self).__init__()
              self.camera = camera
              self.window=window1
              self.dolp_process = dolp_process
              self.frame_count=0
              
      
          def run(self):
              print("hey")
              cur_time=time.time()
      
              while True:
                  if not stop_stream:
                     if self.dolp_process:
                       if self.window.started:
                          if not self.window.updated_frame_flag:
                              # print("waitingg")
                              pass
                          else:          
                              print("heyyy")
                              print("started processing image")
                              if self.frame_count < sys.maxsize:
                                  self.frame_count+=1
                                  print("dolp_process:",self.frame_count)
                              else:
                                  self.frame_count==0
                              
                              if self.frame_count %5==0:
                                  print("dolp_process_enter:",self.frame_count)    
                                  try:
                                      print("printstillhere")
                                      im_I=np.copy(self.window.last_frame)
                                  except:
                                      print("Some fault happening")
                                      # print("Frame got is: ", self.window.last_frame)
                                      continue
                                  # print(self.window.last_frame)
                                  self.window.updated_frame_flag=False
                                  m,n = np.shape(im_I)
                                  print(m,"  ",n)
                            
                                  
                                  im_I= im_I[0::3,0::2]
                               
                                  print("check0")
                                  x=len(im_I) - 1
                                  y=len(im_I[0]) -1
                                  print("x ",x, "y ", y, " m ",m, "n ",n)
      
              #### save the DOLP image
      
      
                                  DOLP=np.array(DOLP*255, dtype=(np.uint8))
      
                                  
      		
                                  height,width,channel = np.shape(DOLP)
                                  bytesPerLine= channel*width
      
                                  convert_to_qt_fmt = QImage(DOLP.data, width, height, bytesPerLine, QImage.Format_RGB888)
                          
                                  Pic=convert_to_qt_fmt.scaled(640, 480, Qt.KeepAspectRatio)
                                  self.image_update_dolp.emit(Pic)
      
      if __name__ == '__main__':
          app = QApplication([])
          window = StartWindow()
          window.show()
          app.exit(app.exec_())
      
      jsulmJ Offline
      jsulmJ Offline
      jsulm
      Lifetime Qt Champion
      wrote on last edited by
      #2

      @Kolappan It looks like your thread (MovieThread) is modifying UI (self.window.update_fps())! This is only allowed from main thread. Use signals/slots to communicate between main thread and the other threads.

      https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      1

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved