Exemplo n.º 1
0
        private void SetFocus()
        {
            if (this.camera != null)
            {
                var focusControl = this.camera.VideoDeviceController.FocusControl;

                if (focusControl.Supported)
                {
                    var focusRange = focusControl.SupportedFocusRanges.Contains(AutoFocusRange.FullRange) ? AutoFocusRange.FullRange : focusControl.SupportedFocusRanges.FirstOrDefault();
                    var focusMode  = focusControl.SupportedFocusModes.Contains(FocusMode.Continuous) ? FocusMode.Continuous : focusControl.SupportedFocusModes.FirstOrDefault();

                    //set AF
                    var focusSettings = new FocusSettings()
                    {
                        Mode                  = focusMode,
                        AutoFocusRange        = focusRange,
                        DisableDriverFallback = true,
                        WaitForFocus          = false
                    };

                    focusControl.Configure(focusSettings);
                }

                var flash = this.camera.VideoDeviceController.FlashControl;

                if (flash.Supported)
                {
                    flash.Enabled = false;
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Sets camera to focus on the passed in region of interest
        /// </summary>
        /// <param name="region">The region to focus on, or null to focus on the default region</param>
        /// <returns></returns>
        private async Task <MediaCaptureFocusState> FocusCamera(RegionOfInterest region)
        {
            var roiControl   = _mediaCapture.VideoDeviceController.RegionsOfInterestControl;
            var focusControl = _mediaCapture.VideoDeviceController.FocusControl;

            if (region != null)
            {
                // If the call provided a region, then set it
                await roiControl.SetRegionsAsync(new[] { region }, true);

                var focusRange = focusControl.SupportedFocusRanges.Contains(AutoFocusRange.FullRange) ? AutoFocusRange.FullRange : focusControl.SupportedFocusRanges.FirstOrDefault();
                var focusMode  = focusControl.SupportedFocusModes.Contains(FocusMode.Single) ? FocusMode.Single : focusControl.SupportedFocusModes.FirstOrDefault();

                var settings = new FocusSettings {
                    Mode = focusMode, AutoFocusRange = focusRange
                };

                focusControl.Configure(settings);
            }
            else
            {
                // If no region provided, clear any regions and reset focus
                await roiControl.ClearRegionsAsync();
            }

            await focusControl.FocusAsync();

            return(focusControl.FocusState);
        }
        // </SnippetTapFocusPreviewControl>


        /// <summary>
        /// Focus the camera on the given rectangle of the preview, defined by the position and size parameters, in UI coordinates within the CaptureElement
        /// </summary>
        /// <param name="position">The position of the tap, to become the center of the focus rectangle</param>
        /// <param name="size">the size of the rectangle around the tap</param>
        /// <returns></returns>
        ///
        // <SnippetTapToFocus>
        public async Task TapToFocus(Point position, Size size)
        {
            _isFocused = true;

            var previewRect  = GetPreviewStreamRectInControl();
            var focusPreview = ConvertUiTapToPreviewRect(position, size, previewRect);

            // Note that this Region Of Interest could be configured to also calculate exposure
            // and white balance within the region
            var regionOfInterest = new RegionOfInterest
            {
                AutoFocusEnabled = true,
                BoundsNormalized = true,
                Bounds           = focusPreview,
                Type             = RegionOfInterestType.Unknown,
                Weight           = 100,
            };


            var focusControl = _mediaCapture.VideoDeviceController.FocusControl;
            var focusRange   = focusControl.SupportedFocusRanges.Contains(AutoFocusRange.FullRange) ? AutoFocusRange.FullRange : focusControl.SupportedFocusRanges.FirstOrDefault();
            var focusMode    = focusControl.SupportedFocusModes.Contains(FocusMode.Single) ? FocusMode.Single : focusControl.SupportedFocusModes.FirstOrDefault();
            var settings     = new FocusSettings {
                Mode = focusMode, AutoFocusRange = focusRange
            };

            focusControl.Configure(settings);

            var roiControl = _mediaCapture.VideoDeviceController.RegionsOfInterestControl;
            await roiControl.SetRegionsAsync(new[] { regionOfInterest }, true);

            await focusControl.FocusAsync();
        }
        private async Task SetupAutoFocus()
        {
            if (IsFocusSupported)
            {
                var focusControl = mediaCapture.VideoDeviceController.FocusControl;

                var focusSettings = new FocusSettings
                {
                    AutoFocusRange = focusControl.SupportedFocusRanges.Contains(AutoFocusRange.FullRange)
                        ? AutoFocusRange.FullRange
                        : focusControl.SupportedFocusRanges.FirstOrDefault()
                };

                var supportedFocusModes = focusControl.SupportedFocusModes;
                if (supportedFocusModes.Contains(FocusMode.Continuous))
                {
                    focusSettings.Mode = FocusMode.Continuous;
                }
                else if (supportedFocusModes.Contains(FocusMode.Auto))
                {
                    focusSettings.Mode = FocusMode.Auto;
                }

                if (focusSettings.Mode == FocusMode.Continuous || focusSettings.Mode == FocusMode.Auto)
                {
                    focusSettings.WaitForFocus = false;
                    focusControl.Configure(focusSettings);
                    await focusControl.FocusAsync();
                }
            }
        }
        public async Task AutoFocusAsync(int x, int y, bool useCoordinates)
        {
            if (IsFocusSupported)
            {
                var focusControl = mediaCapture.VideoDeviceController.FocusControl;
                var roiControl   = mediaCapture.VideoDeviceController.RegionsOfInterestControl;
                try
                {
                    if (roiControl.AutoFocusSupported && roiControl.MaxRegions > 0)
                    {
                        if (useCoordinates)
                        {
                            var props = mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);

                            var previewEncodingProperties = GetPreviewResolution(props);
                            var previewRect      = GetPreviewStreamRectInControl(previewEncodingProperties, captureElement);
                            var focusPreview     = ConvertUiTapToPreviewRect(new Point(x, y), new Size(20, 20), previewRect);
                            var regionOfInterest = new RegionOfInterest
                            {
                                AutoFocusEnabled = true,
                                BoundsNormalized = true,
                                Bounds           = focusPreview,
                                Type             = RegionOfInterestType.Unknown,
                                Weight           = 100
                            };
                            await roiControl.SetRegionsAsync(new[] { regionOfInterest }, true);

                            var focusRange = focusControl.SupportedFocusRanges.Contains(AutoFocusRange.FullRange)
                                ? AutoFocusRange.FullRange
                                : focusControl.SupportedFocusRanges.FirstOrDefault();

                            var focusMode = focusControl.SupportedFocusModes.Contains(FocusMode.Single)
                                ? FocusMode.Single
                                : focusControl.SupportedFocusModes.FirstOrDefault();

                            var settings = new FocusSettings
                            {
                                Mode           = focusMode,
                                AutoFocusRange = focusRange,
                            };

                            focusControl.Configure(settings);
                        }
                        else
                        {
                            // If no region provided, clear any regions and reset focus
                            await roiControl.ClearRegionsAsync();
                        }
                    }

                    await focusControl.FocusAsync();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("AutoFocusAsync Error: {0}", ex);
                }
            }
        }
        public async System.Threading.Tasks.Task StartCapturePreviewAsync()
        {
            try
            {
                Windows.Devices.Enumeration.Panel devicePanel = Windows.Devices.Enumeration.Panel.Back;
                var obj = Global.Current.LocalSettings.LoadData(conCameraPanel);
                if (obj != null && obj.ToString() == conCameraFront)
                {
                    devicePanel = Windows.Devices.Enumeration.Panel.Front;
                    this.captureElement.FlowDirection = Windows.UI.Xaml.FlowDirection.RightToLeft;
                }
                else
                {
                    this.captureElement.FlowDirection = Windows.UI.Xaml.FlowDirection.LeftToRight;
                }
                if ((App.Current as App).mediaCapture == null)
                {
                    await(App.Current as App).InitializeCapture(devicePanel);
                }
                Global.Current.LocalSettings.SaveData(conCameraPanel, devicePanel.ToString());
                this.mediaCapture = (App.Current as App).mediaCapture;
                this.zoomControl  = this.mediaCapture.VideoDeviceController.ZoomControl;
                if (this.mediaCapture.VideoDeviceController.FocusControl.Supported)
                {
                    var focusSettings = new FocusSettings();
                    focusSettings.AutoFocusRange        = AutoFocusRange.FullRange;
                    focusSettings.Mode                  = FocusMode.Auto;
                    focusSettings.WaitForFocus          = true;
                    focusSettings.DisableDriverFallback = false;
                    this.mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);
                }
                if (this.zoomControl != null && this.zoomControl.Supported)
                {
                    this.zoomSlider.Visibility    = Windows.UI.Xaml.Visibility.Visible;
                    this.zoomSlider.IsEnabled     = true;
                    this.zoomSlider.Maximum       = this.zoomControl.Max;
                    this.zoomSlider.Minimum       = this.zoomControl.Min;
                    this.zoomSlider.StepFrequency = this.zoomControl.Step;
                    this.zoomSlider.Value         = this.zoomControl.Value;
                }
                else
                {
                    this.zoomSlider.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                }
                this.AppbarSwitchCamera.IsEnabled = (App.Current as App).isSupportFront;
                await this.mediaCapture.VideoDeviceController.ExposureControl.SetAutoAsync(true);

                this.captureElement.Source = this.mediaCapture;
                await this.mediaCapture.StartPreviewAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Exemplo n.º 7
0
        private async void InitVideoCapture()
        {
            ///摄像头的检测
            var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);

            // var cameraDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);

            if (cameraDevice == null)
            {
                Debug.WriteLine("No camera device found!");
                return;
            }
            var settings = new MediaCaptureInitializationSettings
            {
                StreamingCaptureMode = StreamingCaptureMode.Video,
                //必须,否则截图的时候会很卡很慢
                PhotoCaptureSource = PhotoCaptureSource.VideoPreview,
                MediaCategory      = MediaCategory.Other,
                AudioProcessing    = AudioProcessing.Default,
                VideoDeviceId      = cameraDevice.Id
            };

            _mediaCapture = new MediaCapture();


            //初始化
            await _mediaCapture.InitializeAsync(settings);

            VideoCapture.Source = _mediaCapture;
            await _mediaCapture.StartPreviewAsync();

            var props = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);

            props.Properties.Add(RotationKey, 90);

            await _mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, props, null);

            var focusControl = _mediaCapture.VideoDeviceController.FocusControl;

            if (focusControl.Supported)
            {
                await focusControl.UnlockAsync();

                var setting = new FocusSettings {
                    Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.FullRange
                };
                focusControl.Configure(setting);
                await focusControl.FocusAsync();
            }

            _isPreviewing = true;
            _isInitVideo  = true;
            InitVideoTimer();
        }
