6

Is there a solution to open a mp4 and overlay a graph (Matplotlib) or something like this?

Something like this

Balzer82
  • 949
  • 4
  • 10
  • 21

1 Answers1

4

You can obtain the frames from the video using openCV, as in this example, and plot a graph over the top with matplotlib, e.g.

import cv2
import matplotlib.pyplot as plt
import numpy as np

filename = './SampleVideo.mp4'
cap = cv2.VideoCapture(filename)

try:
    frames = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
    width  = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT))
except AttributeError:
    frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    width  = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

fig, ax = plt.subplots(1,1)
plt.ion()
plt.show()

#Setup a dummy path
x = np.linspace(0,width,frames)
y = x/2. + 100*np.sin(2.*np.pi*x/1200)

for i in range(frames):
    fig.clf()
    flag, frame = cap.read()

    plt.imshow(frame)
    plt.plot(x,y,'k-', lw=2)
    plt.plot(x[i],y[i],'or')
    plt.pause(0.01)

    if cv2.waitKey(1) == 27:
        break
    

I got the video from here.

Ed Smith
  • 11,838
  • 2
  • 41
  • 53
  • I got your example working. How would I go about saving the video file with the graphs drawn on it? – tylerjw Jan 10 '16 at 23:31
  • Hi @tylerjw, you could use cv2 `VideoWriter` or `matplotlib` `manimation` writer. Personally I'd save frames to file and then build a video from images, using `savefig('./out{:05d}'.format(i).png` to get a range of file with successive names and then put together with `ffmpeg` or something... – Ed Smith Jan 11 '16 at 09:33
  • Thank you. I found that matplotlib is just too slow for my application(not real time, but faster than several seconds/frame) so I'm going to try to write it using opencv and their drawing tools. – tylerjw Jan 12 '16 at 01:06
  • The site of the video has a warning not to proceed from my browser ;( – KansaiRobot Oct 18 '21 at 11:52
  • Hi @KansaiRobot, just updated link – Ed Smith Oct 19 '21 at 09:16
  • somehow it doesn't work. `AttributeError: 'module' object has no attribute 'cv'`. I modified it to `cv2.CAP_PROP_FRAME_COUNT`. However I don't see neither plot or video – KansaiRobot Oct 19 '21 at 10:19
  • I tried to modify it. Didn't work :( – KansaiRobot Oct 19 '21 at 11:04
  • Looks like cv has changed, added exception handle – Ed Smith Oct 20 '21 at 09:30
  • Hi @KansaiRobot, does it work now it's updated? – Ed Smith Oct 21 '21 at 08:41
  • I have run it quickly and it seems it works. Sorry I will check it better in the weekend – KansaiRobot Oct 21 '21 at 12:35
  • I am wondering if there is a way to not only show it but also putting back into a video format. (so that it can be played later) – KansaiRobot Oct 21 '21 at 15:10