How to get the picturebox image path that captured by the webcam - c#

In my form. I have two picturebox and a button that capture the image into picturebox.
Two Picturebox
WebcamImage - represent the live camera image
PreviewImage - represent the Captured image from webcamimage
When i saved this captured image it will go to my UserImage picturebox (In my Usercontrol)
The problems is i don't know how i'm gonna get the picturebox image path.
What i want is when i click my saved button the image path will be saved to my label text.
Here's my code
PS: I'm using Aforge.dll
public partial class CaptureImage : Form
{
private FilterInfoCollection CaptureDevice;
private VideoCaptureDevice FinalFrame;
RegisterCustomer _view;
public CaptureImage(RegisterCustomer view)
{
InitializeComponent();
this._view = view;
}
private void CaptureImage_Load(object sender, EventArgs e)
{
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo Device in CaptureDevice)
{
comboBox1.Items.Add(Device.Name);
}
comboBox1.SelectedIndex = 0;
FinalFrame = new VideoCaptureDevice();
FinalFrame = new VideoCaptureDevice(CaptureDevice[comboBox1.SelectedIndex].MonikerString);
if (FinalFrame.VideoCapabilities.Length > 0)
{
string highestSolution = "0;0";
//Search for the highest resolution
for (int i = 0; i < FinalFrame.VideoCapabilities.Length; i++)
{
if (FinalFrame.VideoCapabilities[i].FrameSize.Width > Convert.ToInt32(highestSolution.Split(';')[0]))
highestSolution = FinalFrame.VideoCapabilities[i].FrameSize.Width.ToString() + ";" + i.ToString();
}
}
FinalFrame.NewFrame += new NewFrameEventHandler(FinalFrame_NewFrame);
FinalFrame.Start();
btn_save.Hide();
btn_cancel.Hide();
}
void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
WebcamImage.Image = (Bitmap)eventArgs.Frame.Clone();
}
private void CaptureImage_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalFrame.IsRunning == true)
{
FinalFrame.Stop();
}
}
private void btn_save_Click(object sender, EventArgs e)
{
_view.UserImage.Image = PreviewImage.Image;
this.Close();
}
private void btn_cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btn_capture_Click(object sender, EventArgs e)
{
PreviewImage.Image = (Bitmap)WebcamImage.Image.Clone();
PreviewImage.BringToFront();
btn_capture.Hide();
btn_save.Show();
btn_cancel.Show();
}
}
This is only i know in getting the picturebox image path by using openfile dialog
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Image Files (*.jpg;*.jpeg;.*.png; | *.jpg;*.jpeg;.*.png;)";
ofd.FilterIndex = 1;
ofd.Multiselect = false;
ofd.Title = "Select Image File";
if (ofd.ShowDialog() == DialogResult.OK)
{
location = ofd.FileName;
path.Text = location;
UserImage.Image = Image.FromFile(location);
UserImage.SizeMode = PictureBoxSizeMode.StretchImage;
}
}

Related

Vertically changing text using C#

