Display Video Frame of WebCam in C# Window Form - c#

I am currently using my Webcam to display video frame by creating another window. However, I had reserved a box for video displaying in my window form application and try not to create another window for video frame. How could i do it?
Attach my code for creating new video:
VideoCapture capture;
Mat frame;
capture = new VideoCapture();
frame = new Mat();
capture.Open(0);
string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test1.jpg";
//// Read the video stream
Cv2.NamedWindow("Video", WindowMode.AutoSize);
while (true)
{
if (capture.Read(frame))
{
Cv2.ImShow("Video", frame);
}
}
My window form application:
private void EmoStart_Click(object sender, EventArgs e)
{
VideoCapture capture;
Mat frame;
string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test1.jpg";
capture = new VideoCapture();
frame = new Mat();
capture.Open(0);
while (true)
{
if (capture.Read(frame))
{
pictureBox1.Image = capture.Read(frame);
}
}
}
Could the picture box read the captured frame?
When i try to open up another windows, both of them are freezed.
How could i attach the Webcam frame to my application form?
Thank you!

Related

Attempted to read or write protected memory when capture video using Emgu-CV

I try to capture video using Emgu-CV but I have an error. My code of the following:
Timer My_Time = new Timer();
int FPS = 30;
public Form1()
{
InitializeComponent();
//Frame Rate
My_Timer.Interval = 1000 / FPS;
My_Timer.Tick += new EventHandler(My_Timer_Tick);
My_Timer.Start();
_capture = new Capture("test.avi");
}
private void My_Timer_Tick(object sender, EventArgs e)
{
imageBox.Image = _capture.QueryFrame();
}
The error occurs at
_capture = new Capture("test.avi");
Thanks.
Detail
You should not start your timer before the instantiation of your Capture object.
It might be querying frames before your avi video is loaded.
Try just swapping this lines:
_capture = new Capture("test.avi");
My_Timer.Start();

Save App.RootFrame Background in wp8

I am using PhotoChooserTaskto pick a picture from photo gallery and then set this picture as my app background. Everything works fine, but when I exit my application it's not saved. What I am looking is to save this background for my application.
I am using below code:
photoChooserTask = new PhotoChooserTask()
photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
System.IO.IsolatedStorage.IsolatedStorageSettings settings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
imgCustom.Source = bmp;
System.Windows.Media.ImageBrush backgroundBrush = new System.Windows.Media.ImageBrush() { ImageSource = bmp };
App.RootFrame.Background = backgroundBrush;
}
}
What I am looking is, If I close and run my application, This background should not change unless the user changes it.
Thanks!
How about trying out this piece of code at the end:
var frame = App.Current.RootVisual as PhoneApplicationFrame;
frame.Background = backgroundBrush;
Reference: Windows Phone app background image

MediaRecorder doesn't start in android xamarin

I am developing an app where i can upload videos of upto 2 mins per user.
I want the user to record a video and upload it to the server.I am able to do it with intent but not with media recorder.
The requirement is to not allow user to preview the video and instead record it and when user stops recording, upload the video to server.
(Is it possible to not allow the playback of the recorded video in VIDEO_CAPTURE intent ???)
I am trying to record a video with media recorder. But it throws an exception at MediaRecorder.Start()
Here's the code : -
//Class level variables
Camera PhoneCamera;
VideoView VideoRecorderView;
MediaRecorder VideoRecorder;
Button BtnRecordVideo;
// I start a video recording on click of the button
void RecordVideoWithCustomRecorder(object sender,EventArgs e){
//TODO : Create a custom layout for recording video in one shot and then uplaoding it to kaltura server
if (IsRecording) {
VideoRecorder.Stop ();
ReleaseMediaRecorder ();
PhoneCamera.Lock ();
(sender as Button).SetBackgroundResource (Resource.Drawable.record_red);
StopTimer ();
//UploadVideo
byte[] getBytes = System.IO.File.ReadAllBytes (RecorderFile._file.AbsolutePath);
UploadVideoToKaltura (getBytes);
IsRecording = false;
} else {
ReleaseCamera ();
if (PrepareVideoRecorder ()) {
//System.Threading.Thread.Sleep (1000); i tried putting this, but it won't work
VideoRecorder.Start ();//I get an exception here - not sure why
RunOnUiThread (() => {
(sender as Button).SetBackgroundResource (Resource.Drawable.record_stop);
initTimer2 ();
IsRecording = true;
});
} else {
ReleaseMediaRecorder ();
RunOnUiThread (() => {
AlertDialogManager.ShowDialogWithSingleButton(this,"Video Error","Can't record the video now. Exit the camera and try recording again.","Exit Camera",(()=>{
this.Finish();
}));
});
}
}
}
//Here's the code to prepare the media recorder
bool PrepareVideoRecorder(){
PhoneCamera = IsFrontCameraAvailable ? Camera.Open (1) : Camera.Open ();
VideoRecorder = new MediaRecorder ();
//Unlock & set camera to media recorder
PhoneCamera.Unlock ();
VideoRecorder.SetCamera (PhoneCamera);
//Set Source - Video and audio
VideoRecorder.SetAudioSource (AudioSource.Camcorder);
VideoRecorder.SetVideoSource (VideoSource.Camera);
//set Camcorder profile
VideoRecorder.SetProfile(CamcorderProfile.Get(CamcorderQuality.High));
//set output file
RecorderFile._file = new File(RecorderFile._dir, String.Format("vm_movie_{0}.mp4", Guid.NewGuid()));
VideoRecorder.SetOutputFile (RecorderFile._file.AbsolutePath);
//set preview display
VideoRecorder.SetPreviewDisplay (VideoRecorderView.Holder.Surface);
//Prepare media recorder
VideoRecorder.SetMaxDuration (12000);
try{
VideoRecorder.Prepare();
}catch(Exception ex){
Utils.WriteDebugInfo ("Excepion -PrepareVideoRecorder: " + ex.Message);
return false;
}
return true;
}
//Release Media Recorder
private void ReleaseMediaRecorder(){
if (VideoRecorder != null) {
VideoRecorder.Reset(); // clear recorder configuration
VideoRecorder.Release(); // release the recorder object
VideoRecorder = null;
PhoneCamera.Lock(); // lock camera for later use
}
}
//Release Camers
private void ReleaseCamera(){
if (PhoneCamera != null){
PhoneCamera.Release ();
// release the camera for other applications
PhoneCamera = null;
}
}
//Creating app specific diary for videos
private void CreateDirectoryForVideos()
{
RecorderFile._dir = new File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures),"VirtualMentorVideos");
if (!RecorderFile._dir.Exists())
{
RecorderFile._dir.Mkdirs();
}
}

