4

I've been playing around with v4l2 and I finally managed to connect to my laptop's camera and set it to stream.

At the moment I save the frames as 1.jpg, 2.jpg etc.

Thinking on a basic level, I need a storage container for those jpegs and then a video player runs the container contents in sequence and I get video.

I assume the video format is going to be my container.

How do I create and write to one?

icza
  • 389,944
  • 63
  • 907
  • 827
user3017869
  • 543
  • 2
  • 6
  • 16

1 Answers1

5

The easiest would be to save your JPEG images in a video file of format MJPEG, which is a simple video format consisting a series of JPEG images.

You may turn to different ready-to-use encoders to turn a series of JPEG images into an MJPEG (or any other format) video file, such as ffmpeg. Using ffmpeg, you could do it with the following command:

ffmpeg -r 2 -i "%02d.jpg" -vcodec mjpeg test.avi

If you want to do it in Go, you may use the dead-simple github.com/icza/mjpeg package (disclosure: I'm the author).

Let's see an example how to turn the JPEG files 1.jpg, 2.jpg, ..., 10.jpg into a movie file:

checkErr := func(err error) {
    if err != nil {
        panic(err)
    }
}

// Video size: 200x100 pixels, FPS: 2
aw, err := mjpeg.New("test.avi", 200, 100, 2)
checkErr(err)

// Create a movie from images: 1.jpg, 2.jpg, ..., 10.jpg
for i := 1; i <= 10; i++ {
    data, err := ioutil.ReadFile(fmt.Sprintf("%d.jpg", i))
    checkErr(err)
    checkErr(aw.AddFrame(data))
}

checkErr(aw.Close())
icza
  • 389,944
  • 63
  • 907
  • 827
  • Hey, I am really excited about the package you built. I just got home from work and tried it. I get an avi file but it does not play. VLC reports the following error. `[00007fe028009478] avi demux error: no key frame set for track 0` If you want to check the my code: [link](https://bitbucket.org/coder8/cam) – user3017869 Nov 21 '16 at 18:47
  • @user3017869 You have to keep open the `AviWriter` as long as you intend to add new image frames, and close it when you're done. Also, can you play the video with [mplayer](http://www.mplayerhq.hu/design7/news.html)? Because I tested it with mplayer and there were no errors (`sudo apt install mplayer`). – icza Nov 21 '16 at 22:35
  • @user3017869 Added an example program with images and result video. Please check that: [example](https://github.com/icza/mjpeg/tree/master/example) – icza Nov 21 '16 at 23:14
  • Total brainfart, I had the mjpeg.New func in the continuous for loop. And I ended up with a single frame video. Your solution worked gr8 from the very beginning. Ty – user3017869 Nov 22 '16 at 17:16