In OpenCV, using H.264 encoding to compress video files can be achieved through the cv2.VideoWriter class. Below is a specific example demonstrating how to use this class to save video captured from a camera with H.264 encoding to a file.
First, ensure that OpenCV is installed on your system. Additionally, since H.264 is a patented encoding format, you must ensure that OpenCV is configured with codecs that support H.264, such as ffmpeg or x264.
Here is a simple code example demonstrating how to capture video and save it with H.264 encoding:
pythonimport cv2 # Specify the output filename output_filename = 'output.mp4' # Set the video codec; for H.264, use 'X264' or adjust based on your environment fourcc = cv2.VideoWriter_fourcc(*'X264') # Create VideoWriter object, specifying filename, codec, frame rate, and resolution out = cv2.VideoWriter(output_filename, fourcc, 20.0, (640, 480)) # Use the first camera device cap = cv2.VideoCapture(0) if not cap.isOpened(): print("Unable to open camera") exit() while True: # Capture a video frame ret, frame = cap.read() if not ret: print("Unable to read frame, ending capture") break # Write the frame to the output file out.write(frame) # Display the frame cv2.imshow('frame', frame) if cv2.waitKey(1) == ord('q'): break # Release the camera and file handles, and close all windows cap.release() out.release() cv2.destroyAllWindows()
In this code, I first configure the H.264 encoding method (via the fourcc variable, using 'X264' or adjusting based on your environment). Then, initialize VideoWriter to write the video file, specifying the filename, codec, frame rate, and resolution.
Next, loop through capturing video frames from the camera and use out.write(frame) to write each frame to the specified output file. Finally, release all resources and close all windows.
Note that for the above code to run, OpenCV must be configured with ffmpeg or other libraries supporting H.264 encoding. Additionally, if you are using other operating systems or environments, you may need to install the appropriate codecs or adjust the fourcc codec settings.