I'm planning to add this feature on my application where it will display a single line of text on a label which the user imported.
How it works: The user imports a text file, then after a Button click the Label text will change to the first line of text on the text file that the user imported. After X amount of seconds, it will change to the second one. Basically, it will move vertically down until the last line then after it will stop.
List<string> lstIpAddress = new List<string>();
int nCount = 0;
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 30000;
}
private void LoadBTN_Click(object sender, EventArgs e)
{
OpenFileDialog load = new OpenFileDialog();
if (load.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Clear();
load.InitialDirectory = Environment.SpecialFolder.Desktop.ToString();
load.Filter = "txt files (*.txt)|*.txt";
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(load.OpenFile()))
{
string line;
while ((line = r.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
for (int nlstItem = 0; nlstItem < lstIpAddress.Count; nlstItem++)
{
listBox1.Items.Add(lstIpAddress[nlstItem]);
}
label2.Text = listBox1.Items[nCount].ToString();
nCount++;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
label2.Text = listBox1.Items[nCount].ToString();
timer1.Start();
}
You need to move nCount++; to a Timer1 click event. Also, you should check if nCount is in range of listBox1.Items.Count otherwise you will get an exception.
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
nCount++;
if (nCount < listBox1.Items.Count)
{
label2.Text = listBox1.Items[nCount].ToString();
}
timer1.Start();
}

How to pass file dialog Instance as a parameter in C#

I am trying to compare two images by using picture box, but I got a problem: How can I pass the selected picture name as a parameter to a function as a string?
I save picture path and name as a string name1 and string name2, but I got a problem when I pass them as parameters.
Below is my code. Please tell me where I am wrong.
private void pictureBox1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd1 = new OpenFileDialog();
ofd1.Title = "Select User Profile Image";
ofd1.Filter = "Image File(*.png;*.jpg;*.bmp;*.gif)|*.png;*.jpg;*.bmp;*.gif";
if (ofd1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(ofd1.FileName);
string name1 = ofd1.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
Compare(name1,name2);
}
public void Compare(string bmp1, string bmp2, byte threshold = 3)
{
Bitmap firstBmp = (Bitmap)Image.FromFile(bmp1);
Bitmap secondBmp = (Bitmap)Image.FromFile(bmp2);
firstBmp.GetDifferenceImage(secondBmp, true);
string result = string.Format("Difference: {0:0.0} %", firstBmp.PercentageDifference(secondBmp, threshold) * 100);
}
You create variable name1 inside if statement inside pictureBox1_Click(). You should create class level variable to use it inside button1_Click(), because name1 is visible only inside if block:
public YourClass
{
string name1 = String.Empty:
//..... your code
private void pictureBox1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd1 = new OpenFileDialog();
ofd1.Title = "Select User Profile Image";
ofd1.Filter = "Image File(*.png;*.jpg;*.bmp;*.gif)|*.png;*.jpg;*.bmp;*.gif";
if (ofd1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(ofd1.FileName);
name1 = ofd1.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
Compare(name1,name2);
}
public void Compare(string bmp1, string bmp2, byte threshold = 3)
{
Bitmap firstBmp = (Bitmap)Image.FromFile(bmp1);
Bitmap secondBmp = (Bitmap)Image.FromFile(bmp2);
firstBmp.GetDifferenceImage(secondBmp, true);
string result = string.Format("Difference: {0:0.0} %", firstBmp.PercentageDifference(secondBmp, threshold) * 100);
}
}
If you create name2 the same way, you should make it class level variable too.
You can declare a member variable in your Form to save the file path:
public partial class YourForm : Form
{
private string _imagePath1;
private string _imagePath2;
private void pictureBox1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd1 = new OpenFileDialog();
// ... your code
if (ofd1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(ofd1.FileName);
// SAVE PATH TO CLASS MEMBER
_imagePath1 = ofd1.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
// USE CLASS MEMBERS
Compare(_imagePath1, _imagePath2);
}
}
I think below URL is helpful to you
http://www.c-sharpcorner.com/uploadfile/prathore/image-comparison-using-C-Sharp

how to mirror capture of webcam with Aforge.Net library in C#

I'm using the AForge.NET library (http://www.aforgenet.com) to capture an image from my webcam,show it in a picturebox and then save it.But the capture is not like mirror. Does anybody know how to mirror the capture in c#?
public static Bitmap _latestFrame;
private FilterInfoCollection webcam;
private VideoCaptureDevice cam;
Bitmap bitmap;
private int orderidcapture = 0;
private string date1 = "";
private void Frm_Capturet_Load(object sender, EventArgs e)
{
try
{
piclocation = new Ini(Application.StartupPath + "\\UserSetting.ini").GetValue("Webservice",
"DigitalSign").ToString();
webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo VideoCaptureDevice in webcam)
{
comboBox1.Items.Add(VideoCaptureDevice.Name);
}
comboBox1.SelectedIndex = 0;
}
catch (Exception error)
{
MessageBox.Show(error.Message + "error11");
}
Focus();
}
private string piclocation = "";
void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
bitmap = (Bitmap)eventArgs.Frame.Clone();
picFrame.Image = bitmap;
}
private void button1_Click(object sender, EventArgs e)
{
cam = new VideoCaptureDevice(webcam[comboBox1.SelectedIndex].MonikerString);
cam.NewFrame += new NewFrameEventHandler(cam_NewFrame);
cam.DisplayPropertyPage(new IntPtr(0));
cam.Start();
}
private void button2_Click(object sender, EventArgs e)
{
date1 = date1.Replace("/", "");
Bitmap current = (Bitmap)bitmap.Clone();
string filepath = Environment.CurrentDirectory;
string fileName = System.IO.Path.Combine(piclocation, orderidcapture + "__" + date1 + #"name.jpg");
current.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
current.Dispose();
current = null;
}
solved the problem by my own.
void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
try
{
bitmap = (Bitmap)eventArgs.Frame.Clone();
///add these two lines to mirror the image
var filter = new Mirror(false, true);
filter.ApplyInPlace(bitmap);
///
picFrame.Image = bitmap;
}
catch
{
}
}

Create a HaarCascade to output percentages instead of outputting a "true" when a threshold is being surpassed

