Write Frames With Non-standard Resolution To Video In Opencv
Solution 1:
For me, this code does work, but MJPG does round the odd resolution to an even resolution. H264 did not work with that resolution at all.
int main(int argc, char* argv[])
{
// start camera
cv::VideoCapture cap(0);
// read a single image to find camera resolution
cv::Mat image;
cap >> image;
if (image.empty())
{
std::cout << "Could not find/open camera. Press Enter to exit." << std::endl;
std::cin.get();
return0;
}
cv::Size targetSize(199, 171);
cv::VideoWriter writer("out.avi", CV_FOURCC('M','J','P','G'), 25, targetSize, true); // does create a 198x170 video file.//cv::VideoWriter writer("out.avi", -1, 25, targetSize, true); // does not work for x264vfw for example with an error message.while (cv::waitKey(30) != 'q')
{
cap >> image;
if (!image.empty())
{
cv::imshow("captured image", image);
// resize the actual image to a target size
cv::Mat writableImage;
cv::resize(image, writableImage, targetSize);
writer.write(writableImage);
}
}
// release the camera
cap.release();
writer.release();
std::cout << "Press Enter to exit." << std::endl;
std::cin.get();
return0;
}
In general, many codecs are restricted to some pixel-block-constraints like having a multiple of 2, 4, 8, 16 or 32 in each dimension. Either because of the algorithm itself or some hardware instruction optimizations.
Solution 2:
cv2.VideoWriter("video_out.avi", fourcc, 25, (173, 99))
creates a writer for frames of size 173x99 (width x height).
frame_out
is a frame of size 99x173 (frame is indexed [y, x]).
Change the indexing to write matching frame sizes.
Solution 3:
In OSX environment:
- OSX: High Sierra (10.13.6)
- Python: 3.6.3
- Open CV (using prebuilt python pck): opencv-python-headless 4.1.0.25
The only combination that worked for me was mp4 wrapper (OSX doesn't love avi) and mp4v
codec. Also tried avc1
but it wouldn't write a non standard sized frame
codec = 'mp4v'fourcc = cv2.VideoWriter_fourcc(*codec)
size = ( 1000 , 500 )
fps = 15writer = cv2.VideoWriter('filename.mp4', fourcc, fps, size, True)
Post a Comment for "Write Frames With Non-standard Resolution To Video In Opencv"