// Takes a photo from the webcam and displays it. private async void TakePhoto_Click(object sender, RoutedEventArgs e) { try { ShowStatusMessage("Taking photo..."); TakePhoto.IsEnabled = false; // Capture the photo to an in-memory stream. var photoStream = new InMemoryRandomAccessStream(); await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), photoStream); ShowStatusMessage("Create photo file successful"); // Display the photo. var bmpimg = new BitmapImage(); photoStream.Seek(0); await bmpimg.SetSourceAsync(photoStream); CapturedImage.Source = bmpimg; TakePhoto.IsEnabled = true; ShowStatusMessage("Photo taken"); } catch (Exception ex) { ShowExceptionMessage(ex); TakePhoto.IsEnabled = true; } }
/// <summary> /// Continuously look for a QR code /// NOTE: this method won't work if recording is enabled ('hey Cortana, start recording' thing). /// </summary> public static async Task<string> ReadAsync(CancellationToken token = default(CancellationToken)) { var mediaCapture = new MediaCapture(); await mediaCapture.InitializeAsync(); await mediaCapture.AddVideoEffectAsync(new MrcVideoEffectDefinition(), MediaStreamType.Photo); var reader = new BarcodeReader(); reader.Options.TryHarder = false; while (!token.IsCancellationRequested) { var imgFormat = ImageEncodingProperties.CreateJpeg(); using (var ras = new InMemoryRandomAccessStream()) { await mediaCapture.CapturePhotoToStreamAsync(imgFormat, ras); var decoder = await BitmapDecoder.CreateAsync(ras); using (var bmp = await decoder.GetSoftwareBitmapAsync()) { Result result = await Task.Run(() => { var source = new SoftwareBitmapLuminanceSource(bmp); return reader.Decode(source); }); if (!string.IsNullOrEmpty(result?.Text)) return result.Text; } } await Task.Delay(DelayBetweenScans); } return null; }
private async void Run() { await _HubConnection.Start(); var cam = new MediaCapture(); await cam.InitializeAsync(new MediaCaptureInitializationSettings() { MediaCategory = MediaCategory.Media, StreamingCaptureMode = StreamingCaptureMode.Video }); _Sensor.MotionDetected += async (int pinNum) => { var stream = new InMemoryRandomAccessStream(); Stream imageStream = null; try { await Task.Factory.StartNew(async () => { _Sensor.IsActive = false; await cam.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream); stream.Seek(0); imageStream = stream.AsStream(); imageStream.Seek(0, SeekOrigin.Begin); string imageUrl = await NotificationHelper.UploadImageAsync(imageStream); switch (await OxfordHelper.IdentifyAsync(imageUrl)) { case AuthenticationResult.IsOwner: // open the door MotorController.PWM(26); break; case AuthenticationResult.Unkown: // send notification to the owner NotificationHelper.NotifyOwnerAsync(imageUrl); break; case AuthenticationResult.None: default: break; } _Sensor.IsActive = true; }); } finally { if (stream != null) stream.Dispose(); if (imageStream != null) imageStream.Dispose(); } }; }
private async Task CapturePicture() { if (!isCaptureDone) { return; } isCaptureDone = false; var stream = new InMemoryRandomAccessStream(); await captureManager.CapturePhotoToStreamAsync(Windows.Media.MediaProperties.ImageEncodingProperties.CreateJpeg(), stream); var decoder = await BitmapDecoder.CreateAsync(stream); using (var memStream = new InMemoryRandomAccessStream()) { var encoder = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder); await encoder.FlushAsync(); using (var bitmapStream = new MemoryStream()) { await memStream.AsStream().CopyToAsync(bitmapStream); bitmapStream.Position = 0; var wImg = new WriteableBitmap(1280, 720); wImg.SetSource(bitmapStream.AsRandomAccessStream()); try { var result = visionService.CalculateTranslationAndRotation(wImg); System.Diagnostics.Debug.WriteLine($"Vrijednosti: x: {result.GetX()} y: {result.GetY()} z: {result.GetZ()}"); } catch { System.Diagnostics.Debug.WriteLine("Aleksandar"); } } } isCaptureDone = true; }
private async void v_Button_Capture_Click(object sender, RoutedEventArgs e) { isCapturing = !isCapturing; if (isCapturing) { if (isFirst) { captureManager = new MediaCapture(); await captureManager.InitializeAsync(); capturePreview.Source = captureManager; await captureManager.StartPreviewAsync(); isFirst = false; } v_Image.Source = null; } else { ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg(); var stream = new InMemoryRandomAccessStream(); await captureManager.CapturePhotoToStreamAsync(imageProperties, stream); _bitmap = new WriteableBitmap(300, 300); stream.Seek(0); await _bitmap.SetSourceAsync(stream); //await captureManager.StopPreviewAsync(); v_Image.Source = _bitmap; } }
internal async void captureclr_Click(object sender, RoutedEventArgs e) { // FOR Performance // m_mediaCaptureMgr.PrepareLowLagPhotoCaptureAsync //m_mediaCaptureMgr.CapturePhotoToStreamAsync captureclr.IsEnabled = false; /*Need to fix when it breaks cause of fast taping to take the image SystemExeption*/ try { await m_mediaCaptureMgr.CapturePhotoToStreamAsync(ie_prop, i_rs); } catch (Exception exp) { // TODO implement error functions } /*This fuckign line is so important , or else WB trows exeptions all round the house */ i_rs.Seek(0); /* Losing the aspect ratio because we set both decode pixel width and heigth */ // if u want bitmap image /* * BitmapImage bi = new BitmapImage(); * bi.DecodePixelHeight = (int) previewElement1.Height; * bi.DecodePixelWidth = (int) previewElement1.Width; * bi.SetSource(i_rs); */ /* Now to change the bitmapimage to writeablebitmap image*/ //wHERE the hell is a WriteableBitmap constructor from BitmapImage //BitmapImage bi = new BitmapImage(); //await bi.SetSourceAsync(i_rs); WriteableBitmap wb = new WriteableBitmap((int)previewElement1.ActualWidth, (int)previewElement1.ActualHeight); //TODO go direct to writeablebitmap if possible //wb.SetSource(i_rs); await wb.SetSourceAsync(i_rs); /* Now we need to pull out the pixels (using writeablebitmapEX class) * pulling out every 9th pixel but none on the edges so thats 9x9=81 pixels for a 90x90 square */ Color[,] rgb_array = new Color[9, 9]; // 180 is both left and top from both canvas and capture element Dictionary <String, int> mapa = new Dictionary <string, int>(); //For debuging purposes Dictionary <HelperColor, int> mapa_hc = new Dictionary <HelperColor, int>(); for (int i = 9; i < 90; i = i + 9) { for (int j = 9; j < 90; j = j + 9) { // TODO FIX wb.getpixel returning null ?! rgb_array[(i - 9) / 9, (j - 9) / 9] = wb.GetPixel(180 + i, 180 + j); } } for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { HelperColor hc = temp.clr_name(Color2Hex(rgb_array[i, j])); if (!mapa_hc.ContainsKey(hc)) { mapa_hc.Add(hc, 1); } else { mapa_hc[hc]++; } if (!mapa.ContainsKey(hc.name_shade)) { mapa.Add(hc.name_shade, 1); } else { mapa[hc.name_shade]++; } } } /*To search for the shadename that ocured the most */ /*Benchmark estimated to 125+ ms which is allot for iteraating thorugh map * * TODO create an array variable for this kind of stuff */ String placeholder = ""; int max_ = 0; foreach (KeyValuePair <String, int> kv in mapa) { if (max_ < kv.Value) { max_ = kv.Value; placeholder = kv.Key; } } textblock1.Text = placeholder; captureclr.IsEnabled = true; // Throws error , cannot convert windows smth uri to smth //m_mediael.Source = this.c2u.GetSoundUri(placeholder); //m_mediael.Play(); }
private async void ScanButton(object sender, object e) { string result = null; try { Waiter(true); var tcs = new TaskCompletionSource<object>(); StackPanel sp = new StackPanel() { Margin = new Thickness(20) }; #if WINDOWS_PHONE if (Device == null) { Windows.Foundation.Size initialResolution = new Windows.Foundation.Size(640, 480); wbm = new WriteableBitmap(640, 480); Device = await PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, initialResolution); Device.SetProperty(KnownCameraGeneralProperties.EncodeWithOrientation, Device.SensorLocation == CameraSensorLocation.Back ? Device.SensorRotationInDegrees : -Device.SensorRotationInDegrees); Device.SetProperty(KnownCameraGeneralProperties.AutoFocusRange, AutoFocusRange.Macro); Device.SetProperty(KnownCameraPhotoProperties.SceneMode, CameraSceneMode.Macro); Device.SetProperty(KnownCameraPhotoProperties.FocusIlluminationMode, FocusIlluminationMode.Off); } Rectangle previewRect = new Rectangle() { Height = 480, Width = 360 }; VideoBrush previewVideo = new VideoBrush(); previewVideo.RelativeTransform = new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = (Device.SensorLocation == CameraSensorLocation.Back ? Device.SensorRotationInDegrees : -Device.SensorRotationInDegrees) }; previewVideo.SetSource(Device); previewRect.Fill = previewVideo; Grid combiner = new Grid() { Height = previewRect.Height, Width = previewRect.Width }; combiner.Children.Add(previewRect); Grid.SetColumnSpan(previewRect, 3); Grid.SetRowSpan(previewRect, 3); int windowSize = 100; combiner.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(previewRect.Height / 2 - windowSize) }); combiner.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(windowSize) }); combiner.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(previewRect.Height / 2 - windowSize) }); combiner.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(previewRect.Width / 2 - windowSize) }); combiner.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(windowSize) }); combiner.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(previewRect.Width / 2 - windowSize) }); var maskBrush = new SolidColorBrush(Color.FromArgb(80, 0, 0, 0)); Canvas v1 = new Canvas() { Background = maskBrush }; Canvas v2 = new Canvas() { Background = maskBrush }; Canvas v3 = new Canvas() { Background = maskBrush }; Canvas v4 = new Canvas() { Background = maskBrush }; combiner.Children.Add(v1); Grid.SetRow(v1, 0); Grid.SetColumnSpan(v1, 3); combiner.Children.Add(v2); Grid.SetRow(v2, 2); Grid.SetColumnSpan(v2, 3); combiner.Children.Add(v3); Grid.SetRow(v3, 1); Grid.SetColumn(v3, 0); combiner.Children.Add(v4); Grid.SetRow(v4, 1); Grid.SetColumn(v4, 2); sp.Children.Add(combiner); BackgroundWorker bw = new BackgroundWorker(); DateTime last = DateTime.Now; bw.WorkerSupportsCancellation = true; bw.DoWork += async (s2, e2) => { var reader = new BarcodeReader(); while (!bw.CancellationPending) { if (DateTime.Now.Subtract(last).TotalSeconds > 2) { await Device.FocusAsync(); last = DateTime.Now; } try { Device.GetPreviewBufferArgb(wbm.Pixels); Debug.WriteLine(DateTime.Now.Millisecond); var codeVal = reader.Decode(wbm); if (codeVal != null) { result = codeVal.Text; e2.Cancel = true; tcs.TrySetResult(null); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } } }; bw.RunWorkerAsync(); #else var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); if (cameras.Count < 1) { return; } var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameras.Last().Id }; var imageSource = new MediaCapture(); await imageSource.InitializeAsync(settings); CaptureElement previewRect = new CaptureElement() { Width = 640, Height = 360 }; previewRect.Source = imageSource; sp.Children.Add(previewRect); await imageSource.StartPreviewAsync(); bool keepGoing = true; Action a = null; a = async () => { if (!keepGoing) return; var stream = new InMemoryRandomAccessStream(); await imageSource.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream); stream.Seek(0); var tmpBmp = new WriteableBitmap(1, 1); await tmpBmp.SetSourceAsync(stream); var writeableBmp = new WriteableBitmap(tmpBmp.PixelWidth, tmpBmp.PixelHeight); stream.Seek(0); await writeableBmp.SetSourceAsync(stream); Result _result = null; var barcodeReader = new BarcodeReader { // TryHarder = true, AutoRotate = true }; try { _result = barcodeReader.Decode(writeableBmp); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } stream.Dispose(); if (_result != null) { result = _result.Text; Debug.WriteLine(_result.Text); keepGoing = false; tcs.TrySetResult(null); } else { var x = RunOnUIThread(a); } }; await RunOnUIThread(a); #endif CustomMessageBox messageBox = new CustomMessageBox() { Title = "Scan Tag", Message = "", Content = sp, LeftButtonContent = "OK", RightButtonContent = "Cancel", IsFullScreen = false, }; messageBox.Unloaded += (s2, e2) => { tcs.TrySetResult(null); }; messageBox.Show(); await tcs.Task; messageBox.Dismiss(); #if WINDOWS_PHONE bw.CancelAsync(); #else keepGoing = false; await imageSource.StopPreviewAsync(); #endif Debug.WriteLine("result: '" + result + "'"); string loc = null; string building = null; string floor = null; string room = null; if (!string.IsNullOrEmpty(result)) { var s = result.Split(new char[] { '?' }, 2); if (s.Length == 2) { var paramList = s[1].Split('&') .Select(p => p.Split(new char[] { '=' }, 2)) .Where(p => p.Length == 2); loc = pick(paramList, "cp"); building = pick(paramList, "bld"); floor = pick(paramList, "flr"); room = pick(paramList, "rm"); } } GeoCoord? locVal = GeoCoord.Parse(loc); if (!string.IsNullOrEmpty(building) && !string.IsNullOrEmpty(floor)) { await ShowMap(RoomInfo.Parse(building + "/" + (room == null ? floor : room)), locVal); } } finally { Waiter(false); } }