首页 > 代码库 > 在Windows IoT上使用网络摄像头

在Windows IoT上使用网络摄像头

在树莓派上可以使用它官方标配的摄像头,但是这个摄像头似乎不能被Windows IoT识别和使用。但是,可以在树莓派的USB口上插入任意型号的摄像头,就可以实现树莓派的拍摄功能。

关于摄像头的寻找和拍摄,我将其封装成一个类,如下:

    public class WebCamHelper
    {
        public MediaCapture mediaCapture;

        private bool initialized = false;

        /// <summary>
        /// 异步初始化网络摄像头
        /// </summary>
        public async Task InitializeCameraAsync()
        {
            if (mediaCapture == null)
            {
                // 尝试发现摄像头
                var cameraDevice = await FindCameraDevice();

                if (cameraDevice == null)
                {
                    // 没有发现摄像头
                    Debug.WriteLine("No camera found!");
                    initialized = false;
                    return;
                }

                // Creates MediaCapture initialization settings with foudnd webcam device
                var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };

                mediaCapture = new MediaCapture();
                await mediaCapture.InitializeAsync(settings);
                initialized = true;
            }
        }

        /// <summary>
        /// 异步寻找摄像头,如果没有找到,返回null,否则返回DeviceInfomation
        /// </summary>
        private static async Task<DeviceInformation> FindCameraDevice()
        {
            // Get available devices for capturing pictures
            var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);


            if (allVideoDevices.Count > 0)
            {
                // 如果发现,返回
                return allVideoDevices[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 开启摄像头预览
        /// </summary>
        public async Task StartCameraPreview()
        {
            try
            {
                await mediaCapture.StartPreviewAsync();
            }
            catch
            {
                initialized = false;
                Debug.WriteLine("Failed to start camera preview stream");
            }
        }

        /// <summary>
        /// 关闭摄像头预览
        /// </summary>
        public async Task StopCameraPreview()
        {
            try
            {
                await mediaCapture.StopPreviewAsync();
            }
            catch
            {
                Debug.WriteLine("Failed to stop camera preview stream");
            }
        }


        /// <summary>
        /// 拍摄照片,返回StorageFile,文件将被存储到临时文件夹
        /// </summary>
        public async Task<StorageFile> CapturePhoto()
        {
            // Create storage file in local app storage
            string fileName = GenerateNewFileName() + ".jpg";
            CreationCollisionOption collisionOption = CreationCollisionOption.GenerateUniqueName;
            StorageFile file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(fileName, collisionOption);

            // 拍摄并且存储
            await mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), file);

            //await Task.Delay(500);

            return file;
        }

        /// <summary>
        /// 产生文件名称
        /// </summary>
        private string GenerateNewFileName()
        {
            return " IoTSample" + DateTime.Now.ToString("yyyy.MMM.dd HH-mm-ss");
        }

        public string GenerateUserNameFileName(string userName)
        {
            return userName + DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss") + ".jpg";
        }

        /// <summary>
        /// 如果摄像头初始化成功,返回true,否则返回false
        /// </summary>
        public bool IsInitialized()
        {
            return initialized;
        }

使用示例:

1.初始化

        private WebCamHelper camera;
        if(camera==null)
            {
                camera = new WebCamHelper();
                await camera.InitializeCameraAsync();
            }
            if(camera.IsInitialized())
            {
                tbMessage.Text = "Camera启动成功...";
            }
            else
            {
                tbMessage.Text = "Camera启动失败...";
            }    

2.拍摄

            if (!camera.IsInitialized()) return;
            StorageFile imgFile = await camera.CapturePhoto();

拍摄完成的图片文件就存储在上面的imgFile中。

3.视频预览

如果想开启视频预览,实时查看摄像头捕获的图像,可以在XAML中先添加一个CaptureElement控件:

<CaptureElement x:Name="cameraElement"
                        Loaded="cameraElement_Loaded"/>

在CaptureElement的Loaded事件中执行source绑定:

cameraElement.Source = camera.mediaCapture;

然后在想要开始视频预览的地方,执行:

await camera.StartCameraPreview();

关闭视频预览:

await camera.StopCameraPreview();

 

在Windows IoT上使用网络摄像头