关于这个问题:图像大小调整后OpenCV VideWriter不起作用
是否可以使用 opencv 的cv2.VideoWriter
创建具有"非标准"视频分辨率(即非标准纵横比(的视频?到目前为止我的代码:
fourcc = cv2.VideoWriter_fourcc(*'XVID')
video_out = cv2.VideoWriter("video_out.avi", fourcc, 25, (99, 173))
cap = cv2.VideoCapture("video_in.avi")
while(cap.isOpened()):
ret, frame = cap.read()
frame_out = frame[50:50+173,400:400+99]
video_out.write(frame_out)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
我也尝试过其他视频格式(H264,MJPG(,但没有成功。
编辑:没有成功意味着输出视频被创建,但仍然是空的。如果我使用原始帧大小,帧确实会写入视频。
编辑:Micka的答案有效,但是我现在也运行了python代码:缺少彩色视频输出的布尔参数。
video_out = cv2.VideoWriter("video_out.avi", fourcc, 25, (99, 173), False)
对我来说,这段代码确实有效,但 MJPG 确实将奇数分辨率四舍五入到偶数分辨率。 H264 根本不适用于该分辨率。
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();
return 0;
}
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();
return 0;
}
通常,许多编解码器仅限于某些像素块约束,例如每个维度的倍数为 2、4、8、16 或 32。要么是因为算法本身,要么是因为一些硬件指令优化。
cv2.VideoWriter("video_out.avi", fourcc, 25, (173, 99))
为大小为 173x99(宽 x 高(的帧创建一个编写器。
frame_out
是大小为 99x173 的帧(帧索引为 [y, x](。
更改索引以写入匹配的帧大小。
在 OSX 环境中:
- OSX:高山脉 (10.13.6(
- 蟒蛇:3.6.3
- Open CV(使用预构建的python pck(:opencv-python-headless 4.1.0.25
唯一对我有用的组合是mp4包装器(OSX不喜欢avi(和mp4v
编解码器。也尝试了avc1
但它不会写一个非标准尺寸的框架
codec = 'mp4v'
fourcc = cv2.VideoWriter_fourcc(*codec)
size = ( 1000 , 500 )
fps = 15
writer = cv2.VideoWriter('filename.mp4', fourcc, fps, size, True)