title: Python montage a plot on OpenCV image and record as video
body: <p>Assume that you have a temperature data with sampling rate 512. I want to record this data by synchronized with the camera images. The resulting record going to be just a video file. </p>
  
  <p>I can plot this data with matplotlib and pyqtgraph. </p>
  
  <p>I did it with matplotlib but video sampling rate is decreasing. Here is the code with random incoming data.</p>
  
  <pre><code>import cv2
  import numpy as np
  import matplotlib.pyplot as plt
  
  cap = cv2.VideoCapture(0) # video source: webcam
  fourcc = cv2.cv.CV_FOURCC(*'XVID') # record format xvid
  out = cv2.VideoWriter('output.avi',fourcc, 1, (800,597)) # output video : output.avi
  t = np.arange(0, 512, 1)# sample time axis from 1 to 512
  
  while(cap.isOpened()): # record loop
      ret, frame = cap.read()# get frame from webcam
      if ret==True:
          nse = np.random.randn(len(t))# generate random data squence
          plt.subplot(1, 2, 1)# subplot random data
          plt.plot(t, nse)
          plt.subplot(1, 2, 2)# subplot image
          plt.imshow(frame)
          # save matplotlib subplot as last.png
          plt.savefig("last.png")
          plt.clf()
          img=cv2.imread("last.png") # read last.png
          out.write(img) # record last.png image to output.avi 
          cv2.imshow('frame',img)
  
          if cv2.waitKey(1) &amp; 0xFF == ord('q'): # exit with press q button in frame window
              break
      else:
          break
  cap.release() # relase webcam
  out.release() # save video
  cv2.destroyAllWindows() # close all windows
  </code></pre>