3 、OpenCvSharp 图片转视频
生活随笔
收集整理的這篇文章主要介紹了
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学习指南