My goal is to use my webcam to capture my face and detect my mood by facial expression. The output should be probabilites like 70 % happy, 10 % sad, ...
My approach: very happy and very sad ( and other states ) faces should be saved in a HaarCascade.
My problems are twofold:
How do I create a HaarCascade to use with HaarObjectDetector for the
HaarObjectDetector object to output percentages instead of
outputting a "true" when a threshold is being surpassed?
How do I create a HaarCascade for HaarCascade? Is it easier to use String path = #"C:\Users\haarcascade-frontalface_alt2.xml"; HaarCascade cascade1 = HaarCascade.FromXml(path); with opencv-xml or generate it using HaarCascade m = new HaarCascade(20,20,HaarCascadeStages);? What would HaarCascadeStages be?
Have others already solved this issue and offer sourcecode for c#?
My current code:
public partial class Form1 : Form
{
private bool DeviceExist = false;
private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource = null;
Bitmap picture;
HaarObjectDetector detector;
FaceHaarCascade cascade;
public Form1()
{
InitializeComponent();
}
// get the devices name
private void getCamList()
{
try
{
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
comboBox1.Items.Clear();
if (videoDevices.Count == 0)
throw new ApplicationException();
DeviceExist = true;
foreach (FilterInfo device in videoDevices)
{
comboBox1.Items.Add(device.Name);
}
comboBox1.SelectedIndex = 0; //make dafault to first cam
}
catch (ApplicationException)
{
DeviceExist = false;
comboBox1.Items.Add("No capture device on your system");
}
}
//toggle start and stop button
private void start_Click(object sender, EventArgs e)
{
}
//eventhandler if new frame is ready
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
picture = (Bitmap)eventArgs.Frame.Clone();
//Rectangle[] objects = detector.ProcessFrame(picture);
//if (objects.Length > 0)
//{
// RectanglesMarker marker = new RectanglesMarker(objects, Color.Fuchsia);
// pictureBox1.Image = marker.Apply(picture);
//}
pictureBox1.Image = picture;
}
//close the device safely
private void CloseVideoSource()
{
if (!(videoSource == null))
if (videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
//get total received frame at 1 second tick
private void timer1_Tick(object sender, EventArgs e)
{
label2.Text = "Device running... " + videoSource.FramesReceived.ToString() + " FPS";
}
//prevent sudden close while device is running
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
CloseVideoSource();
}
private void Form1_Load(object sender, EventArgs e)
{
getCamList();
cascade = new FaceHaarCascade();
detector = new HaarObjectDetector(cascade, 30);
detector.SearchMode = ObjectDetectorSearchMode.Average;
detector.ScalingFactor = 1.5f;
detector.ScalingMode = ObjectDetectorScalingMode.GreaterToSmaller;
detector.UseParallelProcessing = false;
detector.Suppression = 2;
}
private void rfsh_Click_1(object sender, EventArgs e)
{
}
private void start_Click_1(object sender, EventArgs e)
{
if (start.Text == "Start")
{
if (DeviceExist)
{
videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
CloseVideoSource();
videoSource.DesiredFrameSize = new Size(640, 480);
//videoSource.DesiredFrameRate = 10;
videoSource.Start();
label2.Text = "Device running...";
start.Text = "Stop";
timer1.Enabled = true;
}
else
{
label2.Text = "Error: No Device selected.";
}
}
else
{
if (videoSource.IsRunning)
{
timer1.Enabled = false;
CloseVideoSource();
label2.Text = "Device stopped.";
start.Text = "Start";
}
}
}
}

How to Record WebCam Video in MPEG or AVI files using C# Desktop Application