Exemplo n.º 8
0
        async Task StartPreview()
        {
            if (String.Equals(Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily, "Windows.Mobile"))
            {
                mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                mediaCapture.SetPreviewMirroring(true);
            }

            var focusControl = mediaCapture.VideoDeviceController.FocusControl;

            if (!focusControl.FocusChangedSupported)
            {
                if (focusControl.Supported)
                {
                    _cleanedUp   = false;
                    _processScan = true;

                    VideoCaptureElement.Source  = mediaCapture;
                    VideoCaptureElement.Stretch = Stretch.UniformToFill;
                    await mediaCapture.StartPreviewAsync();

                    await focusControl.UnlockAsync();

                    focusControl.Configure(new FocusSettings {
                        Mode = FocusMode.Auto
                    });
                    timerFocus.Tick    += timerFocus_Tick;
                    timerFocus.Interval = new TimeSpan(0, 0, 3);
                    timerFocus.Start();
                }
                else
                {
                    OnErrorAsync(new Exception("AutoFocus control is not supported on this device"));
                }
            }
            else
            {
                _cleanedUp   = false;
                _processScan = true;

                mediaCapture.FocusChanged  += mediaCaptureManager_FocusChanged;
                VideoCaptureElement.Source  = mediaCapture;
                VideoCaptureElement.Stretch = Stretch.UniformToFill;
                await mediaCapture.StartPreviewAsync();

                await focusControl.UnlockAsync();

                var settings = new FocusSettings {
                    Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.FullRange
                };
                focusControl.Configure(settings);
                await focusControl.FocusAsync();
            }
        }
Exemplo n.º 9
0
        private async void Init()
        {
            //Get back camera
            var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            var backCameraId =
                devices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Panel.Back).Id;

            //Start preview
            _cameraPreviewImageSource = new CameraPreviewImageSource();
            await _cameraPreviewImageSource.InitializeAsync(backCameraId);

            var properties = await _cameraPreviewImageSource.StartPreviewAsync();

            //Setup preview
            _width  = 640.0;
            _height = _width / properties.Width * properties.Height;
            var bitmap = new WriteableBitmap((int)_width, (int)_height);

            _writeableBitmap = bitmap;

            PreviewImage.Source = _writeableBitmap;

            _writeableBitmapRenderer = new WriteableBitmapRenderer(_cameraPreviewImageSource, _writeableBitmap);

            _cameraPreviewImageSource.PreviewFrameAvailable += OnPreviewFrameAvailable;

            _videoDevice = (VideoDeviceController)_cameraPreviewImageSource.VideoDeviceController;

            //Set timer for auto focus
            if (_videoDevice.FocusControl.Supported)
            {
                var focusSettings = new FocusSettings
                {
                    AutoFocusRange        = AutoFocusRange.Macro,
                    Mode                  = FocusMode.Auto,
                    WaitForFocus          = false,
                    DisableDriverFallback = false
                };

                _videoDevice.FocusControl.Configure(focusSettings);

                _timer = new DispatcherTimer
                {
                    Interval = new TimeSpan(0, 0, 0, 2, 0)
                };
                _timer.Tick += TimerOnTick;
                _timer.Start();
            }

            await _videoDevice.ExposureControl.SetAutoAsync(true);

            _initialized = true;
        }
Exemplo n.º 10
0
        /// <summary>
        /// Reconfigures the focus control on the current video device.
        /// </summary>
        /// <param name="continuous">Whether the continuous auto focus should be set.</param>
        private void ConfigureAutoFocus(bool continuous)
        {
            Tracing.Trace("CameraController: Configuring {0} auto-focus.", continuous ? "continuous" : "normal");

            FocusSettings focusSettings = continuous
                                          ? new FocusSettings {
                Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.Normal
            }
                                          : new FocusSettings {
                Mode = FocusMode.Single, AutoFocusRange = AutoFocusRange.FullRange
            };

            this.MediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);
        }
Exemplo n.º 11
0
        private async Task SetupFocus()
        {
            if (_mediaCapture != null && _isPreviewing)
            {
                var focusControl = _mediaCapture.VideoDeviceController.FocusControl;
                await focusControl.UnlockAsync();

                var settings = new FocusSettings {
                    Mode = FocusMode.Auto
                };
                focusControl.Configure(settings);

                await Task.CompletedTask;
            }
        }
Exemplo n.º 12
0
        private async void Initialize()
        {
            var cameraId = await ViewModel.GetCameraIdAsync(Windows.Devices.Enumeration.Panel.Back);

            _cameraPreviewImageSource = new CameraPreviewImageSource();
            await _cameraPreviewImageSource.InitializeAsync(cameraId.Id);

            var properties = await _cameraPreviewImageSource.StartPreviewAsync();

            _width  = Window.Current.Bounds.Width;
            _height = Window.Current.Bounds.Height;
            var bitmap = new WriteableBitmap((int)_width, (int)_height);

            _writeableBitmap = bitmap;

            PreviewImage.Source = _writeableBitmap;

            _writeableBitmapRenderer = new WriteableBitmapRenderer(_cameraPreviewImageSource, _writeableBitmap);

            _cameraPreviewImageSource.PreviewFrameAvailable += OnPreviewFrameAvailable;

            _videoDevice = (VideoDeviceController)_cameraPreviewImageSource.VideoDeviceController;

            if (_videoDevice.FocusControl.Supported)
            {
                var focusSettings = new FocusSettings
                {
                    AutoFocusRange        = AutoFocusRange.Macro,
                    Mode                  = FocusMode.Auto,
                    WaitForFocus          = false,
                    DisableDriverFallback = false
                };

                _videoDevice.FocusControl.Configure(focusSettings);

                _timer = new DispatcherTimer
                {
                    Interval = TimeSpan.FromSeconds(2)
                };
                _timer.Tick += OnTick;
                _timer.Start();
            }

            await _videoDevice.ExposureControl.SetAutoAsync(true);

            _initialized = true;
        }
