此代码在Windows上有效,但在Linux上显示错误“未在主线程中创建QApplication”,如何解决,

时间:2018-10-16 05:04:22

标签: python image opencv

import cv2
import threading

class camThread(threading.Thread):
    def __init__(self, previewName, camID):

        threading.Thread.__init__(self)
        self.previewName = previewName
        self.camID = camID

    def run(self):

        print "Starting " + self.previewName
        camPreview(self.previewName, self.camID)

def camPreview(previewName, camID):
    cv2.namedWindow(previewName)
    cam = cv2.VideoCapture(camID)
    if cam.isOpened():  # try to get the first frame

        rval, frame = cam.read()

    else:

        rval = False
    while rval:

        cv2.imshow(previewName, frame)
        rval, frame = cam.read()
        key = cv2.waitKey(20)
        if key == 27:  

            break
    cv2.destroyWindow(previewName)

# Create two threads as follows

thread1 = camThread("Camera 1", 1)
thread2 = camThread("Camera 2", 2)

thread1.start()
thread2.start()

1 个答案:

答案 0 :(得分:0)

不要创建线程,namedWindowimshowdestroyWindow不得在线程中调用。

def preview(camera_ids):
    cameras = {}
    for name, id in camera_ids.items():
        cv2.namedWindow(name)
        cameras[name] = cv2.VideoCapture(id)
    while True:
        for name, cam in cameras.items():
            ok, frame = cam.read()
            if ok: cv2.imshow(name, frame)
        key = cv2.waitKey(20)
        if key == 27:  
            break
    for name in cameras:
        cv2.destroyWindow(name)

preview({"Camera 1": 1, "Camera 2": 2})