Search code examples
pythonmultithreadingpyqtqthread

threading method in imageprocessing PyQt application


I develop a program which is constantly "watching" a specific folder, and when some image is copied into that folder, a function is called from another class and start the processing. The problem that these images are huge so whenever that image processing function starts, the ui freezes until the end of the process. I learnt that QThread might be the solution, but I cannot figure it out how to apply when I have many function in the class...

To be more specific, please, see the order of the steps.

class Main(QtGui.QMainWindow):
    def __init__():

    functions = Functions()
    ...
    self.something.signal.connect(self.functions.doStuff)

class Functions(QtCore.QObject):
    def __init__():

    imProc = ImageProcessing() 

    def doStuff():
        initialImage = loadimage(...)
        processedImage = imProc.process1(initialImage)

class ImageProcessing(QtCore.QObject) 
    def __init__(): 

    def process1(original_image):
        do maximum likelihood on the image
        return segmented image

    def process2(original_image):

        do another image processing task
        return segmented image

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    main = Main()
    main.show()
    main.exec_()

The problem is when process1() is running the main window freezes...could you please advise how to run the process1() in the background separately from the ui?

Thanks in advance!


Solution

  • OK, so I figured it out. I give a generic description how I solved it:

    First here is my ImageProcessing class...

    class ImageProcess(QtCore.QThread):
        def __init__(self):
            QtCore.QThread.__init__(self)
    
        def __del__(self):
            self.exiting = True
            self.wait()
    
        def run(self):
            #machine learning algorithm, which results a processed image...
            self.emit( QtCore.SIGNAL('image'), processedImage) 
            return 
    

    The I have my Functions class...

    class Functions(QtCore.QObject):
        def __init__():
    
            self.improc = ImageProcess()
            self.connect(self.improc, SIGNAL("image"), self.processImage)
    
            self.segmented_image = []
    
            self.improc.setPath(self.image)
            self.improc.start()
    
        def processImage(self,seg_img):    
            self.segmented_image = seg_img
    

    and then QMainWindow is set up as usual...

    Hope it helps for somenone who is srtuggeling with Qthread, signal-slots application...