我正在尝试使用以下代码使用 openCV 2.4.6.1 修改和编写一些视频:
cv::VideoCapture capture( video_filename );
// Check if the capture object successfully initialized
if ( !capture.isOpened() )
{
printf( "Failed to load video, exiting.\n" );
return -1;
}
cv::Mat frame, cropped_img;
cv::Rect ROI( OFFSET_X, OFFSET_Y, WIDTH, HEIGHT );
int fourcc = static_cast<int>(capture.get(CV_CAP_PROP_FOURCC));
double fps = 30;
cv::Size frame_size( RADIUS, (int) 2*PI*RADIUS );
video_filename = "test.avi";
cv::VideoWriter writer( video_filename, fourcc, fps, frame_size );
if ( !writer.isOpened() && save )
{
printf("Failed to initialize video writer, unable to save video!\n");
}
while(true)
{
if ( !capture.read(frame) )
{
printf("Failed to read next frame, exiting.\n");
break;
}
// select the region of interest in the frame
cropped_img = frame( ROI );
// display the image and wait
imshow("cropped", cropped_img);
// if we are saving video, write the unwrapped image
if (save)
{
writer.write( cropped_img );
}
char key = cv::waitKey(30);
当我尝试使用 VLC 运行输出视频“test.avi”时,出现以下错误:avidemux 错误:没有为轨道 0 设置关键帧。我使用的是 Ubuntu 13.04,我尝试使用编码的视频使用 MPEG-4 和 libx264。我认为修复应该很简单,但找不到任何指导。实际代码可在 https://github.com/benselby/robot_nav/tree/master/video_unwrap 获得。 .提前致谢!
最佳答案
[PYTHON] 除了分辨率不匹配之外,每秒帧数也可能不匹配。就我而言,分辨率设置正确,但问题出在 fps 上。检查 VideoCapture 对象读取的每秒帧数,它显示为 30.0,但如果我将 VideoWriter 对象的 fps 设置为 30.0,则在 VLC 中会抛出相同的错误。不要将其设置为 30.0,您可以通过将其设置为 30 来解决错误。
附言您可以使用 cap.get(3)
宽度、cap.get(4)
高度和 cap.get(5)
在捕获 while/for 循环内获取 fps。
完整代码如下:
import numpy as np
import cv2 as cv2
cap = cv2.VideoCapture(0)
#Define Codec and create a VideoWriter Object
fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
#30.0 in the below line doesn't work while 30 does work.
out = cv2.VideoWriter('output.mp4', fourcc, 30, (640, 480))
while(True):
ret, frame = cap.read()
colored_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA)
print('Width = ', cap.get(3),' Height = ', cap.get(4),' fps = ', cap.get(5))
out.write(colored_frame)
cv2.imshow('frame', colored_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
有关可检查所有属性的完整文档 (C++) 可在此处获得:propId OpenCV Documentation
关于c++ - 使用 openCV 编写视频 - 没有为轨道 0 设置关键帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18598149/