Exemplo n.º 13
0
        private async void CafFocusRadioButton_Checked(object sender, RoutedEventArgs e)
        {
            // Reset tap-to-focus status
            _isFocused = false;
            FocusRectangle.Visibility = Visibility.Collapsed;

            var focusControl = _mediaCapture.VideoDeviceController.FocusControl;

            await focusControl.UnlockAsync();

            var settings = new FocusSettings {
                Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.FullRange
            };

            focusControl.Configure(settings);
            await focusControl.FocusAsync();
        }
        // <SnippetCafFocusRadioButton>
        private async void CafFocusRadioButton_Checked(object sender, RoutedEventArgs e)
        {
            if (!_isPreviewing)
            {
                // Autofocus only supported while preview stream is running.
                return;
            }

            var focusControl = _mediaCapture.VideoDeviceController.FocusControl;
            await focusControl.UnlockAsync();

            var settings = new FocusSettings {
                Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.FullRange
            };

            focusControl.Configure(settings);
            await focusControl.FocusAsync();
        }
        async private void PreviewElement_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _mediaCapture         = new MediaCapture();
                _mediaCapture.Failed += mediaCapture_Failed;

                var _deviceInformation = await GetCameraDeviceInfoAsync(Windows.Devices.Enumeration.Panel.Back);

                var settings = new MediaCaptureInitializationSettings();
                //settings.StreamingCaptureMode = StreamingCaptureMode.Video;
                settings.PhotoCaptureSource = PhotoCaptureSource.Photo;
                settings.AudioDeviceId      = "";
                if (_deviceInformation != null)
                {
                    settings.VideoDeviceId = _deviceInformation.Id;
                }

                await _mediaCapture.InitializeAsync(settings);

                var focusSettings = new FocusSettings();
                focusSettings.AutoFocusRange        = AutoFocusRange.FullRange;
                focusSettings.Mode                  = FocusMode.Auto;
                focusSettings.WaitForFocus          = true;
                focusSettings.DisableDriverFallback = false;

                _mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);
                await _mediaCapture.VideoDeviceController.ExposureControl.SetAutoAsync(true);

                //_mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                //_mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);


                PreviewElement.Source = _mediaCapture;
                await _mediaCapture.StartPreviewAsync();

                //mediaCapture.VideoDeviceController.PrimaryUse = Windows.Media.Devices.CaptureUse.Photo;
                //PreviewElement.Source = mediaCapture;
            }
            catch (Exception ex)
            {
                new MessageDialog(ex.Message, "Error");
            }
        }
        async Task SetupAutoFocus()
        {
            if (IsFocusSupported)
            {
                var focusControl = mediaCapture.VideoDeviceController.FocusControl;

                var focusSettings = new FocusSettings();

                if (ScanningOptions.DisableAutofocus)
                {
                    focusSettings.Mode     = FocusMode.Manual;
                    focusSettings.Distance = ManualFocusDistance.Nearest;
                    focusControl.Configure(focusSettings);
                    return;
                }

                focusSettings.AutoFocusRange = focusControl.SupportedFocusRanges.Contains(AutoFocusRange.FullRange)
                                        ? AutoFocusRange.FullRange
                                        : focusControl.SupportedFocusRanges.FirstOrDefault();

                var supportedFocusModes = focusControl.SupportedFocusModes;
                if (supportedFocusModes.Contains(FocusMode.Continuous))
                {
                    focusSettings.Mode = FocusMode.Continuous;
                }
                else if (supportedFocusModes.Contains(FocusMode.Auto))
                {
                    focusSettings.Mode = FocusMode.Auto;
                }

                if (focusSettings.Mode == FocusMode.Continuous || focusSettings.Mode == FocusMode.Auto)
                {
                    focusSettings.WaitForFocus = false;
                    focusControl.Configure(focusSettings);
                    await focusControl.FocusAsync();
                }
            }
        }
Exemplo n.º 17
0
        public async Task InitializeAsync()
        {
            _timeout = BarCodeManager.MaxTry;
            _sw.Restart();


            var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            var backCamera = devices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);

            m_mediaCapture = new MediaCapture();
            await m_mediaCapture.InitializeAsync();


            var focusControl = m_mediaCapture.VideoDeviceController.FocusControl;

            if (!focusControl.FocusChangedSupported)
            {
                OnErrorAsync(new Exception("AutoFocus control is not supported on this device"));
            }
            else
            {
                _cleanedUp   = false;
                _processScan = true;

                m_mediaCapture.FocusChanged += M_mediaCapture_FocusChanged;
                captureElement.Source        = m_mediaCapture;
                await m_mediaCapture.StartPreviewAsync();

                await focusControl.UnlockAsync();

                var settings = new FocusSettings {
                    Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.FullRange
                };
                focusControl.Configure(settings);
                await focusControl.FocusAsync();
            }
        }
        private VideoCapture(MediaCapture capture)
        {
            var cameraController = capture.VideoDeviceController;

            Capture        = capture;
            CanEnableLight = cameraController.TorchControl.Supported;
            CanFocus       = cameraController.FocusControl.Supported;

            if (CanFocus && cameraController.FocusControl.SupportedFocusModes.Count > 0)
            {
                var focusConfig = new FocusSettings();
                focusConfig.AutoFocusRange        = AutoFocusRange.Normal;
                focusConfig.DisableDriverFallback = false;
                if (cameraController.FocusControl.SupportedFocusModes.Contains(FocusMode.Continuous))
                {
                    focusConfig.Mode = FocusMode.Continuous;
                }
                else if (cameraController.FocusControl.SupportedFocusModes.Contains(FocusMode.Auto))
                {
                    focusConfig.Mode = FocusMode.Auto;
                }
            }
        }
Exemplo n.º 19
0
        public async void FocusOnTap(TappedRoutedEventArgs e)
        {
            if (isFocusing || !IsBackCamera)
                return;
            isFocusing = true;
            Point tappoint = e.GetPosition(captureElement);
            Point positionPercentage = new Point(tappoint.X / captureElement.ActualWidth, tappoint.Y / captureElement.ActualHeight);
            bool FocusAtPointSupported = mediaCapture.VideoDeviceController.RegionsOfInterestControl.AutoFocusSupported && mediaCapture.VideoDeviceController.RegionsOfInterestControl.MaxRegions > 0;
            if (!FocusAtPointSupported)
            {
                //throw new InvalidOperationException("Focus at point is not supported by the current device.");
            }

            if (positionPercentage.X < 0.0 || positionPercentage.X > 1.0)
            {
                //throw new ArgumentOutOfRangeException("focusPoint", positionPercentage, "Horizontal location in the viewfinder should be between 0.0 and 1.0.");
            }

            if (positionPercentage.Y < 0.0 || positionPercentage.Y > 1.0)
            {
                //throw new ArgumentOutOfRangeException("focusPoint", positionPercentage, "Vertical location in the viewfinder should be between 0.0 and 1.0.");
            }

            double x = positionPercentage.X;
            double y = positionPercentage.Y;
            double epsilon = 0.01;


            if (x >= 1.0 - epsilon)
            {
                x = 1.0 - 2 * epsilon;
            }

            if (y >= 1.0 - 0.01)
            {
                y = 1.0 - 2 * epsilon;
            }

            FocusSettings focusSettings = new FocusSettings { Mode = FocusMode.Single, AutoFocusRange = AutoFocusRange.FullRange };

            this.mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);

            await this.mediaCapture.VideoDeviceController.RegionsOfInterestControl.SetRegionsAsync(
                new[]
                {
                    new RegionOfInterest
                    {
                        Type             = RegionOfInterestType.Unknown,
                        Bounds           = new Windows.Foundation.Rect(x, y, epsilon, epsilon),
                        BoundsNormalized = true,
                        AutoFocusEnabled = true,
                        Weight           = 1
                    }
                });

            await this.mediaCapture.VideoDeviceController.FocusControl.FocusAsync();
            isFocusing = false;
        }
