Esempio n. 1
0
        public async Task CaptureToFile()
        {
            //<SnippetCaptureToFile>
            var myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);

            StorageFile file = await myPictures.SaveFolder.CreateFileAsync("photo.jpg", CreationCollisionOption.GenerateUniqueName);

            using (var captureStream = new InMemoryRandomAccessStream())
            {
                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var decoder = await BitmapDecoder.CreateAsync(captureStream);

                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                    var properties = new BitmapPropertySet {
                        { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) }
                    };
                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.FlushAsync();
                }
            }
            //</SnippetCaptureToFile>
        }
Esempio n. 2
0
        /// <summary>
        /// Captures a photo. Photo data is stored to ImageStream, and
        /// application is navigated to the preview page after capturing.
        /// </summary>
        private async Task Capture()
        {
            bool goToPreview = false;

            if (!_capturing)
            {
                CapturePreview.Source = null;
                Progress.IsActive     = true;
                _capturing            = true;

                _dataContext.ResetStreams();

                IRandomAccessStream stream = _dataContext.FullResolutionStream.AsRandomAccessStream();
                await _photoCaptureManager.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                await _photoCaptureManager.StopPreviewAsync();

                await AppUtils.ScaleImageStreamAsync(
                    _dataContext.FullResolutionStream,
                    _dataContext.FullResolution,
                    _dataContext.PreviewResolutionStream,
                    _dataContext.PreviewResolution);

                _capturing  = false;
                goToPreview = true;
            }

            if (goToPreview)
            {
                _dataContext.WasCaptured = true;
                Frame.Navigate(typeof(PreviewPage));
            }
        }
