Emgu CV check web cam connectivity - c#

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);

Related

How to Thumb Preview in Picture Box From Thumb Impression Device

I am trying to preview an image in picture box from Thumb Impression device. I am doing this successfully on button click which shows an image of my thumb on button click. But my requirement is, when i keep my thumb it should immediately shows my thumb without button click. Following is the code which i am using in button click. Please anyone guide.
private void GetMinDataBtn_Click(object sender, EventArgs e)
{
SGFingerPrintManager manager = new SGFingerPrintManager();
int deviceInfo = manager.Init(SGFPMDeviceName.DEV_AUTO);
deviceInfo = manager.OpenDevice(0);
try
{
this.m_TestMin.Initialize();
SGFPMDeviceInfoParam pInfo = new SGFPMDeviceInfoParam();
deviceInfo = manager.GetDeviceInfo(pInfo);
byte[] buffer = new byte[pInfo.ImageWidth * pInfo.ImageHeight]; //Here sometime it fails to load image through device. And sometimes it continously works without an issue.
deviceInfo = manager.GetImageEx(buffer, 0x1388, (int)this.FDxPicBox.Handle, 50);
if (manager.CreateTemplate(buffer, this.m_TestMin) == 0)
{
this.FdxToFIRBtn.Enabled = true;
this.VerifyBtn.Enabled = true;
this.StatusBar.Text = "Get Minutiae Data Success";
deviceInfo = manager.CloseDevice();
}
}
catch (Exception ex)
{
deviceInfo = manager.CloseDevice();
MessageBox.Show(ex.ToString());
this.StatusBar.Text = "Thumb data failed to get";
}
}

Windows Media Capture -402587628 error "The text associated with this error code could not be found."

private async Task InitializeCameraAsync()
{
if (_mediaCapture == null)
{
// Get available devices for capturing pictures
var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
// Get the desired camera by panel
DeviceInformation cameraDevice =
allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null &&
x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
// If there is no camera on the specified panel, get any camera
cameraDevice = cameraDevice ?? allVideoDevices.FirstOrDefault();
if (cameraDevice == null)
{
//ShowMessageToUser("No camera device found.");
Debug.WriteLine("No camera device found.");
return;
}
// Create MediaCapture and its settings
_mediaCapture = new MediaCapture();
// Register for a notification when video recording has reached the maximum time and when something goes wrong
//_mediaCapture.RecordLimitationExceeded += MediaCapture_RecordLimitationExceeded;
var mediaInitSettings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };
// Initialize MediaCapture
try
{
await _mediaCapture.InitializeAsync(mediaInitSettings);
_isInitialized = true;
}
catch (UnauthorizedAccessException)
{
//ShowMessageToUser("The app was denied access to the camera");
Debug.WriteLine("The app was denied access to the camera");
}
catch (Exception ex)
{
Debug.WriteLine("Exception when initializing MediaCapture with {0}: {1}", cameraDevice.Id, ex.ToString());
}
// If initialization succeeded, start the preview
if (_isInitialized)
{
// Figure out where the camera is located
if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
{
// No information on the location of the camera, assume it's an external camera, not integrated on the device
_externalCamera = true;
}
else
{
// Camera is fixed on the device
_externalCamera = false;
// Only mirror the preview if the camera is on the front panel
//_mirroringPreview = (cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
}
//await StartPreviewAsync();
//UpdateCaptureControls();
}
}
}
Problem appears in the second "catch" statement while trying to InitializeAsync mediaCapture.
How can I check what's wrong, if it doesn't provide me any error details?

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

Threading slowdown camera operation of live streaming

I am working on one project where I have implemented threading for processing images captured by the camera.
Please find the below code for ProcessFrame() which is called by the timer after some time Interval.
private void ProcessFrame()
{
try
{
Image<Bgr, Byte> ImageFrame;
// Get Image from the camera
ImageFrame = capture.QueryFrame();
// check if imageFrame is null or not
if (ImageFrame == null)
{
// if null then re- initialize the camera
try
{
capture.Dispose();
capture = new Capture(URL);
ImageFrame = capture.QueryFrame();
}
catch (Exception ex)
{
}
}
// resize image to show on Picture control
ImageFrame = ImageFrame.Resize(img.Width, img.Height, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR);
// show image on picture control
img.Image = ImageFrame;
try
{
#region Making directory and image in this code
string VerifyImageFolderId = VerifyImageFolder + "\\" + "Camera_" + (1) + "\\";
if (!Directory.Exists(VerifyImageFolderId))
Directory.CreateDirectory(VerifyImageFolderId);
string VerifyImageFileName = VerifyImageFolderId + "\\" + nSavedImagesCounter + ".jpg";
img.Image.Save(VerifyImageFileName); // Save Image
nSavedImagesCounter++;
#endregion
#region Starting thread For processing Image
Thread processImage = new Thread(new ThreadStart(() => ProcessImage(VerifyImageFileName)));
processImage.Start();
#endregion
}
catch (Exception ex)
{
Log(ex.Message);
MessageBox.Show(ex.Message);
}
finally
{
GC.Collect();
}
//#endregion
}
catch (NullReferenceException e)
{
Console.Write("Exception:\n" + DateTime.Now.ToString("hhmmss"));
}
}
Here, is the second function ProcessImage(string ImagePath) which is use to perform some file processing operations as follows:
private void ProcessImage(string ImagePath)
{
#region Check for threadSafeFunction
if (this.InvokeRequired)
{
Console.WriteLine("Inside InvokeRequired");
this.Invoke(new MethodInvoker(delegate() { ProcessImage(ImagePath); }));
}
else
{
1. Detect faces in Image
2. Draw Face markers on Image
3. Some database based on result of Face Detection
4. Delete image File
}
}
After adding of the threading working of ProcessFrame() function was slow down.
and I am not able to get the live streaming on display.
Can any one help me on this?
Thanks in advance.
i suggest you use queue for processing images
run this code once
BlockingCollection<string> imageQueue=new BlockingCollection<string>();
new Thread(() =>
{
foreach (string imagePath in imageQueue.GetConsumingEnumerable())
{
ProcessImage(imagePath);
}
}).Start();
and change ProcessFrame Like This
private void ProcessFrame()
{
.....
#region Starting thread For processing Image
imageQueue.Add(VerifyImageFileName);
#endregion
...
}

Categories

Resources