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; } }
private async void Button_Click_1(object sender, RoutedEventArgs e) { using (var captureStream = new InMemoryRandomAccessStream()) { var pngProperties = ImageEncodingProperties.CreatePng(); //pngProperties.Width = (uint)pictureBox1.Width; //pngProperties.Height = (uint)pictureBox1.Height; pngProperties.Width = (uint)PreviewFrameImage.ActualWidth; pngProperties.Height = (uint)PreviewFrameImage.ActualHeight; AddLog("キャプチャ開始"); //await mediaCapture.CapturePhotoToStreamAsync(pngProperties, captureStream); Windows.Storage.StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync("sample.bmp", Windows.Storage.CreationCollisionOption.ReplaceExisting); //await mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreatePng(), sampleFile); captureStream.Seek(0); AddLog("AsStream"); //ビットマップにして表示 System.IO.Stream stream = System.IO.WindowsRuntimeStreamExtensions.AsStream(captureStream); var img = System.Drawing.Bitmap.FromStream(stream); //this.pictureBox1.Image = img; //img.Save(Environment.SpecialFolder.Desktop + @"\aaa.bmp"); AddLog("表示"); // 画面に表示 var a = System.Windows.Media.Imaging.BitmapFrame.Create(stream, System.Windows.Media.Imaging.BitmapCreateOptions.None, System.Windows.Media.Imaging.BitmapCacheOption.OnLoad); PreviewFrameImage.Source = a; } }
public async Task <InMemoryRandomAccessStream> CapturePhoto() { var stream = new InMemoryRandomAccessStream(); await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreatePng(), stream); return(stream); }
private static ImageEncodingProperties GetCompressedProperties() { var encodingQuality = ImageEncodingProperties.CreatePng(); //encodingQuality.Height = encodingQuality.Height / 2; //encodingQuality.Width = encodingQuality.Width / 2; //encodingQuality.Subtype = "GIF"; return(encodingQuality); }
/// <summary> /// Captures the photo to storage file asynchronously. /// </summary> /// <param name="folder">The folder.</param> /// <param name="fileName">Name of the file.</param> /// <param name="defaultExtension">The default extension.</param> /// <returns></returns> public async Task <StorageFile> CapturePhotoToStorageFileAsync(StorageFolder folder = null, string fileName = null, string defaultExtension = ".jpg") { if (_countdownControl != null && this.PhotoCaptureCountdownSeconds > 0) { #pragma warning disable 4014 _countdownControl.FadeInCustom(); await _countdownControl.StartCountdownAsync(this.PhotoCaptureCountdownSeconds); _countdownControl.FadeOutCustom(); #pragma warning restore 4014 } if (_flashAnimation != null) { _flashAnimation.Begin(); } if (folder == null) { folder = KnownFolders.PicturesLibrary; } if (fileName == null) { fileName = await folder.CreateTempFileNameAsync(defaultExtension); } var photoFile = await folder.CreateFileAsync( fileName, CreationCollisionOption.FailIfExists); ImageEncodingProperties imageEncodingProperties; switch (Path.GetExtension(fileName)) { case ".png": imageEncodingProperties = ImageEncodingProperties.CreatePng(); break; default: imageEncodingProperties = ImageEncodingProperties.CreateJpeg(); break; } try { await MediaCapture.CapturePhotoToStorageFileAsync(imageEncodingProperties, photoFile); } catch { OnCameraFailed(null, null); return(null); } return(photoFile); }
async void CaptureImage() { this.IsEnabled = false; try { var di = (DeviceInformation)listBox1.SelectedItem; if (di != null) { using (MediaCapture mediaCapture = new MediaCapture()) { mediaCapture.Failed += (s, e) => { MessageBox.Show("キャプチャできませんでした:" + e.Message, "Error", MessageBoxButton.OK); }; MediaCaptureInitializationSettings setting = new MediaCaptureInitializationSettings(); setting.VideoDeviceId = di.Id;//カメラ選択 setting.StreamingCaptureMode = StreamingCaptureMode.Video; await mediaCapture.InitializeAsync(setting); //調整しないと暗い場合があるので var vcon = mediaCapture.VideoDeviceController; vcon.Brightness.TrySetAuto(true); vcon.Contrast.TrySetAuto(true); var pngProperties = ImageEncodingProperties.CreatePng(); pngProperties.Width = (uint)image1.ActualWidth; pngProperties.Height = (uint)image1.ActualHeight; using (var randomAccessStream = new InMemoryRandomAccessStream()) { await mediaCapture.CapturePhotoToStreamAsync(pngProperties, randomAccessStream); randomAccessStream.Seek(0); //ビットマップにして表示 var bmp = new BitmapImage(); using (System.IO.Stream stream = System.IO.WindowsRuntimeStreamExtensions.AsStream(randomAccessStream)) { bmp.BeginInit(); bmp.CacheOption = BitmapCacheOption.OnLoad; bmp.StreamSource = stream; bmp.EndInit(); } this.image1.Source = bmp; } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } this.IsEnabled = true; }
async private void PreviewElement_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e) { var bi = new BusyIndicator(); try { bi.Open("Please wait"); 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); await ByteArrayToBitmapImage(_bytes); var bitmap = new BitmapImage(); stream.Seek(0); await bitmap.SetSourceAsync(stream); var model = this.Tag as MaintenanceRepair; if (model == null) { model = new MaintenanceRepair(); } if (model.IsMajorPivot) { model.MajorComponentImgList.Add(new ImageCapture { ImageBitmap = bitmap }); } else { model.SubComponentImgList.Add(new ImageCapture { ImageBitmap = bitmap }); } PreviewElement.Visibility = Windows.UI.Xaml.Visibility.Collapsed; Img.Visibility = Windows.UI.Xaml.Visibility.Visible; this.IsSecondaryButtonEnabled = true; } bi.Close(); } catch (Exception) { bi.Close(); } }
private async Task TakePicture(string conversID) { if (!WebcamService.IsInitialized) { await WebcamService.InitializeCameraAsync(); await WebcamService.StartCameraPreviewAsync(); } using (var stream = new InMemoryRandomAccessStream()) { ImageEncodingProperties imgFormat = ImageEncodingProperties.CreatePng(); // create storage file in local app storage StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync( "AdaPhotoTMP.png", CreationCollisionOption.ReplaceExisting); // take photo await WebcamService.MediaCapture.CapturePhotoToStorageFileAsync(imgFormat, file); FileStream fileStream = new FileStream(file.Path, FileMode.Open); Stream streamFinal = fileStream.AsRandomAccessStream().AsStream(); StringConstructorSDK client = new StringConstructorSDK() { WebAppUrl = $"{ AppConfig.WebUri}" }; try { var activity = new Activity { From = new ChannelAccount("Jean"), Text = "Picture from UWP", Type = ActivityTypes.Message, //Envoyer le stream ChannelData = await client.PictureAnalyseAsync(AppConfig.Vision, streamFinal), //ATTENTION CONVERSID DIFFERENT!!!!! Name = conversID, //Summary = serviceUrl }; await _client.Conversations.PostActivityAsync(_conversation.ConversationId, activity); } catch (HttpRequestException) { //Impossible to take picture } } }
/// <summary> /// Gets the Image encondings properties. /// </summary> /// <param name="format">The selected format.</param> /// <returns>The properties of the selected format.</returns> private ImageEncodingProperties GetImageEncodingProperties(PhotoCaptureFormat format) { switch (format) { case PhotoCaptureFormat.JPG: return(ImageEncodingProperties.CreateJpeg()); case PhotoCaptureFormat.BMP: return(ImageEncodingProperties.CreateBmp()); case PhotoCaptureFormat.PNG: default: return(ImageEncodingProperties.CreatePng()); } }
public async Task TakePhotoAsync() { var stream = new InMemoryRandomAccessStream(); await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream); try { var folder = KnownFolders.CameraRoll; var file = await folder.CreateFileAsync("pict.jpg", CreationCollisionOption.GenerateUniqueName); // var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation()); // await ReencodeAndSavePhotoAsync(stream, file, photoOrientation); await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreatePng(), file); } catch (Exception ex) { return; } }
private async void TakePicture(object parameter) { Idle = false; await _mediaCapture.StopPreviewAsync(); var fileName = string.Format("Photo-{0}.png", Guid.NewGuid()); var file = await _localMediaFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName); var imageEncodingProperties = ImageEncodingProperties.CreatePng(); await _mediaCapture.CapturePhotoToStorageFileAsync(imageEncodingProperties, file); var mediaItem = new MediaItem(FolderType.Local, ReservationId, file.Name); MediaItems.Add(mediaItem); SelectedMediaItem = mediaItem; PreviewEnabled = false; Idle = true; }
private async void MakePhoto() { // This is where we want to save to. var storageFolder = KnownFolders.SavedPictures; //var file = await storageFolder.CreateFileAsync("Test" + ".png", CreationCollisionOption.ReplaceExisting); IReadOnlyList <StorageFile> files = await storageFolder.GetFilesAsync(); var file = await storageFolder.CreateFileAsync("Test" + ".png", CreationCollisionOption.ReplaceExisting); await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreatePng(), file); await persons.addNewFace(); Greetings.Text = "Hello " + persons.getName(algorithm.RecognizeNewFace(persons.newFace)) + "!"; await file.DeleteAsync(StorageDeleteOption.Default); listener = 0; }
public CameraCapturePageViewModel(INavigationService navigationService) { _navigationService = navigationService; TakePictureCommand = new DelegateCommand(async() => { var imageEncodingProps = ImageEncodingProperties.CreatePng(); using (var stream = new InMemoryRandomAccessStream()) { await this.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 (ImageSource == null) { ImageSource = new BitmapImage(); } await this.ImageSource.SetSourceAsync(stream); this.ImageVisibility = Visibility.Visible; } }); RetakePictureCommand = new DelegateCommand(() => { ImageVisibility = Visibility.Collapsed; }); AcceptCommand = new DelegateCommand <byte[]>((bytes) => { _serviceDetail.OdoReadingImageCapture.ImageBitmap = this.ImageSource; if (bytes.Length > 0) { _serviceDetail.ODOReadingSnapshot = Convert.ToBase64String(bytes); } _navigationService.Navigate("ServiceScheduling", _serviceDetail); //_navigationService.ClearHistory(); }); }
async private void PreviewElement_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e) { var bi = new BusyIndicator(); try { bi.Open("Please wait"); 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); var bitmap = new BitmapImage(); stream.Seek(0); await bitmap.SetSourceAsync(stream); var model = this.Tag as ServiceSchedulingDetail; if (model.OdoReadingImageCapture == null) { model.OdoReadingImageCapture = new ImageCapture(); } model.OdoReadingImageCapture.ImageBitmap = bitmap; model.ODOReadingSnapshot = Convert.ToBase64String(_bytes); PreviewElement.Visibility = Windows.UI.Xaml.Visibility.Collapsed; Img.Visibility = Windows.UI.Xaml.Visibility.Visible; this.IsSecondaryButtonEnabled = true; Img.Source = bitmap; } bi.Close(); } catch (Exception) { bi.Close(); throw; } }
private async void startCapture_Tapped(object sender, TappedRoutedEventArgs e) { startCapture.Visibility = Visibility.Collapsed; NoFiles.Visibility = Visibility.Collapsed; render.Visibility = Visibility.Collapsed; RenderComplete.Visibility = Visibility.Collapsed; IncrementProject.IsEnabled = false; IncrementProject.Opacity = .65; //Interval.IsEnabled = false; Interval.Visibility = Visibility.Collapsed; tbInterval.Visibility = Visibility.Visible; tbInterval.Text = (string)((ComboBoxItem)Interval.SelectedItem).Content; HourMinuteSecond.Visibility = Visibility.Collapsed; tbHourMinuteSecond.Text = (string)((ComboBoxItem)HourMinuteSecond.SelectedItem).Content; tbHourMinuteSecond.Visibility = Visibility.Visible; CameraSource.Visibility = Visibility.Collapsed; tbCameraSource.Visibility = Visibility.Visible; tbCameraSource.Text = (string)((ComboBoxItem)CameraSource.SelectedItem).Content; CameraSettings2.Visibility = Visibility.Collapsed; tbCameraSetting.Visibility = Visibility.Visible; tbCameraSetting.Text = (string)((ComboBoxItem)CameraSettings2.SelectedItem).Content; DarnSeconds j = (DarnSeconds)((ComboBoxItem)Interval.SelectedItem).Tag; String k = (string)((ComboBoxItem)HourMinuteSecond.SelectedItem).Content; if (k == "Hours") { HowManySecondsBetween = j.HowManyDarnSeconds * 360; } else if (k == "Minutes") { HowManySecondsBetween = j.HowManyDarnSeconds * 60; } else { HowManySecondsBetween = j.HowManyDarnSeconds; } int i = 1; isRecording = true; stopCapture.Visibility = Visibility.Visible; while (isRecording) { StorageFile z = await PictureLapsesFolder.CreateFileAsync("Lapses.png", CreationCollisionOption.GenerateUniqueName); ImageEncodingProperties q = ImageEncodingProperties.CreatePng(); await _mediaCapture.CapturePhotoToStorageFileAsync(q, z); await Task.Delay(HowManySecondsBetween * 1000); } render.Visibility = Visibility.Visible; IncrementProject.IsEnabled = true; IncrementProject.Opacity = 1.0; Interval.Visibility = Visibility.Visible; tbInterval.Visibility = Visibility.Collapsed; HourMinuteSecond.Visibility = Visibility.Visible; tbHourMinuteSecond.Visibility = Visibility.Collapsed; CameraSource.Visibility = Visibility.Visible; tbCameraSource.Visibility = Visibility.Collapsed; CameraSettings2.Visibility = Visibility.Visible; tbCameraSetting.Visibility = Visibility.Collapsed; stopCapture.Visibility = Visibility.Collapsed; startCapture.Visibility = Visibility.Visible; PleaseWait.Visibility = Visibility.Collapsed; }
/// <summary> /// Captures the next frame. /// </summary> public async Task <FrameData> Capture(Double coarsening = 10.0, Boolean fused = false) { if (_mediaCapture != null) { if (coarsening < 1.0) { throw new YAMPRuntimeException("Video: coarsening must be larger than or equal to 1.0."); } var imageProperties = ImageEncodingProperties.CreatePng(); var stream = new InMemoryRandomAccessStream(); await _mediaCapture.CapturePhotoToStreamAsync(imageProperties, stream); var decoder = await BitmapDecoder.CreateAsync(stream); var pixelData = await decoder.GetPixelDataAsync(); var rgbValues = pixelData.DetachPixelData(); var width = (Int32)decoder.PixelWidth; var height = (Int32)decoder.PixelHeight; var inverseCoarsening = 1.0 / coarsening; var finalWidth = (Int32)(width * inverseCoarsening); var finalHeight = (Int32)(height * inverseCoarsening); var count = new Byte[finalHeight, finalWidth]; var rvalues = new Double[finalHeight, finalWidth]; var gvalues = new Double[finalHeight, finalWidth]; var bvalues = new Double[finalHeight, finalWidth]; for (var i = 0; i < width; i++) { var idx = (Int32)(i * inverseCoarsening); if (idx >= finalWidth) { idx = finalWidth - 1; } for (int j = 0; j < height; j++) { var jdx = (Int32)(j * inverseCoarsening); if (jdx >= finalHeight) { jdx = finalHeight - 1; } rvalues[jdx, idx] += rgbValues[(j * width + i) * 4 + 2]; gvalues[jdx, idx] += rgbValues[(j * width + i) * 4 + 1]; bvalues[jdx, idx] += rgbValues[(j * width + i) * 4 + 0]; count[jdx, idx]++; } } for (var i = 0; i < finalHeight; i++) { for (var j = 0; j < finalWidth; j++) { var cinv = 1.0 / count[i, j]; rvalues[i, j] *= cinv; gvalues[i, j] *= cinv; bvalues[i, j] *= cinv; } } if (fused) { for (var i = 0; i < finalHeight; i++) { for (var j = 0; j < finalWidth; j++) { rvalues[i, j] = (Int32)rvalues[i, j]; gvalues[i, j] = (Int32)gvalues[i, j]; bvalues[i, j] = (Int32)bvalues[i, j]; rvalues[i, j] *= rfactor; gvalues[i, j] *= gfactor; bvalues[i, j] *= bfactor; rvalues[i, j] += gvalues[i, j] + bvalues[i, j]; } } return(new FrameData { Blue = rvalues, Green = rvalues, Red = rvalues, IsFused = true }); } return(new FrameData { Blue = bvalues, Green = gvalues, Red = rvalues, IsFused = false }); } return(new FrameData()); }
private async void ProcessVideoFrame(ThreadPoolTimer timer) { if (!frameProcessingSimaphore.Wait(0)) { // We are already doing something return; } try { IEnumerable <DetectedFace> faces = null; const BitmapPixelFormat inputPixelFormat = BitmapPixelFormat.Nv12; Face[] globalFaces = null; using (var previewFrame = new VideoFrame(inputPixelFormat, (int)videoProperties.Width, (int)videoProperties.Height)) { await mediaCapture.GetPreviewFrameAsync(previewFrame); if (FaceTracker.IsBitmapPixelFormatSupported(previewFrame.SoftwareBitmap.BitmapPixelFormat)) { faces = await faceTracker.ProcessNextFrameAsync(previewFrame); if (!facesExistInFrame) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Enable the Train feature and disable the other buttons PageYes.Visibility = Visibility.Collapsed; PageNo.Visibility = Visibility.Collapsed; TrainMe.Visibility = Visibility.Visible; }); } if (faces.Any()) { if (!facesExistInFrame) { facesExistInFrame = true; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Enable the Yes/No buttons. Disable the Train Button PageYes.Visibility = Visibility.Visible; PageNo.Visibility = Visibility.Visible; TrainMe.Visibility = Visibility.Collapsed; }); await ShowMessage("Will you help me? If so, make sure I can see you face and click \"Yse\"", 1); } if (faces.Count() > 1) { await ShowMessage("Can only identify when multiple faces are visible."); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Disable the Yes/No buttons. PageYes.Visibility = Visibility.Collapsed; PageNo.Visibility = Visibility.Collapsed; }); } else { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Enable the Yes/No Buttons PageYes.Visibility = Visibility.Visible; PageNo.Visibility = Visibility.Visible; TrainMe.Visibility = Visibility.Collapsed; }); var captureStream = new MemoryStream(); await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreatePng(), captureStream.AsRandomAccessStream()); captureStream.AsRandomAccessStream().Seek(0); // ask the face api what it sees // See: https://docs.microsoft.com/en-us/azure/cognitive-services/face/face-api-how-to-topics/howtodetectfacesinimage globalFaces = await faceServiceClient.DetectAsync(captureStream, true, true, requiredFaceAttributes); if (random.Next(3) == 0 && imageNeededCount > 0) { imageNeededCount--; SavePicture(mediaCapture); if (imageNeededCount == 0) { await ShowMessage("Ok, you have been recognized...", 1000); AddToFaceIdList(); } } ; } var previewFrameSize = new Size(previewFrame.SoftwareBitmap.PixelWidth, previewFrame.SoftwareBitmap.PixelHeight); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ShowFaceTracking(faces, previewFrameSize); ShowIdentificationiStatus(globalFaces); }); var firstFace = faces.FirstOrDefault(); } else { facesExistInFrame = false; // reset the stuff because there are no faces to analyze. await ShowMessage(String.Empty); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ShowFaceTracking(faces, new Size()); }); } var test = faces.Count(); } } } catch (Exception ex) { var test = ex; // face detection failed for some reason. } finally { frameProcessingSimaphore.Release(); } }
private async void TakePicture(MediaCapture capture, PreviewImage preview, string outputFile, int delay) { if (!File.Exists(outputFile)) { File.Create(outputFile).Close(); } StorageFile file = await StorageFile.GetFileFromPathAsync(outputFile); ImageEncodingProperties imgFormat = ImageEncodingProperties.CreatePng(); new Thread(delegate() { Thread.CurrentThread.IsBackground = true; Stopwatch stopwatch = Stopwatch.StartNew(); long millisecondsToWait = delay * 1000; int i = delay; while (true) { long now = stopwatch.ElapsedMilliseconds; if (now >= millisecondsToWait) { // take photo in async IAsyncAction action = capture.CapturePhotoToStorageFileAsync(imgFormat, file); while (true) { if (action.Status == AsyncStatus.Completed || action.Status == AsyncStatus.Error) { break; } Thread.Sleep(1); } Dispatcher.Invoke(new Action(() => { this.CountDown.Visibility = Visibility.Hidden; Task _ = preview.StopAsync(); capture.Dispose(); if (action.Status == AsyncStatus.Completed) { this.PictureFile = file.Path; } else { DeletePicture(); } LoadPicture(); ResetMessage(); ValidateField(this.Picture); })); break; } Dispatcher.Invoke(new Action(() => { this.CountDown.Visibility = Visibility.Visible; this.CountDown.Text = i.ToString(); })); i--; Thread.Sleep(1000); } }).Start(); }