Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

Face Detection in Windows Phone

From Wiki
Jump to: navigation, search

This article demonstrate how to use the Face Detection library for Windows Phone.

WP Metro Icon Multimedia.png
WP Metro Icon UI.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
Article Metadata
Code ExampleTested with
Devices(s): Nokia Lumia 820,920
Windows Phone 8
Created: somnathbanik (16 Aug 2014)
Last edited: somnathbanik (17 Aug 2014)



Hello friends, almost a year back I was exploring the Face Detection Library for Windows Phone and found that the library was not supporting portrait orientation. During the course of working with the library we added portrait support along with few more features which can add more value to the library like, overlay mask on face, take picture with the mask on run time, save and share photo on social network. This article shows how to use the library and create a real time face detection application in Windows Phone.


Create a standard Windows Phone Project

Let’s create a standard Windows Phone Application Project

  • Launch Visual Studio
  • Click on File
  • Click on New Project
  • Select Windows Phone App (Visual C# Template)
  • Add Name and Location of the project
  • Click OK to create the project.

Create a Custom Control Project

  • Right Click on Project Solution
  • Click on Add
  • Select New Project
  • Select Windows Phone Class Library
  • Add Name and Location of the project
  • Click OK to create the project.
  • Create a class file CameraViewer.cs and FaceDetection.xaml into the project.
  • Finally add the Custom Control project reference to your main project.

Creating UI

  • Before starting to write code in the project make sure you have added your favourite mask image in the project; in this example we have created an image folder in the project and put the mask image into it. Now you are ready to write code in your project. Now open the FaceDetection.xaml file and add the following code to create the camera viewer
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="0,0,0,0" MouseLeftButtonDown="cameraViewer_MouseLeftButtonDown_1" MouseLeftButtonUp="cameraViewer_MouseLeftButtonUp_1">
<CamControl:CameraViewer x:Name="cameraViewer">
<Canvas x:Name="cnvsFaceRegions" Width="480" Height="800" HorizontalAlignment="Center" VerticalAlignment="Center">
<StackPanel x:Name="sck_Mask" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="12,0,12,0" Width="600">
<TextBlock x:Name="cameraResolution" Visibility="Collapsed" TextWrapping="Wrap" Text="" FontSize="30"></TextBlock>

Code Behind

  • To find the camera orientation and detect face add the below code in FaceDetection.xaml.cs file.
foreach (var r in faces)
// Rectangle toAdd = new Rectangle();
Image imgAdd = new Image();
BitmapImage bmp = new BitmapImage();
bmp.UriSource = new Uri(@"/Images/Mask.png", UriKind.RelativeOrAbsolute);
imgAdd.Source = bmp;
TranslateTransform loc = new TranslateTransform();
if (AppGlobal.isPortrait)
loc.X = r.X * _downsampleFactor / (double)w * cnvsFaceRegions.ActualWidth;
loc.Y = r.Y * _downsampleFactor / (double)w * cnvsFaceRegions.ActualHeight;
loc.X = r.X * _downsampleFactor / (double)w * cnvsFaceRegions.ActualWidth - 50;
loc.Y = r.Y * _downsampleFactor / (double)w * cnvsFaceRegions.ActualHeight + 90;
imgAdd.RenderTransform = loc;
imgAdd.Width = r.Width * _downsampleFactor + 50;
imgAdd.Height = r.Height * _downsampleFactor + 50;
  • When the application loads it initialized the camera and find the camera orientation .
  protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
cameraViewer.SaveToCameraRoll = true;
cameraViewer.NewCameraFrame += NewCameraFrame;
// The event is fired when the shutter button receives a half press.
CameraButtons.ShutterKeyHalfPressed += OnButtonHalfPress;
// The event is fired when the shutter button receives a full press.
CameraButtons.ShutterKeyPressed += OnButtonFullPress;
// The event is fired when the shutter button is released.
CameraButtons.ShutterKeyReleased += OnButtonRelease;
  • The StartPumpingFrames() method of CameraViewer.cs class initialized the camera.
  public void InitializeCamera()
// m_detector = new FaceDetectionWinPhone.Detector(System.Xml.Linq.XDocument.Load(MODEL_FILE));
// Check to see if the camera is available on the device.
if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) ||
(PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true))
// Initialize the default camera.
_camera = new Microsoft.Devices.PhotoCamera();
//Event is fired when the PhotoCamera object has been initialized
Camera.Initialized +=
new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(CameraInitialized);
Camera.CaptureImageAvailable += CameraOnCaptureImageAvailable;
Camera.CaptureCompleted += CameraOnCaptureCompleted;
//Set the VideoBrush source to the camera
// var viewfinderBrush = new VideoBrush();
viewfinderBrush = new VideoBrush();
viewfinderBrush.Stretch = Stretch.Fill;
viewfinderBrush.RelativeTransform = new CompositeTransform { CenterX = 0.5, CenterY = 0.5 };
System.Windows.Shapes. Rectangle rect = new System.Windows.Shapes.Rectangle();
rect.Fill = viewfinderBrush;
// initialize the shutter sound
// Audio
Stream stream = TitleContainer.OpenStream("models/shutter.wav");
_cameraShutterSound = SoundEffect.FromStream(stream);
// CameraButtons.ShutterKeyPressed -= CameraButtonsOnShutterKeyPressed;
if (_photoOnPress)
// CameraButtons.ShutterKeyPressed += CameraButtonsOnShutterKeyPressed;
// The camera is not supported on the device.
"Sorry, this sample requires a phone camera and no camera is detected. This application will not show any camera output.");
  • SaveScreenShots() and ShareMask() method take the picture with the mark and share it on the social network respectively.
private void SaveScreenShots()
// Audio
Stream stream = TitleContainer.OpenStream( "models/shutter.wav");
_cameraShutterSound = SoundEffect.FromStream(stream);
catch (Exception ex)
WriteableBitmap bmp = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
bmp.Render(this, null);
byte[] bb = EncodeToJpeg(bmp);
MemoryStream mem = new MemoryStream();
bmp.SaveJpeg(mem, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
mem.Seek(0, System.IO.SeekOrigin.Begin);
if (mem != null)
MediaLibrary library = new MediaLibrary();
pic = library.SavePicture("Mask_" + Guid.NewGuid().ToString(), mem);
MaskPath = pic.GetPath();
Deployment.Current.Dispatcher.BeginInvoke(() =>
MessageBoxResult result= MessageBox.Show("Your picture is now accessible through the Saved Picture album.", "Saved successfully", MessageBoxButton.OK);
catch (Exception ex)
MessageBox.Show("Unable to save the photo." + ex);
cameraViewer.NewCameraFrame += NewCameraFrame;
private void ShareMask()
Deployment.Current.Dispatcher.BeginInvoke(() =>
if (!String.IsNullOrEmpty(MaskPath))
ShareMediaTask shareMediaTask = new ShareMediaTask();
shareMediaTask.FilePath = MaskPath;
MessageBox.Show("Unable to share this picture.","Sharing Error",MessageBoxButton.OK);


  • This library is based on OpenCV and also capable of detecting other models. You can get more model files from OpenCV website.

Source Code

Related Articles

This page was last modified on 17 August 2014, at 17:00.
766 page views in the last 30 days.