Exemplo n.º 20
0
        private async Task Init()
        {
            try
            {
                _displayRequest.RequestActive();

                _mediaCapture = new MediaCapture();
                var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);

                if (cameraDevice == null)
                {
                    Debug.WriteLine("No camera device found!");
                    return;
                }
                var settings = new MediaCaptureInitializationSettings
                {
                    StreamingCaptureMode = StreamingCaptureMode.Video,
                    MediaCategory        = MediaCategory.Other,
                    AudioProcessing      = Windows.Media.AudioProcessing.Default,
                    VideoDeviceId        = cameraDevice.Id,
                    PhotoCaptureSource   = PhotoCaptureSource.VideoPreview,
                };
                await _mediaCapture.InitializeAsync(settings);

                var focusControl = _mediaCapture.VideoDeviceController.FocusControl;

                if (focusControl.Supported)
                {
                    var focusSettings = new FocusSettings()
                    {
                        Mode = focusControl.SupportedFocusModes.FirstOrDefault(f => f == FocusMode.Continuous),
                        DisableDriverFallback = true,
                        AutoFocusRange        = focusControl.SupportedFocusRanges.FirstOrDefault(f => f == AutoFocusRange.FullRange),
                        Distance = focusControl.SupportedFocusDistances.FirstOrDefault(f => f == ManualFocusDistance.Nearest)
                    };

                    //设置聚焦,最好使用FocusMode.Continuous,否则影响截图会很模糊,不利于识别
                    focusControl.Configure(focusSettings);
                }


                VideoCapture.Source = _mediaCapture;
                _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                await _mediaCapture.StartPreviewAsync();

                //var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
                //MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings
                //{
                //    VideoDeviceId = devices[0].Id
                //}; // 0 => front, 1 => back

                //await _mediaCapture.InitializeAsync(settings);

                //VideoEncodingProperties resolutionMax = null;
                //int max = 0;
                //var resolutions = _mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo);

                //for (var i = 0; i < resolutions.Count; i++)
                //{
                //    VideoEncodingProperties res = (VideoEncodingProperties)resolutions[i];
                //    if (res.Width * res.Height > max)
                //    {
                //        max = (int)(res.Width * res.Height);
                //        resolutionMax = res;
                //    }
                //}

                //await _mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, resolutionMax);
                //capturePreview.Source = _mediaCapture;
                ////RegisterOrientationEventHandlers();
                //_mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                //await _mediaCapture.StartPreviewAsync();
                _orientationSensor.OrientationChanged += (s, arg) =>
                {
                    switch (arg.Orientation)
                    {
                    case SimpleOrientation.Rotated90DegreesCounterclockwise:
                        _mediaCapture.SetPreviewRotation(VideoRotation.None);
                        break;

                    case SimpleOrientation.Rotated180DegreesCounterclockwise:
                    case SimpleOrientation.Rotated270DegreesCounterclockwise:
                        _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise180Degrees);
                        break;

                    default:
                        _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                        break;
                    }
                };

                _timer          = new DispatcherTimer();
                _timer.Interval = TimeSpan.FromMilliseconds(50);
                _timer.Tick    += _timer_Tick;
                _timer.Start();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 21
0
 private async Task SetAutofocusAsync()
 {
     await _mediaCapture.VideoDeviceController.FocusControl.UnlockAsync();
     var focusSettings = new FocusSettings();
     focusSettings.AutoFocusRange = AutoFocusRange.FullRange;
     focusSettings.Mode = FocusMode.Continuous;
     focusSettings.WaitForFocus = true;
     focusSettings.DisableDriverFallback = false;
     _mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);
     await _mediaCapture.VideoDeviceController.FocusControl.FocusAsync();
 }
        public static async Task<ContinuousAutoFocus> StartAsync(FocusControl control)
        {
            var autoFocus = new ContinuousAutoFocus(control);

            AutoFocusRange range;
            if (control.SupportedFocusRanges.Contains(AutoFocusRange.FullRange))
            {
                range = AutoFocusRange.FullRange;
            }
            else if (control.SupportedFocusRanges.Contains(AutoFocusRange.Normal))
            {
                range = AutoFocusRange.Normal;
            }
            else
            {
                // Auto-focus disabled
                return autoFocus;
            }

            FocusMode mode;
            if (control.SupportedFocusModes.Contains(FocusMode.Continuous))
            {
                mode = FocusMode.Continuous;
            }
            else if (control.SupportedFocusModes.Contains(FocusMode.Single))
            {
                mode = FocusMode.Single;
            }
            else
            {
                // Auto-focus disabled
                return autoFocus;
            }

            if (mode == FocusMode.Continuous)
            {
                // True continuous auto-focus
                var settings = new FocusSettings()
                {
                    AutoFocusRange = range,
                    Mode = mode,
                    WaitForFocus = false,
                    DisableDriverFallback = false
                };
                control.Configure(settings);
                await control.FocusAsync();
            }
            else
            {
                // Simulated continuous auto-focus
                var settings = new FocusSettings()
                {
                    AutoFocusRange = range,
                    Mode = mode,
                    WaitForFocus = true,
                    DisableDriverFallback = false
                };
                control.Configure(settings);

                var ignore = Task.Run(async () => { await autoFocus.DriveAutoFocusAsync(); });
            }

            return autoFocus;
        }
Exemplo n.º 23
0
        /// <summary>
        /// Initializes a new MediaCapture instance and starts the Preview streaming to the CamPreview UI element.
        /// </summary>
        /// <returns>Async Task object returning true if initialization and streaming were successful and false if an exception occurred.</returns>
        private async Task <bool> StartWebcamStreamingAsync(CameraPanel panel, CaptureElement preview)
        {
            if (preview == null)
            {
                return(false);
            }

            var successful = true;

            try
            {
                this.preview            = preview;
                this.preview.Visibility = Visibility.Collapsed;

                // For this scenario, we only need Video (not microphone) so specify this in the initializer.
                // NOTE: the appxmanifest only declares "webcam" under capabilities and if this is changed to include
                // microphone (default constructor) you must add "microphone" to the manifest or initialization will fail.

                // Attempt to get the back camera if one is available, but use any camera device if not
                var cameraDevice = await FindCameraDeviceByPanelAsync(this.ConvertCameraPanelToDevicePanel(panel));

                var settings = new MediaCaptureInitializationSettings
                {
                    StreamingCaptureMode = StreamingCaptureMode.Video,
                    VideoDeviceId        = cameraDevice.Id
                };

                mediaCapture = new MediaCapture();
                await mediaCapture.InitializeAsync(settings);

                mediaCapture.Failed += this.MediaCapture_CameraStreamFailed;

                // Query all preview properties of the device.
                var deviceController = mediaCapture.VideoDeviceController;
                //var previewProperties = deviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview).Select(x => new StreamResolution(x));
                var photoProperties = deviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo).Select(x => new StreamResolution(x));

                var defaultEncodingProperties = GetMediaEncodingProperties(photoProperties);
                if (defaultEncodingProperties != null)
                {
                    await deviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, defaultEncodingProperties);
                }

                var focusControl = deviceController.FocusControl;
                if (focusControl.Supported)
                {
                    var focusSettings = new FocusSettings {
                        Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.Macro
                    };
                    focusControl.Configure(focusSettings);
                    await focusControl.FocusAsync();
                }

                // 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);
                CameraPanel      = this.ConvertDevicePanelToCameraPanel(cameraDevice.EnclosureLocation?.Panel ?? Windows.Devices.Enumeration.Panel.Unknown);

                await StartPreviewAsync();

                // Ensure the Semaphore is in the signalled state.
                frameProcessingSemaphore.Release();
            }
            catch (UnauthorizedAccessException)
            {
                // If the user has disabled their webcam this exception is thrown; provide a descriptive message to inform the user of this fact.
                successful = false;
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                successful = false;
            }

            return(successful);
        }
        private async Task SetupAutoFocus()
        {
            if (IsFocusSupported)
            {
                var focusControl = mediaCapture.VideoDeviceController.FocusControl;

                var focusSettings = new FocusSettings();
                focusSettings.AutoFocusRange = focusControl.SupportedFocusRanges.Contains(AutoFocusRange.FullRange)
                    ? AutoFocusRange.FullRange
                    : focusControl.SupportedFocusRanges.FirstOrDefault();

                var supportedFocusModes = focusControl.SupportedFocusModes;
                if (supportedFocusModes.Contains(FocusMode.Continuous))
                {
                    focusSettings.Mode = FocusMode.Continuous;
                }
                else if (supportedFocusModes.Contains(FocusMode.Auto))
                {
                    focusSettings.Mode = FocusMode.Auto;
                }

                if (focusSettings.Mode == FocusMode.Continuous || focusSettings.Mode == FocusMode.Auto)
                {
                    focusSettings.WaitForFocus = false;
                    focusControl.Configure(focusSettings);
                    await focusControl.FocusAsync();
                }
            }
        }