How to access the camera from my Windows Phone 8 app (XAML and C#) and save the taken picture in a determined folder?

I want the Windows Phone 8 app that I am building at this moment to access the camera for taking a photo when a concrete button on the screen is pressed and then save the image that has been taken into a determined folfer (a folder created into the Windows Phone project by me, not the Windows Phone default image gallery).
Could you help me accesing the camera, taking the picture and saving it into the folder created by me, please? I am using XAML and C#.
Thank you so much!!!
I would recommend PhotoCamera class if capture is to be processed on a button in the app
PhotoCamera myCamera = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
//viewfinderBrush is a videobrush object declared in xaml
viewfinderBrush.SetSource(myCamera);
myCamera.Initialized += myCamera_Initialized;
myCamera.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(camera_CaptureCompleted);
myCamera.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(camera_CaptureImageAvailable);
//Events
void myCamera_Initialized(object sender, CameraOperationCompletedEventArgs e)
{
try
{
if (e.Succeeded)
{
}
}
catch
{
MessageBox.Show("Problem occured in camera initialization.");
}
}
void camera_CaptureCompleted(object sender, CameraOperationCompletedEventArgs e)
{
try
{
}
catch
{
MessageBox.Show("Captured image is not available, please try again.");
}
}
void camera_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
{
try
{
}
catch (Exception ex)
{
MessageBox.Show("Captured image is not available, please try again. " + ex.Message);
}
}
And there is one more alternative called CameraCaptureTask
CameraCaptureTask cameraCaptureTask;
cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);
cameraCaptureTask.Show();
void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MessageBox.Show(e.ChosenPhoto.Length.ToString());
//Code to display the photo on the page in an image control named myImage.
//System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
//bmp.SetSource(e.ChosenPhoto);
//myImage.Source = bmp;
}
}
Check this for PhotoCamera class
And this for CameraCaptureTask
There's a simple code demonstration here showing your to put the camera API to use for Windows Phone8 apps.
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) ||
(PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true)) {
// Initialize the default camera.
_photoCamera = new Microsoft.Devices.PhotoCamera();
//Event is fired when the PhotoCamera object has been initialized
_photoCamera.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(OnPhotoCameraInitialized);
//Set the VideoBrush source to the camera
viewfinderBrush.SetSource(_photoCamera);
}
else {
// The camera is not supported on the device.
this.Dispatcher.BeginInvoke(delegate() {
// Write message.
txtDebug.Text = "A Camera is not available on this device.";
});
}
}
private void OnPhotoCameraInitialized(object sender, CameraOperationCompletedEventArgs e) {
int width = Convert.ToInt32(_photoCamera.PreviewResolution.Width);
int height = Convert.ToInt32(_photoCamera.PreviewResolution.Height);
}
Dont forget to add this line in WMAppManifent.xml file.
<Capability Name="ID_CAP_ISV_CAMERA"/>
you can read here ,
Using Cameras in Your Windows Phone Application

Emgu CV check web cam connectivity

I am writing a C# web camera application using Emgu CV. I tried to handle when user unplug the web cam during frame capturing in pictureBox.
If the web camera is unplugged, then the application should start scanning for new web cam connectivity every 2 seconds until the pictureBox can be updated again.
The following timer code could not catch anything, the program initially captures frames, I unplug the camera, then plug back, but the camera can not be restart.
private void timer1_Tick(object sender, EventArgs e)
{
if (cap == null)
{
try
{
cap = new Capture(0);
cap.SetCaptureProperty(CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, 320);
cap.SetCaptureProperty(CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, 240);
Console.WriteLine("Restarting Cam");
}
catch (Exception ee){
Console.WriteLine("null"); cap = null; return;
}
}
else
{
Console.WriteLine("NO null");
}
try
{
Image<Bgr, byte> nextFrame = cap.QueryFrame();
}
catch(Exception ee)
{
Console.WriteLine("Frame Capture fail");
cap.Dispose();
cap = null;
return;
}
using (Image<Bgr, byte> nextFrame = cap.QueryFrame())
{
if (nextFrame != null)
{
Image<Gray, byte> grayframe = nextFrame.Convert<Gray, byte>();
videoBox.Image = nextFrame.ToBitmap();
}
}
}
The program keep printing "No null", 20 second after unplugging the camera, the output console printed out The thread '' (0xb96c) has exited with code 0 (0x0)
You can check connectivity with DirectShow lib. Get an array of all connected cameras first
DirectShowLib.DsDevice[] allCameras = DirectShowLib.DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
add to you class property for selected camera name, and then you can check if camera is connected
bool isConnected = DirectShowLib.DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice).Any(c => c.Name == selectedCameraName);

Categories

Resources