Page 1 of 1

Making AVI file from bitmaps from webcam in realtime

PostPosted: Wed Apr 02, 2014 9:24 pm
by markon1
I have made an application in C# which gets frames from webcam and shows them in an PictureBox. I want to make it to record these frames into AVI video. Image preview works fine until I start recording video. Then it becomes laggy.
recordStart is bool variable which if true means user clicked record button, and if false user clicked to stop recording.
OK, this is function I call to start preview:

Code: Select all
private void btnPreview_Click(object sender, EventArgs e)
        {
            if (!webcam.IsConnected())
            {
                webcam.Connect();
                preview = true;
                btnPreview.Text = "Stop preview";
                previewWorker.RunWorkerAsync();
            }
            else
            {
                previewWorker.CancelAsync();
                preview = false;
                btnPreview.Text =   "Start preview";
            }
        }


This is where I get the frames from webcam, display them on PictureBox and record them to AVI:

Code: Select all
private void previewWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (!previewWorker.CancellationPending)
            {
                webcam.Update();
                frame = webcam.CalcBitmap();
                pictureBox1.Image = frame;

                if (startRecording)
                {
                    writer.AddFrame((Bitmap)frame.Clone());
                }



            }
        }


This is where I stop preview:

Code: Select all
private void previewWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            webcam.Disconnect();
            btnPreview.Text = "Start preview";
        }

And this is function where I start recording the video, and close it (it's an response to the "btnRecord" click event)

Code: Select all
      if (startRecording)
      {
          startRecording = false;
          writer.Close();
          btnRecord.Text = "Start recording";
      }
      else
      {
          startRecording = true;
          btnRecord.Text = "Stop recording";

          writer = new AVIWriter("XVID");
          writer.FrameRate = 25;

          writer.Open(aviPath+"\\"+"test.avi", 640, 480);

      }
I think that problem has something to do with multithreading and/or BackgroundWorker, concept I'm not very used to. (BackgroundWorker used here was done in example source code that I upgraded to my app). So if you know how I could get better performance with this program and get rid of lagging when I start recording video, I'll be very thankful!