Exemplo n.º 25
0
        private async Task InitializeQrCode()
        {
            string error = null;
            try
            {
                //if (_mediaCapture == null)  
                //{  
                // Find all available webcams  
                DeviceInformationCollection webcamList = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);


                // Get the proper webcam (default one)  
                DeviceInformation backWebcam = (from webcam in webcamList where webcam.IsEnabled && webcam.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back select webcam).FirstOrDefault();


                // Initializing MediaCapture  


                _mediaCapture = new MediaCapture();
                await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
                {
                    VideoDeviceId = backWebcam.Id,
                    AudioDeviceId = "",
                    StreamingCaptureMode = StreamingCaptureMode.Video,
                    PhotoCaptureSource = PhotoCaptureSource.VideoPreview
                });


                // Adjust camera rotation for Phone  
                _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                _mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);


                // Set the source of CaptureElement to MediaCapture  
                captureElement.Source = _mediaCapture;
                await _mediaCapture.StartPreviewAsync();


                //_mediaCapture.FocusChanged += _mediaCapture_FocusChanged;


                // Seetting Focus & Flash(if Needed)  


                var torch = _mediaCapture.VideoDeviceController.TorchControl;
                if (torch.Supported) torch.Enabled = true;


                await _mediaCapture.VideoDeviceController.FocusControl.UnlockAsync();
                var focusSettings = new FocusSettings();
                focusSettings.AutoFocusRange = AutoFocusRange.FullRange;
                focusSettings.Mode = FocusMode.Continuous;
                focusSettings.WaitForFocus = true;
                focusSettings.DisableDriverFallback = false;
                _mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);
                await _mediaCapture.VideoDeviceController.FocusControl.FocusAsync();


                //}  
            }
            catch (Exception ex)
            {
                dialog = new MessageDialog("Error: " + ex.Message);
                dialog.ShowAsync();
            }
        }
        private async Task <bool> InitVideoCapture()
        {
            mediaCapture = new MediaCapture();
            var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);

            if (cameraDevice == null)
            {
                await UiUtils.NotifyUser("No camera device found!");

                return(false);
            }

            var settings = new MediaCaptureInitializationSettings
            {
                StreamingCaptureMode = StreamingCaptureMode.Video,
                MediaCategory        = MediaCategory.Other,
                AudioProcessing      = Windows.Media.AudioProcessing.Default,
                PhotoCaptureSource   = PhotoCaptureSource.VideoPreview,
                VideoDeviceId        = cameraDevice.Id
            };

            try
            {
                await mediaCapture.InitializeAsync(settings);
            }
            catch (UnauthorizedAccessException)
            {
                await UiUtils.NotifyUser("Please turn on the camera permission of the app to ensure scan QR code normaly.");

                return(false);
            }

            var focusControl = mediaCapture.VideoDeviceController.FocusControl;

            if (focusControl.Supported)
            {
                var focusSettings = new FocusSettings()
                {
                    Mode = focusControl.SupportedFocusModes.FirstOrDefault(f => f == FocusMode.Continuous),
                    DisableDriverFallback = true,
                    AutoFocusRange        = focusControl.SupportedFocusRanges.FirstOrDefault(f => f == AutoFocusRange.FullRange),
                    Distance = focusControl.SupportedFocusDistances.FirstOrDefault(f => f == ManualFocusDistance.Nearest)
                };
                focusControl.Configure(focusSettings);
            }
            VideoCapture.Source        = mediaCapture;
            VideoCapture.FlowDirection = FlowDirection.LeftToRight;
            // Fix preview mirroring for front webcam
            if (cameraDevice.EnclosureLocation?.Panel == Windows.Devices.Enumeration.Panel.Front)
            {
                VideoCapture.FlowDirection = FlowDirection.RightToLeft;
            }
            await mediaCapture.StartPreviewAsync();

            // Fix preview orientation for portrait-first devices (such as Windows Phone)
            if (DisplayInformation.GetForCurrentView().NativeOrientation == DisplayOrientations.Portrait)
            {
                var  props       = mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
                Guid RotationKey = new Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1");
                props.Properties.Add(RotationKey, 90);
                await mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, props, null);
            }
            if (mediaCapture.VideoDeviceController.FlashControl.Supported)
            {
                mediaCapture.VideoDeviceController.FlashControl.Enabled = false;
            }

            if (focusControl.Supported)
            {
                await focusControl.FocusAsync();
            }
            return(true);
        }
Exemplo n.º 27
0
        private async Task InitializeCameraAsync()
        {
            var cameraID = await GetCameraID(Windows.Devices.Enumeration.Panel.Back);
            
            MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings();
            settings.PhotoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.VideoPreview;
            settings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.Video;
            settings.AudioDeviceId = string.Empty;
            settings.VideoDeviceId = cameraID.Id;
            await this.photoTaker.InitializeAsync(settings);

            var maxResolution = this.photoTaker.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo).Aggregate((i1, i2) => (i1 as VideoEncodingProperties).Width > (i2 as VideoEncodingProperties).Width ? i1 : i2);
            await this.photoTaker.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, maxResolution);
            FocusSettings focusSetting = new FocusSettings() { Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.Normal, DisableDriverFallback = false, WaitForFocus = true };
            this.photoTaker.VideoDeviceController.FocusControl.Configure(focusSetting);
        }
Exemplo n.º 28
0
        /// <summary>
        /// 处理所预览的图片
        /// </summary>
        private async void PhotoHandle()
        {
            var focusSettings = new FocusSettings
            {
                Mode           = FocusMode.Auto,
                AutoFocusRange = AutoFocusRange.Macro,
                Distance       = ManualFocusDistance.Nearest
            };
            Result _result = null;

            try
            {
                while (_result == null && _cancel != true)
                {
                    //对焦
                    var autoFocusSupported = _mediaCapture.VideoDeviceController.FocusControl.SupportedFocusModes.Contains(FocusMode.Auto);
                    if (autoFocusSupported)
                    {
                        _mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);
                        //await _mediaCapture.VideoDeviceController.FocusControl.FocusAsync();
                    }
                    var photoStorageFile = await KnownFolders.PicturesLibrary.CreateFileAsync("scan.jpg", CreationCollisionOption.ReplaceExisting);

                    await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoStorageFile);

                    //获取文件的流
                    var stream = await photoStorageFile.OpenReadAsync();

                    var writeableBmp = new WriteableBitmap(1, 1);
                    writeableBmp.SetSource(stream);

                    writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight);
                    stream.Seek(0);
                    writeableBmp.SetSource(stream);

                    //识别扫描图片
                    status.Text = "开始扫描";
                    _result     = await ScanQRCodeAsync(writeableBmp);

                    await photoStorageFile.DeleteAsync(StorageDeleteOption.PermanentDelete);

                    //如果识别成功
                    if (_result != null)
                    {
                        status.Text = "识别成功:" + _result.Text + "开始连接";
                        await StopPreviewAsync();

                        tip.Stop();
                        string result = _result.Text;
                        //二维码解码为纯数字
                        if (IsInteger(result))
                        {
                            string[] info = new string[2];
                            info[0] = "Barcode";
                            info[1] = result;
                            SocketInit(_result.ToString(), "10240");

                            //break;
                            // await new MessageDialog(info[1]).ShowAsync();
                            _result = null;
                        }
                        //如果为网页链接,跳转到网页中
                        else
                        {
                            //await new MessageDialog(_result.ToString()).ShowAsync();

                            SocketInit(_result.ToString(), "10240");

                            //break;
                            // _result = null;
                        }
                    }
                    if (_result == null)
                    {
                        status.Text = "扫码失败,请重新扫描!!!";
                    }
                    if (App.IsConnect == true)
                    {
                        status.Text = "连接成功";
                        break;
                    }
                }
            }
            catch
            {
                return;
            }
        }
