3

I am using raspberry pi to capture videos 24/7. I have been using picamera's recording function :

import picamera
camera = picamera.PiCamera()
camera.start_recording('output_file.h264')
camera.wait_recording(600)
camera.stop_recording()

This creates .h264 file.

Now, I am trying to do some things with captured frames (object detection etc.) and therefore need to use other methods to write videos, like opencv's VideoWriter.

Here's my main question: When using picamera, it does not care if the process was killed while recording. I.e. if the process was killed after 300 seconds(for any reasons), the output file still has 300 seconds of video, uncorrupted. However, when I used cv2.VideoWriter to save .mp4 file, when it was not properly released, the video file showed corrupted. What method can I use to write Videos that behaves like picamera?

Any other approaches are welcome too.

Phillip C
  • 81
  • 6

1 Answers1

3

mp4 files have a structure in them that describes the length of the video, what audio/video streams are contained, and how they are interleaved (chopped into pieces and mixed up).

when you kill the writing process, that header does not get written. the video file has become nearly useless. if you have a single stream, it may be recoverable.

a simple ".h264" file does not contain such a header. it's a single contiguous stream of H.264. that can be decoded with no issues.

you can try telling VideoWriter to use a different container format. try ".ts" instead of ".mp4". you can separately tell it the FOURCC of your desired codec (MJPG maybe).

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
  • Thank you so much. Saving in .ts file behaves just as I was hoping. Just to add one more thing, instead of MJPG, MPEG worked for me. – Phillip C Dec 04 '20 at 15:46
  • The `.ts` suffix is great for writing crash-safe video. Using `MPEG` fourcc works well (I'm on Ubuntu), but OpenCV will still complain that the tag is incompatible: `OpenCV: FFMPEG: tag 0x4745504d/'MPEG' is not supported with codec id 2 and format 'mpegts / MPEG-TS (MPEG-2 Transport Stream)'` Is there any fourcc that will not throw this error by OpenCV? ffprobe tells me the resulting .ts file has an mpeg2video video stream, so I've tried a number of different fourcc's (MJPG, MPEG, M2V1, MP2V, MPG1, MPG2, MPG4), all of them throw the same error. – w-m May 17 '22 at 17:42
  • `avc1` usually works. there are some other fourccs defined for use in MPEG containers but I don't know those for sure. `mp4v` should work too (H.263). https://stackoverflow.com/questions/30103077/what-is-the-codec-for-mp4-videos-in-python-opencv and https://en.wikipedia.org/wiki/MPEG-4_Part_14 (though that's MP4, which is different from mpeg transport streams) – Christoph Rackwitz May 17 '22 at 19:41