Esempio n. 3
0
        private async Task <Result> GetCameraImage(CancellationToken cancelToken)
        {
            if (cancelToken.IsCancellationRequested)
            {
                throw new OperationCanceledException(cancelToken);
            }

            imageStream = new InMemoryRandomAccessStream();

            await capture.CapturePhotoToStreamAsync(encodingProps, imageStream);

            await imageStream.FlushAsync();

            var decoder = await BitmapDecoder.CreateAsync(imageStream);

            byte[] pixels =
                (await
                 decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8,
                                           BitmapAlphaMode.Ignore,
                                           new BitmapTransform(),
                                           ExifOrientationMode.IgnoreExifOrientation,
                                           ColorManagementMode.DoNotColorManage)).DetachPixelData();

            const BitmapFormat format = BitmapFormat.RGB32;

            imageStream.Dispose();

            var result =
                await
                Task.Run(
                    () => barcodeReader.Decode(pixels, (int)decoder.PixelWidth, (int)decoder.PixelHeight, format),
                    cancelToken);

            return(result);
        }
        public async Task CapturePhoto()
        {
            try
            {
                if ((App.Current as App).IsProcessingPicture)
                {
                    return;
                }
                (App.Current as App).IsProcessingPicture = true;
                using (var randomAccessStream = new InMemoryRandomAccessStream())
                {
                    await mediaCapture.CapturePhotoToStreamAsync(Windows.Media.MediaProperties.ImageEncodingProperties.CreateJpeg(), randomAccessStream);

                    randomAccessStream.Seek(0);
                    var outStream = new InMemoryRandomAccessStream();
                    var task      = new Task(() =>
                    {
                        this.EncodedPhoto(randomAccessStream, outStream);
                    });
                    task.Start();
                    Frame.Navigate(typeof(PictureEdit), outStream);
                };
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Esempio n. 5
0
        public async Task <byte[]> CapturePhotoWithOrientationAsync()
        {
            var captureStream = new InMemoryRandomAccessStream();
            var outputStream  = new InMemoryRandomAccessStream();

            try
            {
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);
            }
            catch (Exception ex)
            {
                _loggingService.Warning("Exception when taking a photo: {Ex}", ex);
                await _dialogService.ShowAsync("Could not take a photo. Please try again.");

                return(new byte[0]);
            }

            var decoder = await BitmapDecoder.CreateAsync(captureStream);

            var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);

            var cameraOrientation      = _cameraRotationHelper.GetCameraCaptureOrientation();
            var simplePhotoOrientation = _cameraRotationHelper.MirrorOrientation(cameraOrientation);
            var photoOrientation       = _cameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(simplePhotoOrientation);
            var properties             = new BitmapPropertySet {
                { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) }
            };
            await encoder.BitmapProperties.SetPropertiesAsync(properties);

            await encoder.FlushAsync();

            var rawBytes = await _bitmapConverter.GetBytesFromStream(outputStream);

            return(rawBytes);
        }
        /// <summary>
        /// Takes a photo to a StorageFile and adds rotation metadata to it
        /// </summary>
        /// <returns></returns>
        private async Task TakeNormalPhotoAsync()
        {
            var stream = new InMemoryRandomAccessStream();

            try
            {
                Debug.WriteLine("Taking photo...");

                // Generate a filename based on the current time
                var fileName = String.Format("SimplePhoto_{0}.jpg", DateTime.Now.ToString("HHmmss"));

                // Get the orientation of the camera at the time of capture
                var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());

                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                Debug.WriteLine("Photo taken!");

                await ReencodeAndSavePhotoAsync(stream, fileName, photoOrientation);
            }
            catch (Exception ex)
            {
                // File I/O errors are reported as exceptions
                Debug.WriteLine("Exception when taking a photo: {0}", ex.ToString());
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Основная функция, срабатывающая по таймеру
        /// Распознаёт эмоции
        /// </summary>
        async void GetEmotions(object sender, object e)
        {
            if (!IsFacePresent)
            {
                return;
            }
            dt.Stop();

            var ms = new MemoryStream();

            try
            {
                // Запоминаем фотографию в поток в памяти
                await MC.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), ms.AsRandomAccessStream());
            }
            catch { dt.Start(); return; }

            ms.Position = 0L;
            var Emo = await Oxford.RecognizeAsync(ms);

            // ^^^ основной вызов распознавателя эмоций
            if (Emo != null && Emo.Length > 0)
            // если обнаружено одно и более лицо
            {
                var Face = Emo[0]; // берем первое (нулевое) лицо
                                   // Face.Scores - запись с различными эмоциями (Fear,Surprise,...)

                Info.Text = ((int)(100 * Face.Scores.Happiness)).ToString();
            }
            dt.Start(); // перезапускаем таймер
        }
        async private void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var vm = this.DataContext as CameraCapturePageViewModel;
                var imageEncodingProps = ImageEncodingProperties.CreatePng();
                using (var stream = new InMemoryRandomAccessStream())
                {
                    await _mediaCapture.CapturePhotoToStreamAsync(imageEncodingProps, stream);

                    _bytes = new byte[stream.Size];
                    var buffer = await stream.ReadAsync(_bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);

                    _bytes = buffer.ToArray(0, (int)stream.Size);

                    if (vm.ImageSource == null)
                    {
                        vm.ImageSource = new BitmapImage();
                    }
                    stream.Seek(0);
                    await vm.ImageSource.SetSourceAsync(stream);

                    Retake.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    Take.Visibility   = Windows.UI.Xaml.Visibility.Collapsed;
                    await _mediaCapture.StopPreviewAsync();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task TakePhotoAsync(Action <SoftwareBitmapSource> callback)
        {
            //kada uslika postaviti svoj stream
            Slika = new InMemoryRandomAccessStream();
            try
            {
                //konvertovati uslikano u Software bitmap da se moze prikazati u image kontroli
                await MediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateBmp(), Slika);

                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(Slika);

                SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap,
                                                                           BitmapPixelFormat.Bgra8,
                                                                           BitmapAlphaMode.Premultiplied);
                SlikaBitmap = new SoftwareBitmapSource();
                await SlikaBitmap.SetBitmapAsync(softwareBitmapBGR8);

                callback(SlikaBitmap);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception when taking a photo: {0}", ex.ToString());
            }
        }