Exemplo n.º 29
0
        async private void Capture_Image(object sender, RoutedEventArgs e)
        {
            //Create JPEG image Encoding format for storing image in JPEG type  
            ImageEncodingProperties format = ImageEncodingProperties.CreateJpeg();

            StorageFile capturefile;

            //rotate and save the image
            using (var imageStream = new InMemoryRandomAccessStream())
            {
                try
                {
                    await captureManager.VideoDeviceController.FocusControl.UnlockAsync();
                    var focusSettings = new FocusSettings();
                    focusSettings.AutoFocusRange = AutoFocusRange.Normal;
                    focusSettings.Mode = FocusMode.Auto;
                    focusSettings.WaitForFocus = true;
                    focusSettings.DisableDriverFallback = false;
                    captureManager.VideoDeviceController.FocusControl.Configure(focusSettings);
                    await captureManager.VideoDeviceController.FocusControl.FocusAsync();
                }
                catch { }

                //generate stream from MediaCapture
                await captureManager.CapturePhotoToStreamAsync(format, imageStream);

                //create decoder and encoder
                BitmapDecoder dec = await BitmapDecoder.CreateAsync(imageStream);
                BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync(imageStream, dec);

                //roate the image
                enc.BitmapTransform.Rotation = BitmapRotation.Clockwise90Degrees;

                //write changes to the image stream
                await enc.FlushAsync();

                //save the image
                StorageFolder folder = KnownFolders.SavedPictures;
                capturefile = await folder.CreateFileAsync("photo_" + DateTime.Now.Ticks.ToString() + ".jpg", CreationCollisionOption.ReplaceExisting);
                string captureFileName = capturefile.Name;

                //store stream in file
                using (var fileStream = await capturefile.OpenStreamForWriteAsync())
                {
                    try
                    {
                        //because of using statement stream will be closed automatically after copying finished
                        await RandomAccessStream.CopyAsync(imageStream, fileStream.AsOutputStream());
                    }
                    catch
                    {

                    }
                }
            }

            this.Frame.Navigate(typeof(OcrText), capturefile);
        }  
Exemplo n.º 30
0
        private async void InitVideoCapture()
        {
            ///摄像头的检测
            var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);

            if (cameraDevice == null)
            {
                await new MessageDialog("没有找到摄像头!").ShowAsync();
                Debug.WriteLine("No camera device found!");
                return;
            }


            var settings = new MediaCaptureInitializationSettings
            {
                StreamingCaptureMode = StreamingCaptureMode.Video,
                MediaCategory        = MediaCategory.Other,
                AudioProcessing      = Windows.Media.AudioProcessing.Default,
                PhotoCaptureSource   = PhotoCaptureSource.VideoPreview,
                VideoDeviceId        = cameraDevice.Id
            };
            await _mediaCapture.InitializeAsync(settings);

            var focusControl = _mediaCapture.VideoDeviceController.FocusControl;

            if (focusControl.Supported)
            {
                var focusSettings = new FocusSettings()
                {
                    Mode = focusControl.SupportedFocusModes.FirstOrDefault(f => f == FocusMode.Continuous),
                    DisableDriverFallback = true,
                    AutoFocusRange        = focusControl.SupportedFocusRanges.FirstOrDefault(f => f == AutoFocusRange.FullRange),
                    Distance = focusControl.SupportedFocusDistances.FirstOrDefault(f => f == ManualFocusDistance.Nearest)
                };

                //设置聚焦,最好使用FocusMode.Continuous,否则影响截图会很模糊,不利于识别
                focusControl.Configure(focusSettings);
            }
            if (!SettingHelper.IsPc())
            {
                _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
            }


            VideoCapture.Source        = _mediaCapture;
            VideoCapture.FlowDirection = FlowDirection.LeftToRight;
            await _mediaCapture.StartPreviewAsync();

            //SimpleOrientationSensor sensor = SimpleOrientationSensor.GetDefault();
            //sensor.OrientationChanged += (s, arg) =>
            //{
            //    switch (arg.Orientation)
            //    {
            //        case SimpleOrientation.Rotated90DegreesCounterclockwise:
            //            _mediaCapture.SetPreviewRotation(VideoRotation.None);
            //            break;
            //        case SimpleOrientation.Rotated180DegreesCounterclockwise:
            //        case SimpleOrientation.Rotated270DegreesCounterclockwise:
            //            _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise180Degrees);
            //            break;
            //        default:
            //            _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
            //            break;
            //    }
            //};

            try
            {
                if (_mediaCapture.VideoDeviceController.FlashControl.Supported)
                {
                    //关闭闪光灯
                    _mediaCapture.VideoDeviceController.FlashControl.Enabled = false;
                }
            }
            catch
            {
            }

            if (focusControl.Supported)
            {
                //开始聚焦
                await focusControl.FocusAsync();
            }


            //var angle = CameraRotationHelper.ConvertSimpleOrientationToClockwiseDegrees(_rotationHelper.GetUIOrientation());
            // var transform = new RotateTransform { Angle = 90 };
            // VideoCapture.RenderTransform = transform;
        }
Exemplo n.º 31
0
        private async void Init()
        {
            //Get back camera
            var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
            var backCameraId = devices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Panel.Back).Id;

            //Start preview
            _cameraPreviewImageSource = new CameraPreviewImageSource();
            await _cameraPreviewImageSource.InitializeAsync(backCameraId);
            var properties = await _cameraPreviewImageSource.StartPreviewAsync();

            //Setup preview
            _width = 640.0;
            _height = (_width / properties.Width) * properties.Height;
            var bitmap = new WriteableBitmap((int)_width, (int)_height);

            _writeableBitmap = bitmap;

            PreviewImage.Source = _writeableBitmap;

            _writeableBitmapRenderer = new WriteableBitmapRenderer(_cameraPreviewImageSource, _writeableBitmap);

            _cameraPreviewImageSource.PreviewFrameAvailable += OnPreviewFrameAvailable;

            _videoDevice = (VideoDeviceController)_cameraPreviewImageSource.VideoDeviceController;
            
            //Set timer for auto focus
            if (_videoDevice.FocusControl.Supported)
            {
                var focusSettings = new FocusSettings
                {
                    AutoFocusRange = AutoFocusRange.Macro,
                    Mode = FocusMode.Auto,
                    WaitForFocus = false,
                    DisableDriverFallback = false
                };

                _videoDevice.FocusControl.Configure(focusSettings);

                _timer = new DispatcherTimer
                {
                    Interval = new TimeSpan(0, 0, 0, 2, 0)
                };
                _timer.Tick += TimerOnTick;
                _timer.Start();
            }

            await _videoDevice.ExposureControl.SetAutoAsync(true);

            _initialized = true;
        }
        private async void CafFocusRadioButton_Checked(object sender, RoutedEventArgs e)
        {
            // Reset tap-to-focus status
            _isFocused = false;
            FocusRectangle.Visibility = Visibility.Collapsed;

            var focusControl = _mediaCapture.VideoDeviceController.FocusControl;

            await focusControl.UnlockAsync();

            var settings = new FocusSettings { Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.FullRange };
            focusControl.Configure(settings);
            await focusControl.FocusAsync();
        }
        public async Task AutoFocusAsync(int x, int y, bool useCoordinates)
        {
            if (IsFocusSupported)
            {
                var focusControl = mediaCapture.VideoDeviceController.FocusControl;
                var roiControl = mediaCapture.VideoDeviceController.RegionsOfInterestControl;
                try
                {
                    if (roiControl.AutoFocusSupported && roiControl.MaxRegions > 0)
                    {
                        if (useCoordinates)
                        {
                            var props = mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);

                            var previewEncodingProperties = GetPreviewResolution(props);
                            var previewRect = GetPreviewStreamRectInControl(previewEncodingProperties, captureElement);
                            var focusPreview = ConvertUiTapToPreviewRect(new Point(x, y), new Size(20, 20), previewRect);
                            var regionOfInterest = new RegionOfInterest
                            {
                                AutoFocusEnabled = true,
                                BoundsNormalized = true,
                                Bounds = focusPreview,
                                Type = RegionOfInterestType.Unknown,
                                Weight = 100
                            };
                            await roiControl.SetRegionsAsync(new[] { regionOfInterest }, true);

                            var focusRange = focusControl.SupportedFocusRanges.Contains(AutoFocusRange.FullRange)
                                ? AutoFocusRange.FullRange
                                : focusControl.SupportedFocusRanges.FirstOrDefault();

                            var focusMode = focusControl.SupportedFocusModes.Contains(FocusMode.Single)
                                ? FocusMode.Single
                                : focusControl.SupportedFocusModes.FirstOrDefault();

                            var settings = new FocusSettings
                            {
                                Mode = focusMode,
                                AutoFocusRange = focusRange,
                            };

                            focusControl.Configure(settings);
                        }
                        else
                        {
                            // If no region provided, clear any regions and reset focus
                            await roiControl.ClearRegionsAsync();
                        }
                    }

                    await focusControl.FocusAsync();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("AutoFocusAsync Error: {0}", ex);
                }
            }
        }