I am developing a Desktop Application which requires me to connect to webcam(s) and record(save) the video in MPEG, AVI, MP4 and WMV formats and Burn into the CD/DVD. The application is in Win Forms. I am only Looking for free or open source solutions or controls.
I had done saving as AVI using Aforge.Net but its taking more size to save(like 60-100MB for 15sce 320x240 Video ). I am expecting 1MB for 10sec.
Here is the Code :
using System;
using System.Drawing;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.VFW;
namespace Aforge_Web_Cam
{
public partial class VideoForm : Form
{
private FilterInfoCollection VideoCaptureDevices;
private VideoCaptureDevice FinalVideo = null;
private VideoCaptureDeviceForm captureDevice;
private Bitmap video;
private AVIWriter AVIwriter = new AVIWriter();
private SaveFileDialog saveAvi;
public VideoForm()
{
InitializeComponent();
}
private void VideoForm_Load(object sender, EventArgs e)
{
VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
captureDevice = new VideoCaptureDeviceForm();
}
private void butStart_Click(object sender, EventArgs e)
{
if (captureDevice.ShowDialog(this) == DialogResult.OK)
{
VideoCaptureDevice videoSource = captureDevice.VideoDevice;
FinalVideo = captureDevice.VideoDevice;
FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
FinalVideo.Start();
}
}
void FinalVideo_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
if (butStop.Text == "Stop Record")
{
video = (Bitmap)eventArgs.Frame.Clone();
pbVideo.Image = (Bitmap)eventArgs.Frame.Clone();
AVIwriter.Quality = 0;
AVIwriter.AddFrame(video);
}
else
{
video = (Bitmap)eventArgs.Frame.Clone();
pbVideo.Image = (Bitmap)eventArgs.Frame.Clone();
}
}
private void butRecord_Click(object sender, EventArgs e)
{
saveAvi = new SaveFileDialog();
saveAvi.Filter = "Avi Files (*.avi)|*.avi";
if (saveAvi.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int h = captureDevice.VideoDevice.VideoResolution.FrameSize.Height;
int w = captureDevice.VideoDevice.VideoResolution.FrameSize.Width;
AVIwriter.Open(saveAvi.FileName, w, h);
butStop.Text = "Stop Record";
//FinalVideo = captureDevice.VideoDevice;
//FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
//FinalVideo.Start();
}
}
private void butStop_Click(object sender, EventArgs e)
{
if (butStop.Text == "Stop Record")
{
butStop.Text = "Stop";
if (FinalVideo == null)
{ return; }
if (FinalVideo.IsRunning)
{
//this.FinalVideo.Stop();
this.AVIwriter.Close();
pbVideo.Image = null;
}
}
else
{
this.FinalVideo.Stop();
this.AVIwriter.Close();
pbVideo.Image = null;
}
}
private void butCapture_Click(object sender, EventArgs e)
{
pbVideo.Image.Save("IMG" + DateTime.Now.ToString("hhmmss") + ".jpg");
}
private void butCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void VideoForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalVideo == null)
{ return; }
if (FinalVideo.IsRunning)
{
this.FinalVideo.Stop();
this.AVIwriter.Close();
}
}
}
}
AVIWriter doesn't provide videocompression, use FileWriter from AForge.Video.FFMPEG. There you can choose everything: Size, Framerate, Codec and Bitrate and if your video was 600MB in 20 sec it now will be 6 MB in 20 sec.
Here you go:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.FFMPEG;
using AForge.Video.VFW;
namespace WindowsFormsApplication12
{
public partial class Form1 : Form
{
private FilterInfoCollection VideoCaptureDevices;
private VideoCaptureDevice FinalVideo = null;
private VideoCaptureDeviceForm captureDevice;
private Bitmap video;
//private AVIWriter AVIwriter = new AVIWriter();
private VideoFileWriter FileWriter = new VideoFileWriter();
private SaveFileDialog saveAvi;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
captureDevice = new VideoCaptureDeviceForm();
}
private void button1_Click(object sender, EventArgs e)
{
if (captureDevice.ShowDialog(this) == DialogResult.OK)
{
VideoCaptureDevice videoSource = captureDevice.VideoDevice;
FinalVideo = captureDevice.VideoDevice;
FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
FinalVideo.Start();
}
}
void FinalVideo_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
if (butStop.Text == "Stop Record")
{
video = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
//AVIwriter.Quality = 0;
FileWriter.WriteVideoFrame(video);
//AVIwriter.AddFrame(video);
}
else
{
video = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
}
}
private void button2_Click(object sender, EventArgs e)
{
saveAvi = new SaveFileDialog();
saveAvi.Filter = "Avi Files (*.avi)|*.avi";
if (saveAvi.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int h = captureDevice.VideoDevice.VideoResolution.FrameSize.Height;
int w = captureDevice.VideoDevice.VideoResolution.FrameSize.Width;
FileWriter.Open(saveAvi.FileName, w, h,25,VideoCodec.Default,5000000);
FileWriter.WriteVideoFrame(video);
//AVIwriter.Open(saveAvi.FileName, w, h);
butStop.Text = "Stop Record";
//FinalVideo = captureDevice.VideoDevice;
//FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
//FinalVideo.Start();
}
}
private void butStop_Click(object sender, EventArgs e)
{
if (butStop.Text == "Stop Record")
{
butStop.Text = "Stop";
if (FinalVideo == null)
{ return; }
if (FinalVideo.IsRunning)
{
//this.FinalVideo.Stop();
FileWriter.Close();
//this.AVIwriter.Close();
pictureBox1.Image = null;
}
}
else
{
this.FinalVideo.Stop();
FileWriter.Close();
//this.AVIwriter.Close();
pictureBox1.Image = null;
}
}
private void button3_Click(object sender, EventArgs e)
{
pictureBox1.Image.Save("IMG" + DateTime.Now.ToString("hhmmss") + ".jpg");
}
private void button4_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalVideo == null)
{ return; }
if (FinalVideo.IsRunning)
{
this.FinalVideo.Stop();
FileWriter.Close();
//this.AVIwriter.Close();
}
}
}
}

Categories

Resources