Esempio n. 10
0
        private async void button_Click(object sender, RoutedEventArgs e)
        {
            button.IsEnabled  = false;
            button2.IsEnabled = false;
            PB.Visibility     = Visibility.Visible;
            using (var captureStream = new InMemoryRandomAccessStream())
            {
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

                using (var s = captureStream.AsStream())
                {
                    //await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreatePng(), file);
                    var credentials = new StorageCredentials("vrdreamer", "lTD5XmjEhvfUsC/vVTLsl01+8pJOlMdF/ri7W1cNOydXwSdb8KQpDbiveVciOqdIbuDu6gJW8g44YtVjuBzFkQ==");
                    var client      = new CloudBlobClient(new Uri("https://vrdreamer.blob.core.windows.net/"), credentials);
                    var container   = client.GetContainerReference("datasetimages");

                    var blockBlob = container.GetBlockBlobReference(Guid.NewGuid().ToString() + ".jpeg");
                    s.Position = 0;

                    await blockBlob.UploadFromStreamAsync(s);

                    ////await blockBlob.UploadFromFileAsync(captureStream);
                    blobUrl = blockBlob.StorageUri.PrimaryUri.ToString();
                    var add = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36";
                    var httpRequestMessage = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, new Uri("http://www.google.com/searchbyimage?site=search&sa=X&image_url=" + blockBlob.StorageUri.PrimaryUri.ToString()));
                    httpRequestMessage.Headers.Add("User-Agent", add);
                    //items2 = await Table2.ToCollectionAsync();
                    web.NavigateWithHttpRequestMessage(httpRequestMessage);
                    web.DOMContentLoaded += Web_DOMContentLoaded;
                }
            }
        }
Esempio n. 11
0
        public async Task<string> TakePhoto()
        {
            if (_capturing)
            {
                return null;
            }

            _capturing = true;

            using (var stream = new InMemoryRandomAccessStream())
            {
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                var photoOrientation = _displayInformation.ToSimpleOrientation(_deviceOrientation, _mirroringPreview).ToPhotoOrientation();

                if (_mirroringPreview)
                {
                    photoOrientation = PhotoOrientation.FlipHorizontal;
                }

                var photo = await ReencodeAndSavePhotoAsync(stream, photoOrientation);
                PhotoTaken?.Invoke(this, new CameraControlEventArgs(photo));
                _capturing = false;
                return photo;
            }
        }
Esempio n. 12
0
        public async Task <Stream> GetCurrentFrameAsync()
        {
            if (CurrentState != ScenarioState.Streaming)
            {
                return(null);
            }

            // If a lock is being held it means we're still waiting for processing work on the previous frame to complete.
            // In this situation, don't wait on the semaphore but exit immediately.
            if (!frameProcessingSemaphore.Wait(0))
            {
                return(null);
            }

            try
            {
                var stream = new InMemoryRandomAccessStream();
                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                stream.Seek(0);
                return(stream.AsStreamForRead());
            }
            catch
            {
            }
            finally
            {
                frameProcessingSemaphore.Release();
            }

            return(null);
        }
Esempio n. 13
0
        private async void ImageUpload(string deviceId)
        {
            try
            {
                using (Windows.Storage.Streams.InMemoryRandomAccessStream captureStream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                {
                    await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

                    await captureStream.FlushAsync();

                    captureStream.Seek(0);

                    // Drops file onto device file system for debugging only
#if DEBUG
                    IStorageFile photoFile = await KnownFolders.PicturesLibrary.CreateFileAsync("Timelapse.jpg", CreationCollisionOption.ReplaceExisting);

                    ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
                    await mediaCapture.CapturePhotoToStorageFileAsync(imageProperties, photoFile);
#endif
                    LoggingService.Log("ImageUploadService Upload starting");
                    ImageUploadService.Upload(deviceId, captureStream);
                    LoggingService.Log("ImageUploadService Upload done");
                }
            }
            catch (Exception ex)
            {
                LoggingService.Error($"Image capture or upload failed ", ex);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Takes a photo to a StorageFile and adds rotation metadata to it
        /// </summary>
        /// <returns></returns>
        private async Task TakeNormalPhotoAsync()
        {
            var stream = new InMemoryRandomAccessStream();

            try
            {
                Debug.WriteLine("Taking photo...");

                // Read the current orientation of the camera and the capture time
                var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
                var fileName         = String.Format("SimplePhoto_{0}.jpg", DateTime.Now.ToString("HHmmss"));

                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                var file = await _captureFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);

                Debug.WriteLine("Photo taken! Saving to " + file.Path);

                await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);
            }
            catch (Exception ex)
            {
                // File I/O errors are reported as exceptions
                Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
            }
        }
Esempio n. 15
0
        public MainPage()
        {
            this.InitializeComponent();

            InitAsync();

            Timer.Interval = TimeSpan.FromSeconds(3);

            Timer.Tick += async(sender, o) =>
            {
                if (!(MediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) is VideoEncodingProperties properties))
                {
                    return;
                }

                //Jpeg形式でガメラの最大解像度で取得する。
                var property = ImageEncodingProperties.CreateJpeg();
                property.Width  = properties.Width;
                property.Height = properties.Height;

                using (var randomStream = new InMemoryRandomAccessStream())
                {
                    await MediaCapture.CapturePhotoToStreamAsync(property, randomStream);

                    randomStream.Seek(0);

                    var peoplePhotoUrl = await UploadToBlob(randomStream);

                    this.FaceResultText.Text = GetCongestionText((await PredictionWithCustomVisionService(peoplePhotoUrl)));

                    //var detectedFaces = await DetectFaceAsync(randomStream);
                    //this.FaceResultText.Text = $"{detectedFaces.Count} 個。{GetCongestionText(detectedFaces.Count)}";
                }
            };
        }