Exemplo n.º 34
0
        async void createCamera()
        {
            CaptureUse primaryUse = CaptureUse.Video;

            mediaCapture = new MediaCapture();

            DeviceInformationCollection webcamList = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            DeviceInformation backWebcam = (from webcam in webcamList
                                            where webcam.EnclosureLocation != null &&
                                            webcam.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back
                                            select webcam).FirstOrDefault();


            await mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
            {
                VideoDeviceId        = backWebcam.Id,
                AudioDeviceId        = "",
                StreamingCaptureMode = StreamingCaptureMode.Video,
                PhotoCaptureSource   = PhotoCaptureSource.VideoPreview
            });

            mediaCapture.VideoDeviceController.PrimaryUse = primaryUse;

            mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);

            mediaCapture.VideoDeviceController.FlashControl.Enabled = false;

            setEffects();

            reader = new BarcodeReader
            {
                Options = new DecodingOptions
                {
                    PossibleFormats = new BarcodeFormat[] { BarcodeFormat.QR_CODE },
                    TryHarder       = true
                }
            };


            captureElement.Source = mediaCapture;
            await mediaCapture.StartPreviewAsync();

            focusControl = mediaCapture.VideoDeviceController.FocusControl;

            if (focusControl.Supported == true)
            {
                FocusSettings focusSetting = new FocusSettings()
                {
                    AutoFocusRange        = AutoFocusRange.FullRange,
                    Mode                  = FocusMode.Auto,
                    WaitForFocus          = false,
                    DisableDriverFallback = false
                };

                focusControl.Configure(focusSetting);
                await mediaCapture.VideoDeviceController.ExposureControl.SetAutoAsync(true);

                //await focusControl.FocusAsync();
            }

            // zoom
            if (this.mediaCapture.VideoDeviceController.ZoomControl.Supported)
            {
                sliderZoom.Minimum       = this.mediaCapture.VideoDeviceController.ZoomControl.Min;
                sliderZoom.Maximum       = this.mediaCapture.VideoDeviceController.ZoomControl.Max;
                sliderZoom.StepFrequency = this.mediaCapture.VideoDeviceController.ZoomControl.Step;
            }
        }
Exemplo n.º 35
0
        private async Task InitializeQrCode()
        {
            string error = null;

            try
            {
                //if (_mediaCapture == null)
                //{
                // Find all available webcams
                DeviceInformationCollection webcamList = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);


                // Get the proper webcam (default one)
                DeviceInformation backWebcam = (from webcam in webcamList where webcam.IsEnabled select webcam).FirstOrDefault();


                // Initializing MediaCapture


                _mediaCapture = new MediaCapture();
                await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
                {
                    VideoDeviceId        = backWebcam.Id,
                    AudioDeviceId        = "",
                    StreamingCaptureMode = StreamingCaptureMode.Video,
                    PhotoCaptureSource   = PhotoCaptureSource.VideoPreview
                });


                // Adjust camera rotation for Phone
                _mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                _mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);


                // Set the source of CaptureElement to MediaCapture
                captureElement.Source = _mediaCapture;
                await _mediaCapture.StartPreviewAsync();


                // _mediaCapture.FocusChanged += _mediaCapture_FocusChanged; // ToDo:


                // Seetting Focus & Flash(if Needed)


                var torch = _mediaCapture.VideoDeviceController.TorchControl;
                if (torch.Supported)
                {
                    torch.Enabled = true;
                }


                await _mediaCapture.VideoDeviceController.FocusControl.UnlockAsync();

                var focusSettings = new FocusSettings();
                focusSettings.AutoFocusRange        = AutoFocusRange.FullRange;
                focusSettings.Mode                  = FocusMode.Continuous;
                focusSettings.WaitForFocus          = true;
                focusSettings.DisableDriverFallback = false;
                _mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);
                await _mediaCapture.VideoDeviceController.FocusControl.FocusAsync();


                //}
            }
            catch (Exception ex)
            {
                dialog = new MessageDialog("Error: " + ex.Message);
                dialog.ShowAsync();
            }
        }
Exemplo n.º 36
0
        public static async Task <ContinuousAutoFocus> StartAsync(FocusControl control)
        {
            var autoFocus = new ContinuousAutoFocus(control);

            AutoFocusRange range;

            if (control.SupportedFocusRanges.Contains(AutoFocusRange.FullRange))
            {
                range = AutoFocusRange.FullRange;
            }
            else if (control.SupportedFocusRanges.Contains(AutoFocusRange.Normal))
            {
                range = AutoFocusRange.Normal;
            }
            else
            {
                // Auto-focus disabled
                return(autoFocus);
            }

            FocusMode mode;

            if (control.SupportedFocusModes.Contains(FocusMode.Continuous))
            {
                mode = FocusMode.Continuous;
            }
            else if (control.SupportedFocusModes.Contains(FocusMode.Single))
            {
                mode = FocusMode.Single;
            }
            else
            {
                // Auto-focus disabled
                return(autoFocus);
            }

            if (mode == FocusMode.Continuous)
            {
                // True continuous auto-focus
                var settings = new FocusSettings()
                {
                    AutoFocusRange        = range,
                    Mode                  = mode,
                    WaitForFocus          = false,
                    DisableDriverFallback = false
                };
                control.Configure(settings);
                await control.FocusAsync();
            }
            else
            {
                // Simulated continuous auto-focus
                var settings = new FocusSettings()
                {
                    AutoFocusRange        = range,
                    Mode                  = mode,
                    WaitForFocus          = true,
                    DisableDriverFallback = false
                };
                control.Configure(settings);

                var ignore = Task.Run(async() => { await autoFocus.DriveAutoFocusAsync(); });
            }

            return(autoFocus);
        }
