/// <summary> /// Save a stream of image frames as an AVI video file. /// </summary> /// <param name="frames">Ordered list of frames at 30 fps.</param> /// <param name="width">Frame width.</param> /// <param name="height">Frame height.</param> /// <param name="file">Output filename.</param> public static void SaveAsAvi(List <Color[]> frames, int width, int height, string file) { if (frames.Count == 0) { return; } using (VideoWriter writer = new VideoWriter(file, new Size(width, height), 30, true, VideoCodec.FromName("MJPG"))) { writer.Open(); foreach (Color[] frame in frames) { Bgr <byte>[,] bitmap = new Bgr <byte> [height, width]; int h = 0; for (int k = 0; k < height; k++) { for (int i = 0; i < width; i++) { bitmap[k, i] = new Bgr <byte>(frame[h].B, frame[h].G, frame[h].R); h++; } } writer.Write(bitmap.Lock()); } writer.Close(); } }
/// <summary> /// 获取图像 /// </summary> public void Cap_Run(object o) { VideoCapture cap = new VideoCapture(Path); VideoWriter output = new VideoWriter(); int videoW = (int)cap.Get(CaptureProperty.FrameHeight); int videoH = (int)cap.Get(CaptureProperty.FrameHeight); int fps = (int)cap.Get(CaptureProperty.Fps); Size videosize = new Size(videoW, videoH); output.Open("demo.avi", FourCC.MJPG, fps, videosize); while (true) { cap.Read(Source); output.Write(Source); //Source.ImWrite("D:\\Show me your Code\\GitHub仓库\\My-ROV-Project\\temp.jpg"); if (Isopen == 0) { break; } try { (this.Owner as MainForm).PicBox_Video.Image = BitmapConverter.ToBitmap(Source); } catch (Exception e) { MessageBox.Show(e.Message); } } if (Isopen == 0) { this.th.Abort(); } }
static void Main() { //var reader = new CameraCapture(0); //capture from camera var reader = new FileCapture(Path.Combine(getResourceDir(), "Welcome.mp4")); reader.Open(); var writer = new VideoWriter(@"output.avi", reader.FrameSize, /*reader.FrameRate does not work Cameras*/ 30); //TODO: bug: FPS does not work for cameras writer.Open(); Bgr <byte>[,] frame = null; do { reader.ReadTo(ref frame); if (frame == null) { break; } using (var uFrame = frame.Lock()) { writer.Write(uFrame); } frame.Show(scaleForm: true); }while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)); reader.Dispose(); writer.Dispose(); UI.CloseAll(); }
static void Main() { Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH") + ";runtimes/win10-x64/"); //only needed if projects are directly referenced //var reader = new CameraCapture(0); //capture from camera var reader = new FileCapture(Path.Combine(getResourceDir(), "Welcome.mp4")); reader.Open(); var writer = new VideoWriter(@"output.avi", reader.FrameSize, /*reader.FrameRate does not work Cameras*/ 30); //TODO: bug: FPS does not work for cameras writer.Open(); Bgr <byte>[,] frame = null; do { reader.ReadTo(ref frame); if (frame == null) { break; } using (var uFrame = frame.Lock()) { writer.Write(uFrame); } frame.Show(autoSize: true); }while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)); reader.Dispose(); writer.Dispose(); ImageUI.CloseAll(); }
private void RECstart_Click(object sender, EventArgs e) { if (REC.Text.Equals("REC start")) { //string recSaveTargetDirectory = @"./REC/" + DateTime.Now.ToString("yyyy-MM-dd"); //if (!System.IO.File.Exists(recSaveTargetDirectory)) //{ // System.IO.Directory.CreateDirectory(recSaveTargetDirectory); //} string fileName = initPath() + "Rec.avi"; int codec = VideoWriter.FourCC('M', 'J', 'P', 'G'); double fps = 20.0; writer.Open(fileName, codec, fps, frame.Size(), true); REC.Text = "REC stop"; } else { if (writer.IsOpened()) { writer.Release(); } REC.Text = "REC start"; } }
private void GenerateVideo(ISampleSource source) { Console.WriteLine("Initializing video writer..."); using (var writer = new VideoWriter(options.OutputFile.FullName)) { writer.Width = 1920; writer.Height = 1080; writer.Fps = options.Fps; writer.AudioSampleRate = source.WaveFormat.SampleRate; writer.Open(); double totalFrames = FrameMath.CalculateTotalFrames(source, options); Console.WriteLine("Initializing renderer..."); using (var renderer = new GLRenderer(false)) { var wallpaper = Image.FromFile(options.WallpaperFile.FullName) as Bitmap; wallpaperTexture = renderer.LoadTexture(wallpaper); effectChain.Initialize(source.ToMono(), options); Console.WriteLine("Generating video..."); float[] sampleBuffer = new float[writer.AudioSamplesPerFrame]; var frameNumber = 0; while (true) { if (writer.WriteVideo) { renderer.Clear(); RenderFrame(renderer, new Frame(frameNumber, TimeSpan.FromSeconds(frameNumber / (double)options.Fps))); var frame = renderer.Snapshot(); writer.WriteVideoFrame(frame); if (frameNumber % 60 == 0) { ProgressHandler?.Invoke(Math.Round(frameNumber / totalFrames * 100.0, 2)); } frameNumber++; } else { var read = source.Read(sampleBuffer, 0, sampleBuffer.Length); if (read > 0) { writer.WriteAudioFrame(sampleBuffer); } else { break; } } } ProgressHandler?.Invoke(Math.Round(frameNumber / totalFrames * 100.0, 2)); } } }
static void Main(string[] args) { VideoCapture capture = new VideoCapture("Star.mp4"); Mat frame = new Mat(new Size(capture.FrameWidth, capture.FrameHeight), MatType.CV_8UC3); VideoWriter videoWriter = new VideoWriter(); bool isWrite = false; while (true) { if (capture.PosFrames == capture.FrameCount) { capture.Open("Star.mp4"); } capture.Read(frame); Cv2.ImShow("VideoFrame", frame); int key = Cv2.WaitKey(33); // Ctrl + D 또는 Alt + D // 운영체제 별로 다를 수 있습니다. if (key == 4) { videoWriter.Open("Video.avi", FourCC.XVID, 30, frame.Size(), true); isWrite = true; } // Ctrl + X 또는 Alt + X // 운영체제 별로 다를 수 있습니다. else if (key == 24) { videoWriter.Release(); isWrite = false; } else if (key == 'q') { break; } if (isWrite == true) { videoWriter.Write(frame); } } videoWriter.Release(); capture.Release(); Cv2.DestroyAllWindows(); }
public static void SoVüStricherln() { var r = new Random(); var maxdim = 1024; var m = new Mat(maxdim, maxdim, MatType.CV_16SC4); var vw = new VideoWriter(); vw.Open("video.avi", FourCC.Prompt, 29, m.Size(), true); Scalar color = new Scalar(10000d, 10000d, 0d, 0d); var colorchangeconst = 1000; Point p1 = new Point(0, 0); Point p2 = new Point(0, 0); for (int i = 0; i < 10000; i++) { var chan = r.Next(0, 4); // pick color channel var addremnum = r.Next(0, 2) == 0 ? -1 : 1; // add or remove value color[chan] = Math.Clamp(color[chan] + (colorchangeconst * addremnum), Int16.MinValue, Int16.MaxValue); p2.X = r.Next(0, maxdim); p2.Y = r.Next(0, maxdim); m.Line(p1, p2, color, 1); p1 = p2; if (i % 33 == 0) { vw.Write(m); Cv2.ImShow("sickname", m); Cv2.WaitKey(10); } } vw.Release(); //Cv2.ImShow("sickname", m); //Cv2.WaitKey(); }
public static void Main(string[] args) { var success = FFmpegLoader.Load(FFmpegPath); if (!success) { Console.WriteLine("Could not load FFmpeg"); return; } Console.WriteLine($"Loaded FFmpeg v{FFmpegLoader.FFmpegVersion}"); var bitmap = (Bitmap)Image.FromFile(ImagePath); var audio = CodecFactory.Instance.GetCodec(AudioPath) .ToSampleSource(); using (var writer = new VideoWriter(OutputPath)) { writer.Open(); float[] audioData = new float[writer.AudioSamplesPerFrame]; while (true) { if (writer.WriteVideo) { // Write a video frame writer.WriteVideoFrame(bitmap); } else { // Write an audio frame int read = audio.Read(audioData, 0, audioData.Length); if (read <= 0) { break; } writer.WriteAudioFrame(audioData); } } } }
public void XVID() { const string fileName = "temp_XVID.mp4"; try { using var writer = new VideoWriter(); var success = writer.Open( fileName, VideoCaptureAPIs.ANY, FourCC.XVID, 15, new Size(1920, 1440)); Assert.True(success); } finally { DeleteFile(fileName); } }
private void buttonRecord_Click(object sender, EventArgs e) { if (_videoWriter == null) { _videoWriter = new VideoWriter(); // https://www.atmarkit.co.jp/ait/articles/1610/18/news143_2.html if (!_videoWriter.Open(@"C:\Users\skeiya\caps\video.mp4", FourCC.MP4V, 20.0, new OpenCvSharp.Size(WIDTH, HEIGHT))) { MessageBox.Show("hoge"); return; } buttonRecord.Text = "停止"; } else { _videoWriter.Release(); _videoWriter.Dispose(); _videoWriter = null; buttonRecord.Text = "録画"; } }
private void playVideowithSaving() { Mat save = new Mat(); FileDialog ofd = new SaveFileDialog(); string imagePath; OpenCvSharp.FourCC codec = OpenCvSharp.FourCC.Default; OpenCvSharp.CvSize size; size.Height = input1bitmap.Height; size.Width = input1bitmap.Width; FlowArray opticalFlow = new FlowArray(); opticalFlow.Height = input1bitmap.Height; opticalFlow.Width = input1bitmap.Width; opticalFlow.Array = new float[2][]; opticalFlow.Array[0] = new float[opticalFlow.Width * opticalFlow.Height]; opticalFlow.Array[1] = new float[opticalFlow.Width * opticalFlow.Height]; if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { imagePath = ofd.FileName; videofilename = String.Format("{0}.avi", imagePath); } VideoWriter savevid = new VideoWriter(); savevid.Open(videofilename, codec, 24, size, true); if (videoSelected) { while (!(image.Empty())) { input1bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(image); sw.Start(); for (int i = 0; i < 1; i++) { opticalFlow = HornSchunck.calculateOpticalFlow(input1bitmap, input2bitmap, out int k, opticalFlow); } OutputVideo = _CLProcessor.decorateFlowColor(input1bitmap, opticalFlow, HornSchunck.flowInterval, HornSchunck.threshold); save = OpenCvSharp.Extensions.BitmapConverter.ToMat(OutputVideo.Bitmap); savevid.Write(save); pictureBox4.Image.Dispose(); pictureBox5.Image.Dispose(); pictureBox4.Image = OutputVideo.Bitmap; pictureBox5.Image = input1bitmap; Application.DoEvents(); pictureBox4.Refresh(); pictureBox5.Refresh(); sw.Stop(); runTime = 1 / (float)sw.Elapsed.TotalSeconds; label9.Text = String.Format("Frame rate: {0} [fps]", Convert.ToString(runTime)); label9.Visible = true; sw.Reset(); input2bitmap = input1bitmap; capture.Read(image); } } videoSelected = false; capture.Dispose(); image.Dispose(); savevid.Release(); //savevid.Dispose(); pictureBox4.Image.Dispose(); pictureBox5.Image.Dispose(); }
public void Button_Save_Click(object sender, RoutedEventArgs e) { try { CvSize sz; string strRECName; if (savefilename == "name") { strRECName = savefolder + @"\" + "video" + "noname" + ".avi"; } else { strRECName = savefolder + @"\" + savefilename + ".avi"; } if (size.SelectedItem.ToString() == "320,240") { sz = new CvSize(320, 240); } else if (size.SelectedItem.ToString() == "512,424") { sz = new CvSize(512, 424); } else return; vw = new VideoWriter(); vw.Open(strRECName, -1, 30, sz, true); var panel = this.resourcePanels[this.ListBox_ResourcePanels.SelectedIndex]; this.starttime = DateTime.Now; this.currentframe = 0; this.IsRecStarted = true; this.saveImageIndex = (int)this.SliderTextBox.Slider_Main.Value; panel.ImageFrameArrived += Panel_ImageFrameArrived; } catch (Exception ex) { Console.WriteLine(ex); } }
internal static void SuperSchnit() { var cryzyform = 2; // 0.5,1,2,3,4 var lp = new ElPalletto(); var rand = new Random(); var brushSizeNP = new NumerPlayer(np => { var fac = rand.Next(0, 2) == 0 ? -1 : 1; np.N = Math.Clamp(np.N + (fac * rand.Next(0, 4)), 2, 37); }); brushSizeNP.N = 11; var radiusInitNp = new NumerPlayer(np => { var fac = rand.Next(0, 2) == 0 ? -1 : 1; np.N = (int)Math.Clamp(1 + np.N + (fac * np.N * 0.1), 20d, 4000d); }); radiusInitNp.N = 300; var r = radiusInitNp.N; var quad = 0; //quadrant 0,1,2,3 var lenab = 2000; var lens = Lib.SplitGolden(lenab); var m = new Mat((int)lens.Y, (int)lens.X, MatType.CV_16SC4); var vw = new VideoWriter(); vw.Open("video.avi", FourCC.Prompt, 29, m.Size(), true); var p1 = new Point((int)lens.X / 2, (int)lens.Y / 2); lp._Color = new Scalar(-20000d, 30000d, -29990d, 30000d); lp._Color2 = new Scalar(-20000d, 30000d, -29990d, 30000d); for (int i = 0; i < 1000000; i++) { if (r <= brushSizeNP.N / cryzyform) { r = radiusInitNp.N; lp._Color = lp._Color2; radiusInitNp.Kick(); brushSizeNP.Kick(); if (i % 4 == 0) { p1 = new Point2d(rand.Next((int)lens.X), rand.Next((int)lens.Y)); lp.RandomizeColorWithAlpha(); lp._Color2 = lp._Color; } } var circle = Lib.PlotCircle(p1.X, p1.Y, r); var circpixcountquad = (int)((decimal)circle.Count / 4); var segment = circle.GetRange(circpixcountquad * quad, circpixcountquad); int j = 0; foreach (var p in segment) { m.Circle(p, 1, lp._Color, thickness: brushSizeNP.N); lp.CCChanDir(); j++; if (j % 150 == 0) { vw.Write(m); } } //lp.Darken(0.1); var rcut = Lib.SplitGolden(r); r = (int)rcut.X; p1 = segment.LastOrDefault(); if (quad == 0) { p1.Y = p1.Y - r; } if (quad == 1) { p1.X = p1.X + r; } if (quad == 2) { p1.Y = p1.Y + r; } if (quad == 3) { p1.X = p1.X - r; } quad = (quad + 1) % 4; Cv2.ImShow("supafenster", m); Cv2.WaitKey(1); } vw.Release(); }
public static void ImmerDerNaseNach() { var lenab = 1524; var strokeLen = 5; var brushSize = 20; var rotationfactor = 15; // neue maximale rotation in Anteilen von Kreis var rotation = 1d / rotationfactor; var lens = Lib.SplitGolden(lenab); var m = new Mat((int)lens.Y, (int)lens.X, MatType.CV_16SC4); var vw = new VideoWriter(); vw.Open("video.avi", FourCC.Prompt, 29, m.Size(), true); Scalar color = new Scalar(30000d, 30000d, 0, 0); var colorchangeconst = 1500; Point p1 = new Point(lens.X / 2, lens.Y / 2); var r = new Random(); // this is the direction in the circle ranging from 0 to less than 1; var direction = r.NextDouble(); for (int i = 0; i < 30000; i++) { // COLOR CHANGE var chan = r.Next(0, 4); // pick color channel var addremnum = r.Next(0, 2) == 0 ? -1 : 1; // add or remove value color[chan] = Math.Clamp(color[chan] + (colorchangeconst * addremnum), Int16.MinValue, Int16.MaxValue); var circle = Lib.PlotCircle(p1.X, p1.Y, strokeLen); var newStep = circle[(int)(circle.Count * direction)]; newStep = Lib.ContinuePointInRect((int)lens.X, (int)lens.Y, (int)newStep.X, (int)newStep.Y); // anmalen m.Circle(newStep, brushSize, color, thickness: -1); // weiter drehen var posnegativemultiplier = r.Next(0, 2) == 0 ? -1 : 1; direction = Lib.ContinuePointInRange(1, direction + (rotation * posnegativemultiplier)); p1 = newStep; if (i % 5 == 0) { posnegativemultiplier = r.Next(0, 2) == 0 ? -1 : 1; brushSize = Math.Clamp(brushSize + posnegativemultiplier, 5, 30); } if (i % 66 == 0) { vw.Write(m); //Cv2.ImShow("sickname2", m); //Cv2.WaitKey(10); } } vw.Release(); //Cv2.ImShow("sickname", m); //Cv2.WaitKey(); }
// ====================================== // ====================================== // Drawing processing thread : 描画処理用スレッド private void Draw_Thread_DoWork(object sender, DoWorkEventArgs e) { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); long[] time = new long[2] { 0, 0 }; try { while (!stop) { sw.Start(); Bitmap src = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); Bitmap dst = new Bitmap(pictureBox1.Width, pictureBox1.Height); Pen redpen = new Pen(Brushes.Red, 5); Graphics src_g = Graphics.FromImage(src); Graphics dst_g = Graphics.FromImage(dst); src_g.CopyFromScreen(new System.Drawing.Point(src.Width * disp_num, 0), new System.Drawing.Point(0, 0), src.Size, CopyPixelOperation.SourceCopy); dst_g.InterpolationMode = InterpolationMode.NearestNeighbor; if (top != null && bottom != null && top.X != bottom.X && top.Y != bottom.Y && !isClick) { if (top.X < bottom.X && top.Y < bottom.Y) { ex_params = new int[4] { top.X, top.Y, bottom.X - top.X, bottom.Y - top.Y } } ; else if (top.X > bottom.X && top.Y < bottom.Y) { ex_params = new int[4] { bottom.X, top.Y, top.X - bottom.X, bottom.Y - top.Y } } ; else if (top.X < bottom.X && top.Y > bottom.Y) { ex_params = new int[4] { top.X, bottom.Y, bottom.X - top.X, top.Y - bottom.Y } } ; else { ex_params = new int[4] { bottom.X, bottom.Y, top.X - bottom.X, top.Y - bottom.Y } }; int[] ratio = new int[2] { dst.Width / ex_params[2], dst.Height / ex_params[3] }; Rectangle rect = new Rectangle(ex_params[0] * 2, ex_params[1] * 2, ex_params[2] * 2, ex_params[3] * 2); Bitmap dst_cut = src.Clone(rect, src.PixelFormat); if (dst_cut.Width * ratio[1] > pictureBox1.Width) { int h = ex_params[3] * ratio[0]; dst_g.DrawImage(dst_cut, 0, (pictureBox1.Height - h) / 2, dst.Width, h); } else { int w = ex_params[2] * ratio[1]; dst_g.DrawImage(dst_cut, (pictureBox1.Width - w) / 2, 0, w, dst.Height); } } else { dst_g.DrawImage(src, 0, 0, src.Width / 2, src.Height / 2); if (isClick) { System.Drawing.Point now = new System.Drawing.Point(); Invoke((MethodInvoker) delegate { now = PointToClient(Cursor.Position); }); now.Y -= menuStrip1.Height; if (top.X != now.X && top.Y != now.Y) { Rectangle rect = new Rectangle(); if (top.X < now.X && top.Y < now.Y) { rect = new Rectangle(top, new System.Drawing.Size(now.X - top.X, now.Y - top.Y)); } else if (top.X < now.X && top.Y < now.Y) { rect = new Rectangle(top, new System.Drawing.Size(now.X - top.X, now.Y - top.Y)); } else if (top.X > now.X && top.Y < now.Y) { rect = new Rectangle(now.X, top.Y, top.X - now.X, now.Y - top.Y); } else if (top.X < now.X && top.Y > now.Y) { rect = new Rectangle(top.X, now.Y, now.X - top.X, top.Y - now.Y); } else if (top.X > now.X && top.Y > now.Y) { rect = new Rectangle(now, new System.Drawing.Size(top.X - now.X, top.Y - now.Y)); } dst_g.DrawRectangle(redpen, rect); } else { dst_g.DrawLine(redpen, top, now); } } } src_g.Dispose(); dst_g.Dispose(); bmplist.Add(src); Invoke((MethodInvoker) delegate { pictureBox1.Image = dst; }); time[0] += sw.ElapsedMilliseconds; time[1]++; sw.Reset(); } sw.Stop(); } catch (Exception str) { Console.WriteLine(str); } Invoke((MethodInvoker) delegate { draw_label(0); }); writer = new VideoWriter(); if (!Directory.Exists(@"C:\Temp")) { Directory.CreateDirectory(@"C:\Temp"); } writer.Open(@"C:\Temp\" + DateTime.Now.ToString("yyyymmddhhmmss") + ".avi", FourCC.MJPG, 1000 / (double)(time[0] / time[1]), new OpenCvSharp.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height)); for (int n = 0; n < bmplist.Count; n++) { Mat mframe = new Mat(); mframe = bmplist[n].ToMat(); unsafe { byte *b = mframe.DataPointer; for (int i = 0; i < mframe.Width; i++) { for (int j = 0; j < mframe.Height; j++) { byte p = b[0]; b[0] = b[2]; b[2] = p; b = b + 4; } } } writer.Write(mframe); BeginInvoke((MethodInvoker) delegate { draw_label(n); }); } }