Esempio n. 16
0
        private async void CounterCallback(object sender, object e)
        {
            counter--;
            Counter.Text = counter.ToString();
            if (counter == 0)
            {
                dt.Stop();
                if (DFace == null)
                {
                    return;
                }
                var ms = new MemoryStream();
                await MC.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), ms.AsRandomAccessStream());

                Point p; Size sz;
                ExpandFaceRect1(DFace.FaceBox, out p, out sz);
                var cb = await CropBitmap.GetCroppedBitmapAsync(ms.AsRandomAccessStream(), p, sz, 1);

                Faces.Add(cb);
                var res = await CallCognitiveFunction(ms);

                ResultImage.Source = new BitmapImage(new Uri(res));
                await WriteableBitmapToStorageFile(cb);

                Counter.Visibility = Visibility.Collapsed;
            }
        }
Esempio n. 17
0
        private void CaptureCameraSnapshot()
        {
            var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                animCameraTimer.Stop();
                animCameraTimer.Begin();
            });

            if (_mediaCapture.CameraStreamState != Windows.Media.Devices.CameraStreamState.Streaming)
            {
                return;
            }
            IRandomAccessStream stream = new InMemoryRandomAccessStream();

            try
            {
                IAsyncAction action = _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
                action.Completed = (result, status) =>
                {
                    if (status == AsyncStatus.Completed)
                    {
                        OnCapturePhotoCompleted(stream, result, status);
                    }
                };
            }
            catch (Exception)
            {
                if (stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }
            }
        }
Esempio n. 18
0
        private async void Button_Tapped(object sender, TappedRoutedEventArgs e)
        {
            StorageFolder picturesLibrary     = KnownFolders.PicturesLibrary;
            StorageFolder savedPicturesFolder = await picturesLibrary.CreateFolderAsync("PhotoApp Pictures", CreationCollisionOption.OpenIfExists);

            StorageFile file = await savedPicturesFolder.CreateFileAsync("photo.jpg", CreationCollisionOption.GenerateUniqueName);

            using (var captureStream = new InMemoryRandomAccessStream())
            {
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var decoder = await BitmapDecoder.CreateAsync(captureStream);

                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                    var properties = new BitmapPropertySet {
                        { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) }
                    };
                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.FlushAsync();
                }
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Takes a photo to a StorageFile and adds rotation metadata to it
        /// </summary>
        /// <returns></returns>
        private async Task TakePhotoAsync()
        {
            var stream = new InMemoryRandomAccessStream();

            Debug.WriteLine("Taking photo...");
            await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

            try
            {
                var file = await _captureFolder.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.ReplaceExisting);

                Debug.WriteLine("Photo taken! Saving to " + file.Path);

                var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());

                await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);

                Debug.WriteLine("Photo saved!");
            }
            catch (Exception ex)
            {
                // File I/O errors are reported as exceptions
                Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
            }
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            var myPictures = await StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);

            var file = await myPictures.SaveFolder.CreateFileAsync("xaml-islands.jpg", CreationCollisionOption.GenerateUniqueName);

            using (var captureStream = new InMemoryRandomAccessStream())
            {
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var decoder = await BitmapDecoder.CreateAsync(captureStream);

                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                    var properties = new BitmapPropertySet {
                        { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) }
                    };
                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.FlushAsync();

                    imgCollection.Add(file.Path);
                }
            }
        }
