Here, we also normalize the pixel values to the range [0, 255].
Write each frame of the cv::Mat to the output video file using the write function of the VideoWriter object:
cpp
videoWriter.write(mat8bit);
Release the VideoWriter object to flush any buffered frames and close the output video file:
cpp
videoWriter.release();
Here's the complete code:
cpp
#include <opencv2/opencv.hpp>
int main() {
cv::Mat mat = ...; // your CV_16SC3 point type cv::Mat
cv::VideoWriter videoWriter;
std::string videoFile = "output.mp4";
int codec = cv::VideoWriter::fourcc('H','2','6','4');
double fps = 30.0;
cv::Size frameSize(mat.cols, mat.rows);
videoWriter.open(videoFile, codec, fps, frameSize, true);
cv::Mat mat8bit;
cv::convertScaleAbs(mat, mat8bit, 1.0 / 256.0, 0);
videoWriter.write(mat8bit);
videoWriter.release();
return 0;
}
User
I don't want to reduce bit size into 8 from 16. Can I encode CV_16SC3 as-is?
Assistant
Yes, you can encode a cv::Mat with CV_16SC3 point type as-is without reducing the bit size to 8-bit. However, you need to make sure that the output video codec supports this pixel format.
The H.264 codec is capable of encoding 16-bit video, but you need to make sure that your video player or decoder can handle it. Some players may not be able to display 16-bit video correctly.
Here's the modified code to encode cv::Mat with CV_16SC3 point type into a video using the H.264 codec:
cpp
#include <opencv2/opencv.hpp>
int main() {
cv::Mat mat = ...; // your CV_16SC3 point type cv::Mat
cv::VideoWriter videoWriter;
std::string videoFile = "output.mp4";
int codec = cv::VideoWriter::fourcc('H','2','6','4');
double fps = 30.0;
cv::Size frameSize(mat.cols, mat.rows);
videoWriter.open(videoFile, codec, fps, frameSize, true);
videoWriter.set(cv::VIDEOWRITER_PROP_NSTRIPES, 1); // reduce memory consumption
videoWriter.write(mat);
videoWriter.release();
return 0;
}
Note that the cv::VIDEOWRITER_PROP_NSTRIPES property is set to 1 to reduce memory consumption. This property controls the number of stripes used for parallel encoding of the video frames. Setting it to 1 can reduce the memory usage but may also affect the encoding performance. You can experiment with different values to find the optimal setting for your system.
User
Can I config codec for real time streaming profile?
Assistant
Yes, you can configure the H.264 codec to use real-time streaming profile for encoding video. The real-time streaming profile is optimized for low-latency and high-throughput video streaming applications, such as video conferencing, live streaming, and remote desktop.
To configure the H.264 codec for real-time streaming profile, you need to set the appropriate encoding parameters using the cv::VideoWriter::set function. Here's an example code:
Here, we set the following H.264 encoding parameters:
cv::VIDEOWRITER_PROP_PROFILE: set the video codec profile to "AVC1", which is the real-time streaming profile.
cv::VIDEOWRITER_PROP_H264_MV_PREDICTION_MODE: set the motion vector prediction mode to "fast".
cv::VIDEOWRITER_PROP_H264_MAX_QP and cv::VIDEOWRITER_PROP_H264_MIN_QP: set the maximum and minimum quantization parameter values to 0 and 51, respectively, to allow for higher quality and faster encoding.
cv::VIDEOWRITER_PROP_H264_I_FRAME_PERIOD: set the I-frame period to 30 frames to reduce latency and improve random access.
cv::VIDEOWRITER_PROP_H264_LEVEL: set the H.264 level to 3.1 to support up to 1080p resolution at 30fps.
`cv::VIDEOWR
User
I dont have cv::VIDEOWRITER_PROP_*. Where is it defined?
Assistant
The cv::VIDEOWRITER_PROP_* constants are defined in the opencv2/videoio/vidoeio.hpp header file in OpenCV.
Here's an example code that shows how to use cv::VIDEOWRITER_PROP_* constants to set the encoding properties of a cv::VideoWriter object:
cpp
#include <opencv2/opencv.hpp>
int main() {
cv::Mat mat = ...; // your CV_16SC3 point type cv::Mat
cv::VideoWriter videoWriter;
std::string videoFile = "output.mp4";
int codec = cv::VideoWriter::fourcc('H','2','6','4');
double fps = 30.0;
cv::Size frameSize(mat.cols, mat.rows);
videoWriter.open(videoFile, codec, fps, frameSize, true);
// configure H.264 codec for real-time streaming profile
videoWriter.set(cv::VIDEOWRITER_PROP_PROFILE, cv::CAP_PROP_FOURCC('A', 'V', 'C', '1'));
videoWriter.set(cv::VIDEOWRITER_PROP_H264_MV_PREDICTION_MODE, cv::VideoWriter::H264_MV_PMODE_FAST);
videoWriter.set(cv::VIDEOWRITER_PROP_H264_MAX_QP, 0);
videoWriter.set(cv::VIDEOWRITER_PROP_H264_MIN_QP, 0);
videoWriter.set(cv::VIDEOWRITER_PROP_H264_MAX_QP, 51);
videoWriter.set(cv::VIDEOWRITER_PROP_H264_I_FRAME_PERIOD, 30);
videoWriter.set(cv::VIDEOWRITER_PROP_H264_LEVEL, 31);
videoWriter.set(cv::VIDEOWRITER_PROP_H264_PROFILE, cv::VideoWriter::H264_PROFILE_HIGH);
videoWriter.set(cv::VIDEOWRITER_PROP_H264_PARTITIONS, cv::VideoWriter::H264_PARTITIONS_AUTO);
videoWriter.set(cv::VIDEOWRITER_PROP_H264_REPEAT_SEQ_HEADER, true);
videoWriter.set
User
I don't have cv::VIDEOWRITER_PROP_H264_*.
Assistant
If you don't have the cv::VIDEOWRITER_PROP_H264_* properties available in your version of OpenCV, it's likely that your version of OpenCV was compiled without H.264 encoding support.
To enable H.264 encoding support in OpenCV, you need to ensure that your version of OpenCV is built with the WITH_FFMPEG and WITH_XINE flags enabled during the configuration stage of the OpenCV build process.
If you're using OpenCV 4.0 or later, you can check whether H.264 encoding support is available by calling the cv::VideoWriter::isOpened() function after creating a cv::VideoWriter object with H.264 encoding parameters. If the video writer is successfully opened, H.264 encoding support is available. If the video writer fails to open, H.264 encoding support is not available.
User
I think my installation of opencv compiled without support of H264. Im using ubuntu 22.04. How can I make it to support it?
Assistant
To add H.264 encoding support to your OpenCV installation on Ubuntu 22.04, you need to rebuild OpenCV with the appropriate libraries and codecs installed. Here are the steps you can follow:
Install the necessary dependencies for building OpenCV with H.264 support:
This will enable H.264 encoding support by building OpenCV with FFmpeg and Xine libraries.
5. Compile and install OpenCV:
go
make -j$(nproc)
sudo make install
sudo ldconfig
After following these steps, you should have a version of OpenCV installed on your system with H.264 encoding support.
User
Can I use gstreamer to encode my images?
Assistant
Yes, you can use GStreamer to encode your images into video. GStreamer is a popular open-source multimedia framework that supports a wide range of codecs and containers.
To use GStreamer to encode your images, you can use the appsink and videoconvert plugins to convert your cv::Mat images into GStreamer buffers, and the x264enc plugin to encode the video using the H.264 codec. Here's an example pipeline that demonstrates how to encode a sequence of cv::Mat images into a H.264-encoded video using GStreamer:
scss
cv::Mat frame;
// ... Load or capture the frame ...
// Create a GStreamer pipeline
std::string pipeline = "appsrc ! videoconvert ! x264enc ! mp4mux ! filesink location=output.mp4";
GstElement *pipeline = gst_parse_launch(pipeline.c_str(), NULL);
// Get the appsrc element from the pipeline
GstElement *appsrc = gst_bin_get_by_name(GST_BIN(pipeline), "appsrc");
// Set the format and properties of the appsrc element
GstCaps *caps = gst_caps_new_simple("video/x-raw",
"format", G_TYPE_STRING, "BGR",
"width", G_TYPE_INT, frame.cols,
"height", G_TYPE_INT, frame.rows,
"framerate", GST_TYPE_FRACTION, 30, 1, NULL);
gst_app_src_set_caps(GST_APP_SRC(appsrc), caps);
g_object_set(G_OBJECT(appsrc), "is-live", TRUE, "format", GST_FORMAT_TIME, NULL);
// Loop over the frames and push them into the pipeline
for (int i = 0; i < num_frames; ++i) {
// ... Load or capture the frame ...
// Convert the OpenCV Mat to a GStreamer buffer
GstBuffer *buffer = gst_buffer_new_wrapped(frame.data, frame.total() * frame.elemSize(), 0, frame.total() * frame.elemSize());
// Push the buffer into the appsrc element
GstFlowReturn ret = gst_app_src_push_buffer(GST_APP_SRC(appsrc), buffer);
if (ret != GST_FLOW_OK) {
// Handle the error
}
}
// Stop the pipeline and clean up
gst_element_set_state(pipeline, GST_STATE_NULL);
gst_object_unref(GST_OBJECT(pipeline));
In this example, the pipeline consists of an appsrc element that receives the cv::Mat images, a videoconvert element that converts the image format to a format that the x264enc element can handle, the x264enc element that encodes the video using the H.264 codec, an mp4mux element that muxes the encoded video into a MP4 container, and a filesink element that writes the encoded video to a file.
Note that this is just a simple example pipeline, and you may need to customize it to suit your specific requirements. You can experiment with different GStreamer plugins and pipeline configurations to achieve the desired video encoding settings.
User
Can I use cv::VideoWriter with gstreamer?
Assistant
Yes, you can use cv::VideoWriter with GStreamer backend to encode video using OpenCV. OpenCV provides support for GStreamer backend through the GSTREAMER API.
Here's an example code snippet that demonstrates how to use cv::VideoWriter with GStreamer backend to encode a video using the H.264 codec:
scss
#include <opencv2/opencv.hpp>
int main() {
// Open the video capture device or file
cv::VideoCapture cap("video.mp4");
// Create a VideoWriter object with GStreamer backend
cv::VideoWriter writer("appsrc ! videoconvert ! x264enc ! mp4mux ! filesink location=output.mp4", cv::CAP_GSTREAMER, 0, 30, cv::Size(cap.get(cv::CAP_PROP_FRAME_WIDTH), cap.get(cv::CAP_PROP_FRAME_HEIGHT)));
// Loop over the frames and write them to the VideoWriter object
cv::Mat frame;
while (cap.read(frame)) {
writer.write(frame);
}
// Release the VideoCapture and VideoWriter objects
cap.release();
writer.release();
}
In this example, we create a cv::VideoWriter object with the GStreamer pipeline as the output filename, using the cv::CAP_GSTREAMER API to specify the GStreamer backend. The appsrc, videoconvert, x264enc, mp4mux, and filesink plugins are used to create a GStreamer pipeline that converts the input frames to H.264-encoded video and writes the output to a MP4 file.
Note that you can customize the GStreamer pipeline to suit your specific requirements, such as changing the codec, adjusting the bitrate, or adding additional plugins.
User
I've got GStreamer warning: error opening writer pipeline: no element "appsrc". Is it ok?
Assistant
No, it's not okay. The appsrc element is required in the GStreamer pipeline to provide the frames to the pipeline for encoding. The error message you're seeing suggests that the appsrc element is not available on your system.
You can try installing the necessary GStreamer plugins that provide the appsrc element. On Ubuntu, you can try installing the gstreamer1.0-plugins-base package which includes the basic set of GStreamer plugins:
csharp
sudo apt-get install gstreamer1.0-plugins-base
If that doesn't work, you can try installing the libgstreamer-plugins-base1.0-dev package, which includes development headers and additional plugins:
After installing the necessary packages, you can try running your code again to see if the appsrc element is now available.
User
Now i've got GStreamer warning: error opening writer pipeline: no element "mp4mux". What should I have to install?
Assistant
The mp4mux element is part of the gstreamer1.0-plugins-good package, which provides a set of good quality GStreamer plugins, including the mp4mux element that is used in the GStreamer pipeline for MP4 file muxing.
To install the package on Ubuntu, you can run:
csharp
sudo apt-get install gstreamer1.0-plugins-good
After installing the gstreamer1.0-plugins-good package, you can try running your code again to see if the mp4mux element is now available.
User
I've got GStreamer warning: cvWriteFrame() needs images with depth = IPL\_DEPTH\_8U and nChannels = 3. I think this is caused by my cv::Mat has CV_16SC3 pixel type. I dont want to change my pixel type and want to encode with 16bit color depth. What can I do? modifying gstreamer pipeline?
Assistant
Yes, you can modify the GStreamer pipeline to accept CV_16SC3 pixel type frames and convert them to the appropriate format for encoding. You can use the videoconvert element in the pipeline to perform the color format conversion.
Here's an example of how you can modify the GStreamer pipeline to accept CV_16SC3 pixel type frames:
In this modified pipeline, we add the videoconvert element after the appsrc element to convert the input frames to the appropriate format for encoding. We specify the input format as video/x-raw with the format=BGR option, and the output format as video/x-raw with the format=GRAY16_LE option, which specifies a grayscale 16-bit little-endian format.
Note that you may need to adjust the output format and codec settings in the pipeline to suit your specific requirements. Also, keep in mind that encoding video with 16-bit color depth can result in larger file sizes and slower encoding times compared to 8-bit color depth.
User
It is not grayscale image. My image has 16bit color depth and has 3 channels. Also when the video is decoded, it must be also 16bit color depth with 3 channels. Please write gstreamer pipeline for this.
Assistant
My apologies for the confusion. To encode a color image with 16-bit depth and 3 channels, you can modify the GStreamer pipeline to use the video/x-raw format with a pixel format of BGR16-LE. You can then use the x264enc element to encode the video using the H.264 codec.
Here's an example of how you can modify the GStreamer pipeline to encode a cv::Mat with CV_16SC3 pixel type:
In this modified pipeline, we add the video/x-raw format with a pixel format of BGR16-LE to specify that the input frames have 16-bit depth and 3 channels. We then use the x264enc element to encode the video using the H.264 codec. Finally, we use the mp4mux element to create an MP4 container file and the filesink element to write the output to a file.
Note that you may need to adjust the output bitrate and other encoding parameters of the x264enc element to suit your specific requirements. Also, keep in mind that not all media players may support playback of video with 16-bit color depth, so it's important to test your output file with a variety of players to ensure compatibility.
User
Can you show me a code that initializes cv::VideoWriter with that pipeline expression?
Assistant
Sure, here's an example of how you can initialize a cv::VideoWriter object with the modified GStreamer pipeline expression:
c++
#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
int main() {
// OpenCV video writer parameters
int width = 640;
int height = 480;
double fps = 30.0;
cv::Size frameSize(width, height);
int fourcc = cv::VideoWriter::fourcc('a', 'v', 'c', '1');
// GStreamer pipeline expression
std::string pipeline = "appsrc ! video/x-raw, format=BGR16-LE, width=" + std::to_string(width) + ", height=" + std::to_string(height) + " ! x264enc ! mp4mux ! filesink location=output.mp4";
// Initialize video writer with GStreamer pipeline expression
cv::VideoWriter writer(pipeline, fourcc, fps, frameSize, true);
// Check if video writer was successfully initialized
if (!writer.isOpened()) {
std::cerr << "Failed to open video writer" << std::endl;
return -1;
}
// Capture and encode video frames
cv::Mat frame(height, width, CV_16SC3, cv::Scalar(0, 0, 0)); // Example frame with 16-bit depth and 3 channels
for (int i = 0; i < 300; i++) {
// Encode video frame
writer.write(frame);
// Add delay between frames
cv::waitKey(1000 / fps);
}
// Release video writer
writer.release();
return 0;
}
In this example, we create a cv::VideoWriter object with the GStreamer pipeline expression as the first argument. We specify the video writer parameters, such as the width, height, and frame rate, and the codec to use for encoding (H.264, with the avc1 FourCC code). We then check if the video writer was successfully initialized and proceed to capture and encode video frames. Finally, we release the video writer to ensure that the output file is properly closed and written to disk.
User
I think fourcc must be cv::CAP_GSTREAMER. doesn't it?
Assistant
You're correct, my apologies for the confusion. When using GStreamer pipelines with cv::VideoWriter, you should pass cv::CAP_GSTREAMER as the fourcc parameter instead of a FourCC code. Here's the corrected example:
c++
#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
int main() {
// OpenCV video writer parameters
int width = 640;
int height = 480;
double fps = 30.0;
cv::Size frameSize(width, height);
// GStreamer pipeline expression
std::string pipeline = "appsrc ! video/x-raw, format=BGR16-LE, width=" + std::to_string(width) + ", height=" + std::to_string(height) + " ! x264enc ! mp4mux ! filesink location=output.mp4";
// Initialize video writer with GStreamer pipeline expression
cv::VideoWriter writer(pipeline, cv::CAP_GSTREAMER, 0, fps, frameSize, true);
// Check if video writer was successfully initialized
if (!writer.isOpened()) {
std::cerr << "Failed to open video writer" << std::endl;
return -1;
}
// Capture and encode video frames
cv::Mat frame(height, width, CV_16SC3, cv::Scalar(0, 0, 0)); // Example frame with 16-bit depth and 3 channels
for (int i = 0; i < 300; i++) {
// Encode video frame
writer.write(frame);
// Add delay between frames
cv::waitKey(1000 / fps);
}
// Release video writer
writer.release();
return 0;
}
Here, we pass cv::CAP_GSTREAMER instead of a FourCC code as the fourcc parameter. This tells cv::VideoWriter to use GStreamer for video encoding instead of OpenCV's internal codecs.