title: Recording video with Opencv Python Multithreading
body: <p>I am trying to record a video using opencv in python when doing multithreading within the thread that displays the stream on the window. I m fairly new to multithreading and I am not sure what is the reason I am unable to get a video recorded. I save a file but it does not have the stream in it. Pointers greatly appreciated.This is my code:</p>
  
  <pre><code>import cv2
  import os
  import threading
  import shutil
  import json
  import re
  import datetime
  import time
  now=datetime.datetime.now()
  
  
  
  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)
      cam.set(cv2.CAP_PROP_FRAME_WIDTH, 480)
      cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
      if cam.isOpened():
          rval, frame = cam.read()
          frame_width = int(cam.get(3))
          frame_height = int(cam.get(4))
  
      else:
          rval = False
  
      while rval:
          cv2.namedWindow(previewName, cv2.WINDOW_NORMAL)
          if (camID == 2):
              frame= cv2.flip(frame,-1)
         # cv2.setWindowProperty(previewName, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
          cv2.imshow(previewName, frame)
        # cam.set(CV_CAP_PROP_SETTINGS, 0)
          rval, frame = cam.read()
  
          key = cv2.waitKey(20)
          if key == 115 :
              Cam1="Cam"+str(camID)+"_"+timestr
              ts=datetime.datetime.now()
              filename="{}.avi".format(Cam1+ts.strftime("%Y%m%d_%H-%M-%S"))
              out=cv2.VideoWriter(filename,cv2.VideoWriter_fourcc('M','J', 'P','G'),10,(480,720))
              out.write(frame)
              if key == 27:
                print("Stopping recording")
                break
          if key == 27:  # exit on ESC
              break
      cv2.destroyWindow(previewName)
  
  # Create threads as follows
  thread1 = camThread("Camera 1", 0)
  thread2 = camThread("Camera 2", 2)
  thread3 = camThread("Camera 3", 3)
  timestr=str(now.strftime("%Y%m%d_%H-%M-%S"))
  
  print("Working Directory:")
  print(timestr)
  
  #thread1.start()
  thread2.start()
  thread3.start()
  print()
  print("Active threads", threading.activeCount())
  </code></pre>