【问题标题】:Multithreaded cv2.imshow() in Python does not workPython 中的多线程 cv2.imshow() 不起作用
【发布时间】:2017-06-15 21:21:28
【问题描述】:

我有两个摄像头(使用 OpenNI,我每个摄像头有两个流,由同一个驱动 API 实例处理)并且希望有两个线程,每个线程独立地从每个摄像头捕获数据,即对于驱动程序 API,比如 cam_handler,我有两个流 depthrgb 每个摄像头,比如 cam_handler.RGB1_streamcam_handler.DEPTH1_stream

这是相同的代码:

import threading

def capture_and_save(cam_handle, cam_id, dir_to_write, log_writer, rgb_stream,
                     depth_stream, io):
    t = threading.currentThread()
    shot_idx = 0
    rgb_window = 'RGB' + str(cam_id)
    depth_window = 'DEPTH' + str(cam_id)
    while getattr(t, "do_run", True):
        if rgb_stream is not None:

            rgb_array = cam_handle.get_rgb(rgb_stream)
            rgb_array_disp = cv2.cvtColor(rgb_array, cv2.COLOR_BGR2RGB)
            cv2.imshow(rgb_window, rgb_array_disp)
            cam_handle.save_frame('rgb', rgb_array, shot_idx, dir_to_write + str(cam_id + 1))
            io.write_log(log_writer[cam_id], shot_idx, None)

        if depth_stream is not None:
            depth_array = cam_handle.get_depth(depth_stream)
            depth_array_disp = ((depth_array / 10000.) * 255).astype(np.uint8)
            cv2.imshow(depth_window, np.uint8(depth_array_disp))
            cam_handle.save_frame('depth', depth_array, shot_idx, dir_to_write + str(cam_id + 1))
        shot_idx = shot_idx + 1

        key = cv2.waitKey(1)
        if key == 27:  # exit on ESC
            break
    print "Stopping camera %d thread..." % (cam_id + 1)
    return

def main():
    ''' Setup camera threads '''
    cam_threads = []
    dir_to_write = "some/save/path"
    for cam in range(cam_count):
        cam = (cam + 1) % cam_count
        cv2.namedWindow('RGB' + str(cam))
        cv2.namedWindow('DEPTH' + str(cam))
        one_thread = threading.Thread(target=capture_and_save,
                                      name="CamThread" + str(cam + 1),
                                      args=(cam_cap, cam, dir_to_write,
                                            log_writer,
                                            rgb_stream[cam], depth_stream[cam], io,))
        cam_threads.append(one_thread)
        one_thread.daemon = True
        one_thread.start()

        try:
            while True:
                pass
                # cv2.waitKey(1)
        except KeyboardInterrupt:
            ''' Stop everything '''
            for each_thread in cam_threads:
                each_thread.do_run = False
                each_thread.join(1)
            cam_cap.stop_rgb(rgb_stream)
            cam_cap.stop_depth(depth_stream)

            ''' Stop and quit '''
            openni2.unload()
            cv2.destroyAllWindows()

if __name__ == '__main__':
    main()      

所以,我的问题是,如果我从代码中删除 cv2.imshow() 行,一切都会按预期运行,并且我会将两个相机输出保存到文件中。但是,使用 cv2.imshow() 行时,只创建了“空白”窗口,线程似乎“卡住”了,根本没有输出。
我尝试了几个建议,包括将 namedWindow 创建移动到主线程以及 capture_and_save 线程。我也尝试过在waitKey() 周围移动,因为据说OpenCV 只允许在主线程中使用waitKey()。但是没有区别。

【问题讨论】:

    标签: python multithreading opencv


    【解决方案1】:

    我通过使用可变对象解决了这个问题,将字典 cam_disp = {} 传递给线程并读取主线程中的值。 cv2.imshow() 保存在主线程中时效果最好,所以效果很好。我不确定这是否是执行此操作的“正确”方式,因此欢迎所有建议。

    【讨论】:

    【解决方案2】:

    尝试在您的线程目标capture_and_save 中移动cv2.namedWindow('RGB' + str(cam))

    【讨论】:

      【解决方案3】:

      cv2.imshow 函数不是线程安全的。 只需将cv2.namedWindow 移动到调用cv2.imshowthreading.Thread

      import cv2
      import threading
      
      def run():
          cap = cv2.VideoCapture('test.mp4')
          cv2.namedWindow("preview", cv2.WINDOW_NORMAL)
          while True:
              ret, frame = cap.read()
              if frame is None:
                  print("Video is over")
                  break
              cv2.imshow('preview', frame)
              cv2.waitKey(1)
          cap.release()
          cv2.destroyAllWindows()
      
      if __name__ == "__main__":
          thread = threading.Thread(target=run)
          thread.start()
          thread.join()
          print("Bye :)")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-23
        • 1970-01-01
        • 2018-08-12
        • 2015-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        相关资源
        最近更新 更多