GUI冻结了其余的python代码

时间:2014-05-25 15:05:52

标签: python multithreading opencv user-interface

我在python中使用wx gui。和opencv对象检测。当我运行GUI时GUI会冻结其余的代码,当我关闭窗口代码时,我会发现很多问题>解决方案是创建一个线程来运行gui并在main方法中启动这个线程,但同样的问题仍然存在于这里是线程

class GuIthread(threading.Thread):

def __init__ (self):
    threading.Thread.__init__(self)

def run(self):
    gettext.install("app") # replace with the appropriate catalog name\
    global View

    app = MyApp(0)
    app.MainLoop()

然后这是主要方法

if __name__ == '__main__':
parser = OptionParser(usage = "usage: %prog [options] [filename|camera_index]")
parser.add_option("-c", "--cascade", action="store", dest="cascade", type="str", help="Haar cascade file, default %default", default = "../data/haarcascades/haarcascade_frontalface_alt.xml")
(options, args) = parser.parse_args()

cascade = cv.Load(options.cascade)
global Count

if len(args) != 1:
    parser.print_help()
    sys.exit(1)

input_name = args[0]
if input_name.isdigit():
    capture = cv.CreateCameraCapture(int(input_name))
else:
    capture = None

cv.NamedWindow("video", 1)

#size of the video
width = 600
height = 500

if width is None:
    width = int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH))
else:
    cv.SetCaptureProperty(capture,cv.CV_CAP_PROP_FRAME_WIDTH,width)

if height is None:
    height = int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT))
else:
    cv.SetCaptureProperty(capture,cv.CV_CAP_PROP_FRAME_HEIGHT,height)

if capture:
    frame_copy = None
    thread1 = myThread()
    thread1.start()
    threadGUI = GuIthread()
    threadGUI.start()
    threadGUI.join()
    frame_copy = None
    t0=time.time()
    while True:
        global frame 
        frame = cv.QueryFrame(capture)
      #  cv.SaveImage('pic.jpg', frame)
        t1=time.time()
        if (t1-t0) >= 10:
            thread1.run()
            t0=t1
            SendPic (frame)
            Count=0                

        if not frame:
            cv.WaitKey(0)
            break
        if not frame_copy:
            frame_copy = cv.CreateImage((frame.width,frame.height),
                                        cv.IPL_DEPTH_8U, frame.nChannels)

        if frame.origin == cv.IPL_ORIGIN_TL:
            cv.Copy(frame, frame_copy)
        else:
            cv.Flip(frame, frame_copy, 0)

        detect_and_draw(frame_copy, cascade)

        if cv.WaitKey(10) >= 0:
            break
else:
    image = cv.LoadImage(input_name, 1)
    detect_and_draw(image, cascade)
    cv.WaitKey(0)

cv.DestroyWindow("video")

显示gui和视频窗口,但代码不会运行,除非我关闭视窗开始的GUI窗口

我尝试的是 我添加了GUIthread.join()(在添加分段错误之前) 我尝试在一个方法中生成运行GUI的代码,并调用它,但是没有出现视频窗口会发生相同的结果。

1 个答案:

答案 0 :(得分:1)

首先,@ Mark是正确的,你从普通约定向后执行此操作,其中GUI在主线程中运行。您的代码正在阻止,因为您正在执行此操作

threadGUI = GuIthread()
threadGUI.start()
threadGUI.join()  # This blocks until threadGUI is complete.

threadGUI.join()调用将使您的程序阻塞,直到app.MainLoop()完成,直到您关闭GUI才会发生。