Exemplo n.º 37
0
        public async Task InitializeAsync()
        {
            _timeout = BarCodeManager.MaxTry;
            _sw.Restart();
   

            var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
            var backCamera = devices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);

            m_mediaCapture = new MediaCapture();
            await m_mediaCapture.InitializeAsync();

            
            var focusControl = m_mediaCapture.VideoDeviceController.FocusControl;
            if (!focusControl.FocusChangedSupported)
            {
                OnErrorAsync(new Exception("AutoFocus control is not supported on this device"));
            }
            else
            {
                _cleanedUp = false;
                _processScan = true;

                m_mediaCapture.FocusChanged += M_mediaCapture_FocusChanged;
                captureElement.Source = m_mediaCapture;
                await m_mediaCapture.StartPreviewAsync();
                await focusControl.UnlockAsync();
                var settings = new FocusSettings { Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.FullRange };
                focusControl.Configure(settings);
                await focusControl.FocusAsync();
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// 图片处理 获取中间代码区域部分
        /// </summary>
        private async void PhotoHandle()
        {
            var focusSettings = new FocusSettings
            {
                Mode = FocusMode.Auto,
                AutoFocusRange = AutoFocusRange.Macro,
                Distance = ManualFocusDistance.Nearest
            };
            Result _result = null;
            try
            {
                while (_result == null && _cancel != true)
                {
                    //对焦
                    var autoFocusSupported = _mediaCapture.VideoDeviceController.FocusControl.SupportedFocusModes.Contains(FocusMode.Auto);
                    if (autoFocusSupported)
                    {                       
                        _mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);
                        await _mediaCapture.VideoDeviceController.FocusControl.FocusAsync().AsTask();

                    }

                    var photoStorageFile = await KnownFolders.PicturesLibrary.CreateFileAsync("scan.jpg", CreationCollisionOption.ReplaceExisting);
                    await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoStorageFile);

                    var stream = await photoStorageFile.OpenReadAsync();
                    //stream.Seek(0);
                    //await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreatePng(), stream);
                    // initialize with 1,1 to get the current size of the image
                    var writeableBmp = new WriteableBitmap(1, 1);
                    writeableBmp.SetSource(stream);
                    // and create it again because otherwise the WB isn't fully initialized and decoding
                    // results in a IndexOutOfRange
                    writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight);
                    stream.Seek(0);
                    writeableBmp.SetSource(stream);

                    _result =await ScanQRCodeAsync(writeableBmp);

                    await photoStorageFile.DeleteAsync(StorageDeleteOption.PermanentDelete);
                    //如果识别成功
                    if (null != _result)
                    {
                        //      await new MessageDialog(res.Text).ShowAsync();
                        await StopPreviewAsync();
                        tip.Stop();
                        string result = _result.Text;
                        if (IsInteger(result))
                        {
                            string[] info = new string[2];
                            info[0] = "Barcode";
                            info[1] = result;
                      
                            SuppressNavigationTransitionInfo n = new SuppressNavigationTransitionInfo();
                            ((Frame)Window.Current.Content).Navigate(typeof(SearchPage_M), info, n);
                            //获取导航然后清理上一个
                            var a = ((Frame)Window.Current.Content).BackStack;
                            a.RemoveAt(a.Count - 1);
                        }
                        //如果为网页链接,跳转到网页中
                        else
                        {
                            ((Frame)Window.Current.Content).Navigate(typeof(WebView_M), result);
                            //获取导航然后清理上一个
                            var a = ((Frame)Window.Current.Content).BackStack;
                            a.RemoveAt(a.Count - 1);
                        }
                        break;
                    }

                

                }
            }
            catch
            {
                //await new MessageDialog("相机出现问题,请退出该页面重新初始化相机").ShowAsync();
                return;
            }
           

            //var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\1.png");
            //var stream = await file.OpenReadAsync();
            //// initialize with 1,1 to get the current size of the image
            //var writeableBmp = new WriteableBitmap(1, 1);
            //writeableBmp.SetSource(stream);
            //// and create it again because otherwise the WB isn't fully initialized and decoding
            //// results in a IndexOutOfRange
            //writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight);
            //stream.Seek(0);
            //writeableBmp.SetSource(stream);

            //var result = ScanQRCode(writeableBmp);
            //if (result != null)
            //{
            //    await new MessageDialog(result.Text).ShowAsync();
            //}
            //return;
            #region MyRegion
            //while (true)
            //{

            //    if (_isInitialized && _isPreviewing)
            //    {
            //        //对焦
            //        var autoFocusSupported = _mediaCapture.VideoDeviceController.FocusControl.SupportedFocusModes.Contains(FocusMode.Auto);
            //        if (autoFocusSupported)
            //        {
            //            var focusSettings = new FocusSettings
            //            {
            //                Mode = FocusMode.Auto,
            //                AutoFocusRange = AutoFocusRange.Macro,
            //                Distance = ManualFocusDistance.Nearest
            //            };
            //            _mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);
            //            await _mediaCapture.VideoDeviceController.FocusControl.FocusAsync().AsTask();

            //        }
            //        //拍照
            //        //获取照片方向
            //        var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
            //        //设置照片流

            //        var file = await KnownFolders.PicturesLibrary.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.GenerateUniqueName);
            //        using (var stream = new InMemoryRandomAccessStream())
            //        {
            //            await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
            //            var decoder = await BitmapDecoder.CreateAsync(stream);
            //            using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            //            {
            //                var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);
            //                var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };
            //                await encoder.BitmapProperties.SetPropertiesAsync(properties);
            //                await encoder.FlushAsync();
            //            }
            //        }
            //        using (var streamResult = await file.OpenAsync(FileAccessMode.Read))
            //        {
            //            var writeableBmp = new WriteableBitmap(1, 1);
            //            writeableBmp.SetSource(streamResult);
            //            writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight);
            //            streamResult.Seek(0);
            //            writeableBmp.SetSource(streamResult);
            //            await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
            //            image.Source = writeableBmp;
            //        }
            //        ////截图获取图片
            //        var s = clipImage.TransformToVisual(root);
            //        Point p = s.TransformPoint(new Point(0, 0));
            //        RectangleGeometry rect = new RectangleGeometry();
            //        rect.Rect = new Rect(p.X, p.Y, 300, 300);
            //        image.Clip = rect;
            //        await Task.Delay(TimeSpan.FromSeconds(0.1));
            //        RenderTargetBitmap ss = new RenderTargetBitmap();
            //        await ss.RenderAsync(clip);
            //        //让显示图片区域为空
            //        image.Source = null;
            //        var writeBmp = await ClipPhotoHandleAsync(ss);
            //        //       i.Source = writeBmp;

            //        var res = ScanQRCode(writeBmp);
            //        //如果识别成功
            //        if (null != res)
            //        {
            //            //      await new MessageDialog(res.Text).ShowAsync();
            //            await StopPreviewAsync();
            //            tip.Stop();
            //            string result = res.Text;
            //            if (IsInteger(result))
            //            {
            //                string[] info = new string[2];
            //                info[0] = "Barcode";
            //                info[1] = result;
            //                SuppressNavigationTransitionInfo n = new SuppressNavigationTransitionInfo();
            //                ((Frame)Window.Current.Content).Navigate(typeof(SearchPage_M), info, n);
            //                //获取导航然后清理上一个
            //                var a = ((Frame)Window.Current.Content).BackStack;
            //                a.RemoveAt(a.Count - 1);
            //            }
            //            //如果为网页链接,跳转到网页中
            //            else
            //            {
            //                ((Frame)Window.Current.Content).Navigate(typeof(WebView_M), result);
            //                //获取导航然后清理上一个
            //                var a = ((Frame)Window.Current.Content).BackStack;
            //                a.RemoveAt(a.Count - 1);
            //            }
            //            break;
            //        }
            //    }
            //    else
            //    {
            //        return;
            //    }
            //}
            #endregion


        }
        /// <summary>
        /// Sets camera to focus on the passed in region of interest
        /// </summary>
        /// <param name="region">The region to focus on, or null to focus on the default region</param>
        /// <returns></returns>
        private async Task<MediaCaptureFocusState> FocusCamera(RegionOfInterest region)
        {
            var roiControl = _mediaCapture.VideoDeviceController.RegionsOfInterestControl;
            var focusControl = _mediaCapture.VideoDeviceController.FocusControl;

            if (region != null)
            {
                // If the call provided a region, then set it
                await roiControl.SetRegionsAsync(new[] { region }, true);

                var focusRange = focusControl.SupportedFocusRanges.Contains(AutoFocusRange.FullRange) ? AutoFocusRange.FullRange : focusControl.SupportedFocusRanges.FirstOrDefault();
                var focusMode = focusControl.SupportedFocusModes.Contains(FocusMode.Single) ? FocusMode.Single : focusControl.SupportedFocusModes.FirstOrDefault();

                var settings = new FocusSettings { Mode = focusMode, AutoFocusRange = focusRange };

                focusControl.Configure(settings);
            }
            else
            {
                // If no region provided, clear any regions and reset focus
                await roiControl.ClearRegionsAsync();
            }

            await focusControl.FocusAsync();

            return focusControl.FocusState;
        }