Esempio n. 21
0
        async void OnCameraPreviewTapped(object sender, TappedRoutedEventArgs e)
        {
            var stream = new InMemoryRandomAccessStream();

            if (isPreviewing)
            {
                await mediaCapture.StopPreviewAsync();

                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                // transforma em bytes
                var reader = new DataReader(stream.GetInputStreamAt(0));
                var bytes  = new byte[stream.Size];
                await reader.LoadAsync((uint)stream.Size);

                reader.ReadBytes(bytes);

                Xamarin.Forms.DependencyService.Get <ICameraOption>().ImagemCapturada(bytes);

                isPreviewing = false;
            }
            else
            {
                await mediaCapture.StartPreviewAsync();

                isPreviewing = true;
            }
        }
Esempio n. 22
0
        public async Task TakePhotoAsync()
        {
            var stream = new InMemoryRandomAccessStream();

            imeSlike = "Slika" + redniBroj.ToString() + ".jpg";
            redniBroj++;
            Debug.WriteLine("Taking photo...");
            await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

            //var ovajfolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            //_captureFolder = await ovajfolder.GetFolderAsync("Slike");
            //_captureFolder = ovajfolder;
            var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);

            // Fall back to the local app storage if the Pictures Library is not available
            _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
            //_captureFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Slike\\");
            try
            {
                var file = await _captureFolder.CreateFileAsync(imeSlike, CreationCollisionOption.GenerateUniqueName);

                Debug.WriteLine("Photo taken! Saving to " + file.Path);
                mjesto = file.Path;
                await ReencodeAndSavePhotoAsync(stream, file, PhotoOrientation.Normal);

                Debug.WriteLine("Photo saved!");
            }
            catch (Exception ex)
            {
                // File I/O errors are reported as exceptions
                Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Detect face by using local function.
        /// </summary>
        private async Task <InMemoryRandomAccessStream> DetectFaceAsync()
        {
            var imgFormat = ImageEncodingProperties.CreateJpeg();

            while (true)
            {
                try
                {
                    var stream = new InMemoryRandomAccessStream();
                    await mediaCapture.CapturePhotoToStreamAsync(imgFormat, stream);

                    var image = await ImageConverter.ConvertToSoftwareBitmapAsync(stream);

                    detectedFaces = await faceDetector.DetectFacesAsync(image);

                    if (detectedFaces.Count == 0)
                    {
                        continue;
                    }
                    else if (detectedFaces.Count != 1)
                    {
                        Message = "too many faces!";
                    }
                    else
                    {
                        return(stream);
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
Esempio n. 24
0
        private async Task<ImageAnalyzer> CapturePhotoAsync()
        {
            try
            {
                var stream = new MemoryStream();
                await captureManager.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream.AsRandomAccessStream());
                stream.Position = 0;

                ImageAnalyzer imageWithFace = new ImageAnalyzer(stream.ToArray());
                imageWithFace.ShowDialogOnFaceApiErrors = this.ShowDialogOnApiErrors;
                imageWithFace.FilterOutSmallFaces = this.FilterOutSmallFaces;
                imageWithFace.UpdateDecodedImageSize(this.CameraResolutionHeight, this.CameraResolutionWidth);

                return imageWithFace;
            }
            catch (Exception ex)
            {
                if (this.ShowDialogOnApiErrors)
                {
                    await Util.GenericApiCallExceptionHandler(ex, "Error capturing photo.");
                }
            }

            return null;
        }
        /// <summary>
        /// Takes a photo to a StorageFile and adds rotation metadata to it
        /// </summary>
        /// <returns></returns>
        private async Task TakePhotoAsync()
        {
            // While taking a photo, keep the video button enabled only if the camera supports simultaneosly taking pictures and recording video
            VideoButton.IsEnabled = _mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported;

            // Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
            VideoButton.Opacity = VideoButton.IsEnabled ? 1 : 0;

            var stream = new InMemoryRandomAccessStream();

            try
            {
                Debug.WriteLine("Taking photo...");
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                Debug.WriteLine("Photo taken!");

                var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());

                await ReencodeAndSavePhotoAsync(stream, photoOrientation);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception when taking a photo: {0}", ex.ToString());
            }

            // Done taking a photo, so re-enable the button
            VideoButton.IsEnabled = true;
            VideoButton.Opacity   = 1;
        }
Esempio n. 26
0
        public static async void CaptureOnePhoto(int type, Action <IRandomAccessStream> overAction)
        {
            var captureTime = DateTime.Now;

            if (type == 0)
            {
                using (IRandomAccessStream s = new InMemoryRandomAccessStream())
                {
                    await MainCamera.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), s);

                    overAction(s);
                }
            }
            else if (type == 1)
            {
                if (LowLag == null)
                {
                    return;
                }
                var photoData = await LowLag.CaptureAsync();

                using (var stream = photoData.Frame.CloneStream())
                {
                    overAction(stream);
                }
            }
        }
        /// <summary>
        /// Takes a photo to a StorageFile and adds rotation metadata to it
        /// </summary>
        /// <returns></returns>
        private async Task TakePhotoAsync()
        {
            // While taking a photo, keep the video button enabled only if the camera supports simultaneously taking pictures and recording video
            VideoButton.IsEnabled = _mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported;

            // Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
            VideoButton.Opacity = VideoButton.IsEnabled ? 1 : 0;

            var stream = new InMemoryRandomAccessStream();

            Debug.WriteLine("Taking photo...");
            await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

            try
            {
                var file = await _captureFolder.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.GenerateUniqueName);

                Debug.WriteLine("Photo taken! Saving to " + file.Path);

                var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());

                await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);

                Debug.WriteLine("Photo saved!");
            }
            catch (Exception ex)
            {
                // File I/O errors are reported as exceptions
                Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
            }

            // Done taking a photo, so re-enable the button
            VideoButton.IsEnabled = true;
            VideoButton.Opacity   = 1;
        }
