public void StartFacialRecognition(Point formLocation, List <byte[]> faceJpg) { try { //this.FaceJpg = (FaceJpg != null ? FaceJpg : new List<byte[]>()).Where(d => d != null).ToList(); //this.FaceJpg = FaceJpg; _failedCount = 0; _suceededCount = 0; if (libFace != null && !isStartTracking && faceJpg.Count > 0) { isStartTracking = true; libFace.Init(); OnCameraInitialized?.Invoke(); libFace.Show_Window(formLocation, new Size(800, 450)); OnFacialRecognitionProcessing(); //Thread.Sleep(1000); libFace.FaceDetect += lib_FaceDetect; libFace.StartTracking(); try { libFace.Photo_JPG = faceJpg[0]; } catch (Exception ex) { MessageBox.Show(ex.Message); if (faceJpg.Count > 1) { libFace.Photo_JPG = faceJpg[1]; } } faceJpg.RemoveAt(0); } else if (!isStartTracking && faceJpg.Count == 0) { OnFacialRecognitionFailed(); } } catch (Exception ex) { MessageBox.Show(ex.Message); OnFacialRecognitionFailed(); } }
async Task <Result> PlatformScan(MobileBarcodeScanningOptions options) { var rootFrame = RootFrame ?? Window.Current.Content as Frame ?? ((FrameworkElement)Window.Current.Content).GetFirstChildOfType <Frame>(); var dispatcher = Dispatcher ?? Window.Current.Dispatcher; var tcsScanResult = new TaskCompletionSource <Result>(); await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var pageOptions = new ScanPageNavigationParameters { Options = options, ResultHandler = r => { tcsScanResult.SetResult(r); }, Scanner = this, ContinuousScanning = false, CameraInitialized = () => { OnCameraInitialized?.Invoke(); }, CameraError = (errors) => { OnCameraError?.Invoke(errors); } }; rootFrame.Navigate(typeof(ScanPage), pageOptions); }); var result = await tcsScanResult.Task; await dispatcher.RunAsync(CoreDispatcherPriority.High, () => { if (rootFrame.CanGoBack) { rootFrame.GoBack(); } }); return(result); }
public async Task StartScanningAsync(Action <ZXing.Result> scanCallback, MobileBarcodeScanningOptions options = null) { if (stopping) { var error = "Camera is closing"; OnScannerError?.Invoke(new[] { error }); return; } displayRequest.RequestActive(); isAnalyzing = true; ScanCallback = scanCallback; ScanningOptions = options ?? MobileBarcodeScanningOptions.Default; topText.Text = TopText ?? string.Empty; bottomText.Text = BottomText ?? string.Empty; if (UseCustomOverlay) { gridCustomOverlay.Children.Clear(); if (CustomOverlay != null) { gridCustomOverlay.Children.Add(CustomOverlay); } gridCustomOverlay.Visibility = Visibility.Visible; gridDefaultOverlay.Visibility = Visibility.Collapsed; } else { gridCustomOverlay.Visibility = Visibility.Collapsed; gridDefaultOverlay.Visibility = Visibility.Visible; } // Find which device to use var preferredCamera = await GetFilteredCameraOrDefaultAsync(ScanningOptions); if (preferredCamera == null) { var error = "No camera available"; System.Diagnostics.Debug.WriteLine(error); isMediaCaptureInitialized = false; OnScannerError?.Invoke(new[] { error }); return; } if (preferredCamera.EnclosureLocation == null || preferredCamera.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 = preferredCamera.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front; } mediaCapture = new MediaCapture(); // Initialize the capture with the settings above try { await mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings { StreamingCaptureMode = StreamingCaptureMode.Video, VideoDeviceId = preferredCamera.Id }); isMediaCaptureInitialized = true; } catch (UnauthorizedAccessException) { System.Diagnostics.Debug.WriteLine("Denied access to the camera"); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Exception when init MediaCapture: {0}", ex); } if (!isMediaCaptureInitialized) { var error = "Unexpected error on Camera initialisation"; OnScannerError?.Invoke(new[] { error }); return; } // Set the capture element's source to show it in the UI captureElement.Source = mediaCapture; captureElement.FlowDirection = mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; try { // Start the preview await mediaCapture.StartPreviewAsync(); } catch (Exception ex) { var error = "Unexpected error on Camera initialisation"; OnScannerError?.Invoke(new[] { error }); return; } if (mediaCapture.CameraStreamState == CameraStreamState.Streaming) { OnCameraInitialized?.Invoke(); } // Get all the available resolutions for preview var availableProperties = mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview); var availableResolutions = new List <CameraResolution>(); foreach (var ap in availableProperties) { var vp = (VideoEncodingProperties)ap; System.Diagnostics.Debug.WriteLine("Camera Preview Resolution: {0}x{1}", vp.Width, vp.Height); availableResolutions.Add(new CameraResolution { Width = (int)vp.Width, Height = (int)vp.Height }); } CameraResolution previewResolution = null; if (ScanningOptions.CameraResolutionSelector != null) { previewResolution = ScanningOptions.CameraResolutionSelector(availableResolutions); } if (availableResolutions == null || availableResolutions.Count < 1) { var error = "Camera is busy. Try to close all applications that use camera."; OnScannerError?.Invoke(new[] { error }); return; } // If the user did not specify a resolution, let's try and find a suitable one if (previewResolution == null) { // Loop through all supported sizes foreach (var sps in availableResolutions) { // Find one that's >= 640x360 but <= 1000x1000 // This will likely pick the *smallest* size in that range, which should be fine if (sps.Width >= 640 && sps.Width <= 1000 && sps.Height >= 360 && sps.Height <= 1000) { previewResolution = new CameraResolution { Width = sps.Width, Height = sps.Height }; break; } } } if (previewResolution == null) { previewResolution = availableResolutions.LastOrDefault(); } if (previewResolution == null) { System.Diagnostics.Debug.WriteLine("No preview resolution available. Camera may be in use by another application."); return; } MobileBarcodeScanner.Log("Using Preview Resolution: {0}x{1}", previewResolution.Width, previewResolution.Height); // Find the matching property based on the selection, again var chosenProp = availableProperties.FirstOrDefault(ap => ((VideoEncodingProperties)ap).Width == previewResolution.Width && ((VideoEncodingProperties)ap).Height == previewResolution.Height); // Pass in the requested preview size properties // so we can set them at the same time as the preview rotation // to save an additional set property call await SetPreviewRotationAsync(chosenProp); // *after* the preview is setup, set this so that the UI layout happens // otherwise the preview gets stuck in a funny place on screen captureElement.Stretch = Stretch.UniformToFill; await SetupAutoFocus(); var zxing = ScanningOptions.BuildBarcodeReader(); timerPreview = new Timer(async(state) => { var delay = ScanningOptions.DelayBetweenAnalyzingFrames; if (stopping || processing || !isAnalyzing || (mediaCapture == null || mediaCapture.CameraStreamState != Windows.Media.Devices.CameraStreamState.Streaming)) { timerPreview.Change(delay, Timeout.Infinite); return; } processing = true; SoftwareBitmapLuminanceSource luminanceSource = null; try { // Get preview var frame = await mediaCapture.GetPreviewFrameAsync(videoFrame); // Create our luminance source luminanceSource = new SoftwareBitmapLuminanceSource(frame.SoftwareBitmap); } catch (Exception ex) { MobileBarcodeScanner.Log("GetPreviewFrame Failed: {0}", ex); } ZXing.Result result = null; try { // Try decoding the image if (luminanceSource != null) { result = zxing.Decode(luminanceSource); } } catch (Exception ex) { MobileBarcodeScanner.Log("Warning: zxing.Decode Failed: {0}", ex); } // Check if a result was found if (result != null && !string.IsNullOrEmpty(result.Text)) { if (!ContinuousScanning) { delay = Timeout.Infinite; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { await StopScanningAsync(); }); } else { delay = ScanningOptions.DelayBetweenContinuousScans; } LastScanResult = result; ScanCallback(result); } processing = false; timerPreview.Change(delay, Timeout.Infinite); }, null, ScanningOptions.InitialDelayBeforeAnalyzingFrames, Timeout.Infinite); }
/// <summary> /// Initializes the camera /// </summary> /// <returns></returns> public async Task Initialize() { lock (stateLock) { State = CameraState.Initializing; } #if CAN_USE_UWP_TYPES try { var frameSourceGroups = await MediaFrameSourceGroup.FindAllAsync(); StreamSelector = new StreamSelector(); foreach (var sourceGroup in frameSourceGroups) { string name = sourceGroup.DisplayName; string id = sourceGroup.Id; foreach (var sourceInfo in sourceGroup.SourceInfos) { switch (CaptureMode) { case CaptureMode.Continuous: case CaptureMode.SingleLowLatency: { if ((sourceInfo.MediaStreamType == MediaStreamType.VideoRecord || sourceInfo.MediaStreamType == MediaStreamType.VideoPreview) && sourceInfo.SourceKind == MediaFrameSourceKind.Color) { foreach (var setting in sourceInfo.VideoProfileMediaDescription) { StreamDescriptionInternal desc = new StreamDescriptionInternal() { SourceName = sourceInfo.DeviceInformation.Name, SourceId = sourceInfo.Id, Resolution = new CameraResolution() { Width = setting.Width, Height = setting.Height, Framerate = setting.FrameRate }, FrameSourceInfo = sourceInfo, FrameSourceGroup = sourceGroup, CameraType = GetCameraType(sourceInfo.SourceKind) }; StreamSelector.AddStream(desc); } } break; } case CaptureMode.Single: { if (sourceInfo.MediaStreamType == MediaStreamType.Photo && sourceInfo.SourceKind == MediaFrameSourceKind.Color) { foreach (var setting in sourceInfo.VideoProfileMediaDescription) { StreamDescriptionInternal desc = new StreamDescriptionInternal() { SourceName = sourceInfo.DeviceInformation.Name, SourceId = sourceInfo.Id, Resolution = new CameraResolution() { Width = setting.Width, Height = setting.Height, Framerate = setting.FrameRate }, FrameSourceInfo = sourceInfo, FrameSourceGroup = sourceGroup, CameraType = GetCameraType(sourceInfo.SourceKind) }; StreamSelector.AddStream(desc); } } break; } } } } lock (stateLock) { State = CameraState.Initialized; OnCameraInitialized?.Invoke(this, true); } } catch { OnCameraInitialized?.Invoke(this, false); } #else await Task.CompletedTask; #endif }