当前位置:
首页 >
3 、OpenCvSharp 图片转视频
发布时间:2023/12/14
48
豆豆
生活随笔
收集整理的这篇文章主要介绍了
3 、OpenCvSharp 图片转视频
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
写作原因:前段时间做图像识别,一朋友用python将一张图片合成了一段视频,用于测试使用,先就c#做一个图片转视频的记录,使用的是Opencvsharp,如有不对的地方,请多多指教。
一、准备
需要使用到的对象为VideoWriter
其中重载函数有好几个,用来对应不同的需求。
二、参数解释
参数由很多,笔者用下面这个重载函数对这些参数做讲解
/// <summary>/// Creates video writer structure. /// </summary>/// <param name="fileName">Name of the output video file. </param>/// <param name="fourcc">4-character code of codec used to compress the frames. For example, "PIM1" is MPEG-1 codec, "MJPG" is motion-jpeg codec etc. /// Under Win32 it is possible to pass null in order to choose compression method and additional compression parameters from dialog. </param>/// <param name="fps">Frame rate of the created video stream. </param>/// <param name="frameSize">Size of video frames. </param>/// <param name="prms">The `params` parameter allows to specify extra encoder parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .)/// see cv::VideoWriterProperties</param>/// <returns></returns>public VideoWriter(string fileName, FourCC fourcc, double fps, Size frameSize, int[] prms){FileName = fileName ?? throw new ArgumentNullException(nameof(fileName));Fps = fps;FrameSize = frameSize;NativeMethods.HandleException(NativeMethods.videoio_VideoWriter_new4(fileName, (int)fourcc, fps, frameSize, prms, prms.Length, out ptr));if (ptr == IntPtr.Zero)throw new OpenCvSharpException("Failed to create VideoWriter");}fileName:就是生成的视频文件的名字,可由使用者自定义。
fourcc:使用的图片格式,像mjpg。
fps:设置生成的视频的帧率。
frameSize:生成的视频每一帧的大小。
prms:其他的一些参数,像编码格式等,由使用者自定义。
三、代码
Mat SourceMat = Cv2.ImRead(@"F:\Media\1018_2.png");//方法1Size imgSize = new Size(SourceMat.Width, SourceMat.Height);//构造函数设置必要参数//VideoWriter videoWriter = new VideoWriter(outVideo, VideoWriter.FourCC(@"MPG4"), 20, imgSize, true);VideoWriter videoWriter = new VideoWriter(@"F:\out.avi", VideoWriter.FourCC(@"XVID"), 20, imgSize, true);for (int i = 1; i <= 500; i++){Mat mat = new Mat();string FileString = @"F:\Media\1018_2.png";//FileString = FileString + i.ToString() + ".jpg";mat = Cv2.ImRead(FileString);if (!mat.Empty()){//Cv2.ImShow("Image", mat);videoWriter.Write(mat);Cv2.WaitKey(0);}}这里面需要注意的是构造函数中的参数一定要对,不然可能生不成视频或生成后打不开。
不过这里有个问题,就是这个out.avi有大小也可以正常播放,但是会发现这个视频的时长是0,用迅雷播放器播放不会有走秒
用系统自带的Media Player可以看到视频在走秒
不知道是哪里的问题,有知道的大神忘能指导一二。
总结
以上是生活随笔为你收集整理的3 、OpenCvSharp 图片转视频的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 哪一本科普书籍,会改变你的认知?
- 下一篇: 史上最浅显易懂的Git学习指南