Esempio n. 28
0
        /// <summary>
        /// Основная функция, срабатывающая по таймеру
        /// Распознаёт эмоции
        /// </summary>
        async void GetEmotions(object sender, object e)
        {
            if (!IsFacePresent)
            {
                return;
            }
            dt.Stop();
            var ms = new MemoryStream();

            try
            {
                // Запоминаем фотографию в поток в памяти
                await MC.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), ms.AsRandomAccessStream());
            }
            catch { dt.Start(); return; }

            ms.Position = 0L;
            var Emo = await Oxford.RecognizeAsync(ms);

            // ^^^ основной вызов распознавателя эмоций
            if (Emo != null && Emo.Length > 0)
            // если обнаружено одно и более лицо
            {
                var Face = Emo[0]; // берем первое (нулевое) лицо
                // Face.Scores - запись с различными эмоциями (Fear,Surprise,...)
                // Сериализуем в JSON
                var s = JsonConvert.SerializeObject(Face.Scores);

                // TODO: Здесь мы можем делать что хотим с сериализованной строкой
                // Например, печатать:
                System.Diagnostics.Debug.WriteLine(s);
            }
            dt.Start(); // перезапускаем таймер
        }
Esempio n. 29
0
        /// <summary>
        /// Central button clicked to take a picture
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            await StopCapture();

            var myPictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);

            StorageFile file = await myPictures.SaveFolder.CreateFileAsync(
                Path.Combine(Protocol.NewFaceFolder, UserManager.Instance.CurrentProfile.Name + ".jpg"),
                CreationCollisionOption.ReplaceExisting);

            using (var captureStream = new InMemoryRandomAccessStream())
            {
                await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), captureStream);

                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var decoder = await BitmapDecoder.CreateAsync(captureStream);

                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(fileStream, decoder);

                    var properties = new BitmapPropertySet {
                        { "System.Photo.Orientation", new BitmapTypedValue(PhotoOrientation.Normal, PropertyType.UInt16) }
                    };
                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.FlushAsync();
                }
            }
            PhotoRegistred();
        }
Esempio n. 30
0
        /// <summary>
        /// Takes a photo to a StorageFile and adds rotation metadata to it
        /// </summary>
        /// <returns></returns>
        private async Task TakePhotoAsync()
        {
            var stream = new InMemoryRandomAccessStream();

            try
            {
                Debug.WriteLine("Taking photo...");
                await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                Debug.WriteLine("Photo taken!");

                var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
                var file             = await ReencodeAndSavePhotoAsync(stream, photoOrientation);

                Emotion[] emotions = await GetEmotionsAsync(file);

                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => HighlightDetectedFacesWithEmotions(emotions));

                Debug.WriteLine($"{emotions}");

                //await ReencodeAndSavePhotoAsync(stream, photoOrientation);
            }
            catch (Exception ex)
            {
                // File I/O errors are reported as exceptions
                Debug.WriteLine("Exception when taking a photo: {0}", ex.ToString());
            }
        }