SlideShare uma empresa Scribd logo
1 de 88
Nokia Internal Use Only
Photos et autres Sensors
sur Windows Phone
Nicolas CALVI
Consultant / Formateur
MVP Hardware Interaction Design & Development

Wygwam
Nicolas DELABARRE
Relations techniques développeurs

Code/Developpement
Code/developpement
Nokia Internal Use Only
Donnez votre avis !
Depuis votre smartphone sur :
http://notes.mstechdays.fr
De nombreux lots à gagner toute les heures !!!
Claviers, souris et jeux Microsoft…
Merci de nous aider à améliorer les Techdays !

#mstechdays

Code/developpement

Nokia Internal Use Only
WINDOWS PHONE
Un téléphone plein de ressources

#mstechdays

Code/developpement

Nokia Internal Use Only
Qu’est-ce que Windows Phone ?
Un OS créer par Microsoft à destination
des
Constructeurs de SmartPhone.
Une expérience unique grâce a Modern
UI
Des usages multiples
•
•

Grand public
Entreprise

#mstechdays

Code/developpement

Nokia Internal Use Only
Qu’est-ce que Windows Phone ?
Un concentré de technologie
- Caméra jusqu’à 41 MP
- Flash
- GPS
- Accéléromètre
- Baromètre (Altimètre)
- Gyroscope
- Wifi, Bluetooth, 4G
- NFC
- Magnétomètre (Boussole)
- Capteur de lumière ambiant
- Capteur de proximité
-…
#mstechdays

Code/developpement

Nokia Internal Use Only
Qu’allons nous aborder ?
Les senseurs

Non accessible

- Caméra
> Vidéo
> Photo
- Accéléromètre
- Compas
- GPS
- Gyroscope
- Inclinomètre
- Motion API

- Capteur de proximité
- Capteur de
luminosité

On finira par de la Réalité Augmentée avec GART
Le capteur NFC ne sera pas traiter dans cette session
#mstechdays

Code/developpement

Nokia Internal Use Only
SENSEUR : LA CAMÉRA
Il sait voir au-delà de votre perception

#mstechdays

Code/developpement

Nokia Internal Use Only
Comment afficher le flux vidéo ?
// Le namespace
using System.Windows.Media;
// Création du device de capture vidéo
CaptureSource captureSource = new CaptureSource();
VideoCaptureDevice device = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
// On vérifie si la capture est possible

if (device != null)
{
// On crée un Brush pour afficher la vidéo dans notre UI
VideoBrush videoBrush = new VideoBrush();
videoBrush.SetSource(captureSource);
VideoRect.Fill = videoBrush; // Rectangle dans notre XAML
// On démarre la préview Vidéo
captureSource.Start();
}
#mstechdays

Code/developpement

Nokia Internal Use Only
Comment afficher le flux vidéo ?
Ne pas oublier de fermer la camera video !
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
if (captureSource != null)
captureSource.Stop();
base.OnNavigatingFrom(e);
}

#mstechdays

Code/developpement

Nokia Internal Use Only
Comment prendre une photo ?
// On vérifie si la caméra est disponible
if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) || (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true))
{
PhotoCamera photoCamera;
// Initialise la caméra en fonction des capacitées trouvées
if (PhotoCamera.IsCameraTypeSupported(CameraType.Primary))
photoCamera = new PhotoCamera(CameraType.Primary);
else
photoCamera = new PhotoCamera(CameraType.FrontFacing);
// On se branche sur les événements
photoCamera.Initialized += OnPhotoCameraInitialized;
photoCamera.CaptureCompleted += OnPhotoCameraCaptureCompleted;
photoCamera.CaptureImageAvailable += OnPhotoCameraCaptureImageAvailable;
photoCamera.CaptureThumbnailAvailable += OnPhotoCameraCaptureThumbnailAvailable;
// Création d'un Brush pour afficher le buffer dans notre UI
VideoBrush photoBrush = new VideoBrush();
photoBrush.SetSource(photoCamera);

// Affectation du Brush a notre zone de rendu
PhotoRect.Fill = photoBrush; // Rectangle dans notre XAML
}

#mstechdays

Code/developpement

Nokia Internal Use Only
Comment prendre une photo ?
// Déclenche la prise de photo
photoCamera.CaptureImage();

OnPhotoCameraCaptureImageAvailable
OnPhotoCameraCaptureCompleted
OnPhotoCameraCaptureThumbnailAvailable

#mstechdays

Code/developpement

Nokia Internal Use Only
Comment prendre une photo ?
// On sauvegarde la photo dans la média
MediaLibrary librarylibrary = new MediaLibrary();
library.SavePictureToCameraRoll("MonFichier.jpg", e.ImageStream);
// On se repositionne au début du flux de l'image
e.ImageStream.Seek(0, SeekOrigin.Begin);
// Enregistrement de la photo en JPEG dans le répertoire local
using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
{
// Initialisation du buffer (4ko)
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// On copie l'image dans le répertoire local
while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
targetStream.Write(readBuffer, 0, bytesRead);
}
}
// On ferme le fichier
e.ImageStream.Close();

#mstechdays

Code/developpement

Nokia Internal Use Only
Comment prendre une photo ?
Ne pas oublier de fermer la camera photo !
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
if (photoCamera != null)
{
photoCamera.Initialized -= OnPhotoCameraInitialized;
photoCamera.CaptureCompleted -= OnPhotoCameraCaptureCompleted;
photoCamera.CaptureImageAvailable -= OnPhotoCameraCaptureImageAvailable;
photoCamera.CaptureThumbnailAvailable -= OnPhotoCameraCaptureThumbnailAvailable;
photoCamera.Dispose();
}

base.OnNavigatingFrom(e);
}

#mstechdays

Code/developpement

Nokia Internal Use Only
Prise de photo haute résolution
Lumia 1020
7712 x 4352 (16:9)
7136 x 5360 (4:3)

Lumia 1520
5376 x 3024 (16:9)
4992 x 3744 (4:3)

#mstechdays

Code/developpement

Nokia Internal Use Only
NOKIA IMAGING SDK 1.0
Allez plus loin avec ses photos

#mstechdays

Code/developpement

Nokia Internal Use Only
Qu’est-ce que le SDK Nokia Imaging ?
• Librairie native Windows Phone 8, accessible depuis
des projets WP8 C#, VB et C++
• Inclus plus de 50 filtres de traitement d’images et
effets visuels paramétrables
• Ne nécessite aucune connaissance particulière en
traitement algorithmique d’images
• Décodage JPEG partiel – basée sur la technologie
RAJPEG, afin d’accéder aux données sans décoder
toute l’image JPEG :
• Prévisualisation rapide
• Application d’effets, tels que la rotation ou le
cropping d’images haute résolution
#mstechdays

Code/developpement

Nokia Internal Use Only
Liste de filtres et effets (1/3)

#mstechdays

Code/developpement

Nokia Internal Use Only
Liste de filtres et effets (2/3)

#mstechdays

Code/developpement

Nokia Internal Use Only
Liste de filtres et effets (3/3)

#mstechdays

Code/developpement

Nokia Internal Use Only
Enchaînement de filtres

Image
originale
+Milky
+Flip
+Crop
+Lomo
#mstechdays

Code/developpement

Nokia Internal Use Only
Architecture générale
• Cette librairie est architecturée en 3 blocs :
• Image sources (e.g. bitmaps, streams,
files)
• Effect (e.g. 50+ filtres)
• Renderers (outputs bitmaps or files)
• En combinant ces blocs, on va créer un
tunnel de traitement d’image ( ou “rendering
pipeline”)
• Une fois le tunnel créé, il est possible de
modifier les paramètres de filtres ou leur
#mstechdays
Code/developpement
séquencement.
Nokia Internal Use Only

Image Source
Filter Effects
MagicPen
Filter Filter
Flip
Rotation Filter
Renderer
Producteur / Consommateur

#mstechdays

Code/developpement

Nokia Internal Use Only
Comment appliquer un filtre à une photo ?
// Création d'un nokia stream à partir d'un IO Stream

using(var source = new StreamImageSource(e.ChosenPhoto))
// Création d'un effet initial à partir de la source stream nokia

using (var effect = new FilterEffect(source))
// Instanciation d'un render de type "WriteableBitmap"

using( var render = new WriteableBitmapRenderer(effect,
_writeableBitmapTarget))
{
// Création de la liste des filtres

var filters = new List<IFilter>();
filters.Add(new MagicPenFilter());
// Affectation de la liste de filtres à notre objet "effet"

effect.Filters = filters;
// Exécution du rendu

await render.RenderAsync();
// Force le repaint de l'image résultante
_writeableBitmapTarget.Invalidate();
}

#mstechdays

Code/developpement

Nokia Internal Use Only
Et plusieurs filtres ?
// Création d'un nokia stream à partir d'un IO Stream

using( var source = new StreamImageSource(e.ChosenPhoto))
// Création d'un effet initial à partir de la source stream nokia

using( var effect = new FilterEffect(source))
// Instanciation d'un render de type "WriteableBitmap"

using( var render = new WriteableBitmapRenderer(effect,
_writeableBitmapTarget))
{
// Création de la liste des filtres

var filters = new List<IFilter>();
filters.Add(new MagicPenFilter());
filters.Add(new RotationFilter(15));
// Affectation de la liste de filtres à notre objet "effet"

effect.Filters = filters;
// Exécution du rendu

await render.RenderAsync();
// Force le repaint de l'image résultante
_writeableBitmapTarget.Invalidate();
}

#mstechdays

Code/developpement

Nokia Internal Use Only
Modifier les paramètres de filtre
Les paramètres peuvent être changés sans reconstruire le tunnel
de traitement.
•

Néanmoins il faut garder à l’esprit :
• Que le rendu est asynchrone, les paramètres ne peuvent pas être
changés en cours.
• Attention avec certains contrôles UI (e.g. sliders) qui peuvent générer
des événements n’importe quand !

•

Astuce : utiliser une file d’attente d’événements de type Queue<Action>.

#mstechdays

Code/developpement

Nokia Internal Use Only
Modifier les paramètres de filtre
UI (Slider)

Imaging
SDK

ValueChanged event

Rendering a
new preview

ValueChanged event

ValueChanged event

#mstechdays

Code/developpement

Nokia Internal Use Only

Rendering a
new preview
Modifier les paramètres de filtre
Définir une queue d’attente:
Queue<System.Action> _toDo = new Queue<System.Action>();

Quand la ressource est occupée, empiler l’action dans la queue d’attente:
_toDo.Enqueue(
() => { _warpFilter.Level = newValue; }
);

Lambda expression
directement
mise en queue

Quand la ressource est dispo, traitement des actions en attente :
while (_toDo.Count > 0)
{
Action action = _toDo.Dequeue();
action();
}
await _renderer.RenderAsync();

#mstechdays

Exécution des lambda
expression

Code/developpement

Nokia Internal Use Only
Image Source
Type de source

Class

ImageSource
Name

Stream

System.IO.Stream

StreamImageSource

Image Bitmap

Windows.Media.Imaging.WriteableBitmap

BitmapImageSource

Nokia.Graphics.Imaging.Bitmap

Windows Buffer

Windows.Storage.Streams.IBuffer

BufferImageSource

Camera

Windows.Phone.Media.Capture.
ICameraCaptureDevice

CameraPreviewImageSource

Flat Color

Windows.Ui.Color

ColorImageSource

File

Windows.Storage.IStorageFile

StorageFileImageSource

Random Access
Stream

Windows.Storage.Streams.
IRandomAccessStream

RandomAccessStreamImage
Source

#mstechdays

Code/developpement

Nokia Internal Use Only

Image Source
Filter Effects
MagicPen
Filter Filter
Flip
Rotation Filter
Renderer
Renderer
Image Source
Type de
Destination

Class

ImageSource
Name

Imaging SDK Bitmap

Nokia.Graphics.Imaging.Bitmap

BitmapRenderer

Writeable Bitmaps
(XAML Image )

WriteableBitmap

WriteableBitmapRenderer

JPEG

Windows.Storage.Streams.IBuffer

Filter Effects

JpegRenderer

MagicPen
Filter Filter
Flip
Rotation Filter
Renderer

#mstechdays

Code/developpement

Nokia Internal Use Only
Implémentation de filtre personnalisé
// Création d'un effet personnalisé

public class MyCustomFilter : CustomEffectBase
{
public MyCustomFilter(IImageProvider source): base(source)
{
}
protected override void OnProcess(PixelRegion sourcePixelRegion,
PixelRegion targetPixelRegion)
{
sourcePixelRegion.ForEachRow((index, width, pos) =>
{
for (int i = 0; i < width; ++i, ++index)
{
Windows.UI.Color c = ToColor(sourcePixelRegion.ImagePixels[index]);
c.R = (byte)Math.Min(255, c.R * 2);
c.G = (byte)Math.Min(255, c.G * 2);
c.B = (byte)Math.Min(255, c.B * 2);
targetPixelRegion.ImagePixels[index] = FromColor(c);
}
});
}
}

#mstechdays

Code/developpement

Nokia Internal Use Only
APIs pour créer des images sources de type
gradients
• Facilité d’utilisation
• Faible empreinte mémoire

Radial
Gradient
#mstechdays

Linear
Gradient
Code/developpement

Nokia Internal Use Only
Création d’image source gradient
// Affectation de la source de notre Image XAML avec un writeable bitmap
imageTarget.Source = _writeableBitmapTarget;
// Création d'un gradient de couleur de type "radial"
var rad = new RadialGradient(new Windows.Foundation.Point(0.5, 0.5),
new EllipseRadius(0.3, 0.3));
rad.Stops = new GradientStop[]
{
new GradientStop() { Color = Windows.UI.Color.FromArgb(255, 255, 0, 0), Offset = 0 },
new GradientStop() { Color = Windows.UI.Color.FromArgb(255, 0, 255, 0), Offset = 1 }
};
// Création d'une image source de type gradient à partir du gradient
using (var grad = new GradientImageSource(
new Windows.Foundation.Size(imageTarget.Width, imageTarget.Height), rad))
{
// Instantiation d'un render de type "WriteableBitmap" initialisé avec notre gradient
// source et le writeable bitmap de sortie
var render = new WriteableBitmapRenderer(grad, _writeableBitmapTarget);
// Exécution du rendu
await render.RenderAsync();
}

#mstechdays

Code/developpement

Nokia Internal Use Only
Blend modes
1ère image

Blend mode:
Color Burn
#mstechdays

Blend mode:
Color
Code/developpement

Nokia Internal Use Only

2nde image

Blend mode:
Add
Blend d’une photo avec un gradient
// Affectation de la source de notre Image XAML avec un writeable bitmap
imageTarget.Source = _writeableBitmapTarget;
// Création d'un nokia stream à partir d'un IO Stream
using (var backgroundSource = new StreamImageSource(e.ChosenPhoto))
// Création d'une image source de type gradient à partir du gradient
using(var foregroundSource = new GradientImageSource( ...))
// Création d'un filtre d'effet sourcé avec l'image choisie par l'utilisateur
using(var filterEffect = new FilterEffect(backgroundSource))
// Création d'un filtre de blending sourcé avec l'image source gradient
using(var blendFilter = new BlendFilter(foregroundSource))
// Instantiation d'un render de type "WriteableBitmap" initialisé avec notre filtre d'effet et le bitmap de sortie
using(var renderer = new WriteableBitmapRenderer(filterEffect, _writeableBitmapTarget))
{
// Configuration de notre filtre d'effet avec un seul effet ... notre effet blend
blendFilter.BlendFunction = BlendFunction.Color;
filterEffect.Filters = new IFilter[] { blendFilter };
// Exécution du rendu
await renderer.RenderAsync();
// Force le repaint de l'image resultante
_writeableBitmapTarget.Invalidate();

}

#mstechdays

Code/developpement

Nokia Internal Use Only
ChromaKey + Blend

#mstechdays

Code/developpement

Nokia Internal Use Only
Pour aller plus loin
Point d’entrée des ressources techniques relative au SDK Imaging :
http://developer.nokia.com/resources/library/Lumia/nokia-imaging-sdk.html
Projets d’exemples basés sur le SDK Imaging (avec code source) :
http://developer.nokia.com/resources/library/Lumia/nokia-imagingsdk/sample-projects.html
Forum de discussion dédié au SDK Imaging :
http://developer.nokia.com/community/discussion
Articles Wiki :
http://developer.nokia.com/community/wiki/Portal:Windows_Phone_Multi
media

#mstechdays

Code/developpement

Nokia Internal Use Only
SENSEUR : ACCELEROMETRE
Une bonne raison de bouger utile

#mstechdays

Code/developpement

Nokia Internal Use Only
Qu’est-ce que c’est ?
Un accéléromètre est un capteur qui, fixé à
un mobile ou tout autre objet, permet de
mesurer l’accélération linéaire de ce dernier.
On parle encore d'accéléromètre même s'il
s'agit en fait de 3 accéléromètres qui
calculent les 3 accélérations linéaires selon
3 axes orthogonaux.
Source Wikipédia : http://fr.wikipedia.org/wiki/Acc%C3%A9l%C3%A9rom%C3%A8tre

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
// Le namespace
using Microsoft.Devices.Sensors;
// Comment savoir si le téléphone supporte cette fonctionnalité
if (!Accelerometer.IsSupported)
return;

// Comment l’instancier
accelerometer = new Accelerometer();
accelerometer.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);
// Comment récupérer l’information
accelerometer.CurrentValueChanged += OnAccelerometerCurrentValueChanged;
// Comment le démarrer
accelerometer.Start();
#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
private void OnAccelerometerCurrentValueChanged(object sender,
SensorReadingEventArgs<AccelerometerReading> args)
{
AccelerometerReading reading = args.SensorReading;
this.Dispatcher.BeginInvoke(() =>
{
TxtTimestamp.Text = reading.Timestamp.ToString();
TxtAccelerationX.Text = reading.Acceleration.X.ToString();
TxtAccelerationY.Text = reading.Acceleration.Y.ToString();
TxtAccelerationZ.Text = reading.Acceleration.Z.ToString();
});
}

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
Ne pas oublier de fermer le senseur !
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
if (accelerometer != null)
accelerometer.Stop();
base.OnNavigatingFrom(e);
}

#mstechdays

Code/developpement

Nokia Internal Use Only
API partagées avec Windows 8
// Le namespace
using Windows.Devices.Sensors;
// Comment l’instancier
accelerometer = Accelerometer.GetDefault();
// Comment savoir si le téléphone supporte cette fonctionnalité
if (accelerometer != NULL)
return;
// Comment récupérer l’information

accelerometer.ReadingChanged += OnAccelerometerReadingChanged;

#mstechdays

Code/developpement

Nokia Internal Use Only
API partagées avec Windows 8
private void OnAccelerometerReadingChanged(Accelerometer sender,
AccelerometerReadingChangedEventArgs args)
{
AccelerometerReading reading = args.SensorReading;
this.Dispatcher.BeginInvoke(() =>
{
TxtTimestamp.Text = reading.Timestamp.ToString();
TxtAccelerationX.Text = reading.Acceleration.X.ToString("0.00");
TxtAccelerationY.Text = reading.Acceleration.Y.ToString("0.00");
TxtAccelerationZ.Text = reading.Acceleration.Z.ToString("0.00");

}
}

#mstechdays

Code/developpement

Nokia Internal Use Only
SENSEUR : COMPAS
Pour que tout cela est un sens

#mstechdays

Code/developpement

Nokia Internal Use Only
Qu’est-ce que c’est ?
le compas magnétique, dont le principe de
fonctionnement est, comme une boussole,
l'orientation d'une aiguille aimantée dans le
champ du magnétisme terrestre.

Source Wikipédia : http://fr.wikipedia.org/wiki/Compas_(navigation)

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
// Le namespace
using Microsoft.Devices.Sensors;
// Comment savoir si le téléphone supporte cette fonctionnalité
if (!Compass.IsSupported)
return;
// Comment l’instancier
compass = new Compass();
compass.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);
// Comment récupérer l’information
compass.CurrentValueChanged += OnCompassCurrentValueChanged;
compass.Calibrate += OnCompassCalibrate;
// Comment le démarrer
compass.Start();

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
private void OnCompassCurrentValueChanged(object sender,
SensorReadingEventArgs<CompassReading> args)
{
CompassReading reading = args.SensorReading;
this.Dispatcher.BeginInvoke(() =>
{
TxtTimestamp.Text = reading.Timestamp.ToString();
TxtMagneticHeading.Text = reading.MagneticHeading.ToString();
TxtTrueHeading.Text = reading.TrueHeading.ToString();
TxtAccuracy.Text = reading.HeadingAccuracy.ToString();
});
}

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
private void OnCompassCalibrate(object sender, CalibrationEventArgs args)
{
// Mettre votre code ici
// Le compas a besoin d’être calibré
}

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
Pour calibrer le compas, si la propriété « Accuracy » est supérieure à 15,
il faut faire des « 8 » avec le téléphone.
Ceci peut-être gérer dans l’interface, en affichant un texte d’aide invitant
l’utilisateur a faire les « 8 ».
Dès que la valeur descend en dessous de 15, on peut notifier l’utilisateur
que le compas est calibré.

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
Ne pas oublier de fermer le senseur !
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
if (compass != null)
compass.Stop();
base.OnNavigatingFrom(e);
}

#mstechdays

Code/developpement

Nokia Internal Use Only
API partagées avec Windows 8
// Le namespace
using Windows.Devices.Sensors;
// Comment l’instancier
compass = Compass.GetDefault();
// Comment savoir si le téléphone supporte cette fonctionnalité
if (compass != NULL)
return;
// Comment récupérer l’information

compass.ReadingChanged += OnCompassReadingChanged;

#mstechdays

Code/developpement

Nokia Internal Use Only
API partagées avec Windows 8
private void OnCompassReadingChanged(Compass sender, CompassReadingChangedEventArgs args)
{
CompassReading reading = args.SensorReading;
this.Dispatcher.BeginInvoke(() =>
{
CompassTime.Text = reading.Timestamp.ToString();
CompassMagneticHeading.Text = reading.HeadingMagneticNorth.ToString();
CompassTrueHeading.Text = reading.HeadingTrueNorth.Value.ToString();
}
}

#mstechdays

Code/developpement

Nokia Internal Use Only
SENSEUR : GPS
Si vous n’avez pas le sens de l’orientation mieux vaut le consulter

#mstechdays

Code/developpement

Nokia Internal Use Only
Qu’est-ce que c’est ?
Le Global Positioning System (GPS) – que
l'on peut traduire en français par « système
de localisation mondial » – est un système
de géolocalisation fonctionnant au niveau
mondial.

Source Wikipédia : http://fr.wikipedia.org/wiki/Global_Positioning_System

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
// Le namespace
using System.Device.Location;
// Comment l’instancier
gps = new GeoCoordinateWatcher(GeoPositionAccuracy.High); // Ou Default
gps.MovementThreshold = 0;
// Comment récupérer l’information
gps.PositionChanged += OnGeoCoordinateWatcherPositionChanged;
gps.StatusChanged += OnGeoCoordinateWatcherStatusChanged;
// Comment le démarrer
gps.Start();

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
private void OnGeoCoordinateWatcherStatusChanged(object sender,
GeoPositionStatusChangedEventArgs args)
{
this.Dispatcher.BeginInvoke(() =>
{
GPSManualStatus.Text = e.Status.ToString();
});
}
// Les valeurs de Status

GeoPositionStatus.Disabled
.Initializing
.NoData
.Ready

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
private void OnGeoCoordinateWatcherPositionChanged(object sender,
GeoPositionChangedEventArgs<GeoCoordinate> args)
{

this.Dispatcher.BeginInvoke(() =>
{
GPSTime.Text = e.Position.Timestamp.ToString();
GPSLatitude.Text = e.Position.Location.Latitude.ToString();
GPSLongitude.Text = e.Position.Location.Longitude.ToString();
GPSAltitude.Text = e.Position.Location.Altitude.ToString();
GPSHAccuracy.Text = e.Position.Location.HorizontalAccuracy.ToString();
GPSVAccuracy.Text = e.Position.Location.VerticalAccuracy.ToString();
GPSCourse.Text = e.Position.Location.Course.ToString();
GPSSpeed.Text = e.Position.Location.Speed.ToString();
GPSUnknown.Text = e.Position.Location.IsUnknown.ToString();
});
}

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
Ne pas oublier de fermer le senseur !
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
if (gps != null)
gps.Stop();
base.OnNavigatingFrom(e);
}

#mstechdays

Code/developpement

Nokia Internal Use Only
API partagées avec Windows 8
// Le namespace
using Windows.Devices.Geolocation;
// Comment l’instancier
gps = new Geolocator();

gps.DesiredAccuracy = PositionAccuracy.High; // Ou Default
gps.DesiredAccuracyInMeters = 10; // En dessous de 10m ce n’est pas possible
gps.MovementThreshold = 0;
gps.ReportInterval = 1000; // Le GPS a un taux de rafraichissement d’1Hz
// Comment récupérer l’information
gps.PositionChanged += OnGeolocatorPositionChanged;
gps.StatusChanged += OnGeolocatorStatusChanged;

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
private void OnGeolocatorStatusChanged(Geolocator sender, StatusChangedEventArgs args)
{
this.Dispatcher.BeginInvoke(() =>
{
GPSManualStatus.Text = e.Status.ToString();
});
}
// Les valeurs de Status

PositionStatus.Disabled
.Initializing
.NoData
.NotAvailable
.NotInitialized
.Ready

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
private void OnGeolocatorPositionChanged (Geolocator sender, PositionChangedEventArgs args)
{
this.Dispatcher.BeginInvoke(() =>
{
GPSTime.Text = args.Position.Coordinate.Timestamp.ToString();
GPSLatitude.Text = args.Position.Coordinate.Latitude.ToString();
GPSLongitude.Text = args.Position.Coordinate.Longitude.ToString();
GPSAltitude.Text = args.Position.Coordinate.Altitude.ToString();
GPSAltitudeAccuracy.Text = args.Position.Coordinate.AltitudeAccuracy.ToString();
GPSAccuracy.Text = args.Position.Coordinate.Accuracy.ToString();
GPSSpeed.Text = args.Position.Coordinate.Speed.ToString();
}
}

#mstechdays

Code/developpement

Nokia Internal Use Only
SENSEUR : GYROSCOPE
Il ne vous fera pas tourner en bourrique celui là

#mstechdays

Code/developpement

Nokia Internal Use Only
Qu’est-ce que c’est ?
Un gyroscope (du grec « qui observe la rotation
») est un appareil qui exploite le principe de la
conservation du moment angulaire en physique
(ou encore stabilité gyroscopique ou effet
gyroscopique).
Cette loi fondamentale de la mécanique veut
qu'en l'absence de couple appliqué à un solide en
rotation, celui-ci conserve son axe de rotation
invariable
Source Wikipédia : http://fr.wikipedia.org/wiki/Gyroscope

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
// Le namespace
using Microsoft.Devices.Sensors;
// Comment savoir si le téléphone supporte cette fonctionnalité
if (!Gyroscope.IsSupported)
return;

// Comment l’instancier
gyroscope = new Gyroscope();
gyroscope.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);
// Comment récupérer l’information
gyroscope.CurrentValueChanged += OnGyroscopeCurrentValueChanged;
// Comment le démarrer
gyroscope.Start();
#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
private void OnGyroscopeCurrentValueChanged(object sender,
SensorReadingEventArgs<GyroscopeReading> args)
{
GyroscopeReading reading = args.SensorReading;
this.Dispatcher.BeginInvoke(() =>
{
TxtTimestamp.Text = reading.Timestamp.ToString();
TxtRotationX.Text = reading.RotationRate.X.ToString();
TxtRotationY.Text = reading.RotationRate.Y.ToString();
TxtRotationZ.Text = reading.RotationRate.Z.ToString();
}
}

#mstechdays

Code/developpement

Nokia Internal Use Only
API spécifique Windows Phone 8
Ne pas oublier de fermer le senseur !
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
if (gyroscope != null)
gyroscope.Stop();
base.OnNavigatingFrom(e);
}

#mstechdays

Code/developpement

Nokia Internal Use Only
API partagées avec Windows 8
// Le namespace
using Windows.Devices.Sensors;
// Comment l’instancier
gyroscope = Gyrometer.GetDefault();
// Comment savoir si le téléphone supporte cette fonctionnalité
if (gyroscope != NULL)
return;
// Comment récupérer l’information

gyroscope.ReadingChanged += OnGyroscopeReadingChanged;

#mstechdays

Code/developpement

Nokia Internal Use Only
API partagées avec Windows 8
private void OnGyroscopeReadingChanged (Gyrometer sender, GyrometerReadingChangedEventArgs
args)
{
GyrometerReading reading = args.SensorReading;
this.Dispatcher.BeginInvoke(() =>
{
TxtTimestamp.Text = reading.Timestamp.ToString();
TxtRotationX.Text = reading.AngularVelocityX.ToString("0.00");
TxtRotationY.Text = reading.AngularVelocityY.ToString("0.00");
TxtRotationZ.Text = reading.AngularVelocityZ.ToString("0.00");

}
}

#mstechdays

Code/developpement

Nokia Internal Use Only
SENSEUR : INCLINOMÈTRE
Tel le bambou, il sait plier.

#mstechdays

Code/developpement

Nokia Internal Use Only
Qu’est-ce que c’est ?
Un inclinomètre (ou clinomètre) est un capteur
servant à mesurer des angles par rapport à la
ligne d'horizon (ou horizontale).
Là où le niveau à bulle (ou niveau) permet de
détecter précisément où se situe l'horizontale,
l'inclinomètre détermine en plus l'angle
d'inclinaison par rapport à cette horizontale.

Source Wikipédia : http://fr.wikipedia.org/wiki/Inclinom%C3%A8tre

#mstechdays

Code/developpement

Nokia Internal Use Only
API partagées avec Windows 8
// Le namespace
using Windows.Devices.Sensors;
// Comment l’instancier
inclinometer = Inclinometer.GetDefault();
// Comment savoir si le téléphone supporte cette fonctionnalité
if (inclinometer!= NULL)
return;
// Comment récupérer l’information
inclinometer.ReadingChanged += OnInclinometerReadingChanged;

#mstechdays

Code/developpement

Nokia Internal Use Only
API partagées avec Windows 8
private void OnInclinometerReadingChanged (Inclinometer sender,
InclinometerReadingChangedEventArgs args)
{
InclinometerReading reading = args.SensorReading;
this.Dispatcher.BeginInvoke(() =>
{
TxtTimestamp.Text = reading.Timestamp.ToString();
TxtPitch.Text = reading.PitchDegrees.ToString("0.00");
TxtRoll.Text = reading.RollDegrees.ToString("0.00");
TxtYaw.Text = reading.YawDegrees.ToString("0.00");

}
}

#mstechdays

Code/developpement

Nokia Internal Use Only
MOTION API
Avoir tous ses sens en éveils

#mstechdays

Code/developpement

Nokia Internal Use Only
Qu’est-ce que c’est ?
Vous pouvez utiliser la « Motion API » pour créer des applications Windows
Phone qui utilisent l'orientation et le mouvement de l'appareil dans l'espace
comme un mécanisme d'entrée.
La plate-forme Windows Phone inclut des APIs pour obtenir des données
brutes du capteur de la boussole de l'appareil, gyroscope, accéléromètre et des
capteurs.
Cependant la « Motion API » gère le calcul complexe nécessaire pour combiner
les données de ces capteurs et produire des valeurs facile à utiliser pour
l'attitude et le mouvement de l'appareil.
#mstechdays

Code/developpement

Nokia Internal Use Only
Comment ça marche ?
// Le namespace
using Microsoft.Devices.Sensors;
// Comment savoir si le téléphone supporte cette fonctionnalité
if (!Motion.IsSupported)
return;

// Comment l’instancier
motion = new Motion();
motion.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);
// Comment récupérer l’information
motion.CurrentValueChanged += OnMotionCurrentValueChanged;
// Comment le démarrer
motion.Start();
#mstechdays

Code/developpement

Nokia Internal Use Only
Comment ça marche ?
private void OnGyroscopeCurrentValueChanged(object sender, SensorReadingEventArgs<MotionReading>
args)
{
MotionReading reading = args.SensorReading;
this.Dispatcher.BeginInvoke(() =>
{
TxtTimestamp.Text = reading.Timestamp.ToString();
TxtPitch.Text = reading.Attitude.Pitch.ToString(); // En radian
TxtRoll.Text = reading.Attitude.Roll.ToString(); // En radian
TxtYaw.Text = reading.Attitude.Yaw.ToString(); // En radian
TxtAccellerationX.Text = reading.DeviceAcceleration.X.ToString();
TxtAccellerationY.Text = reading.DeviceAcceleration.Y.ToString();
TxtAccellerationZ.Text = reading.DeviceAcceleration.Z.ToString();
}
}

#mstechdays

Code/developpement

Nokia Internal Use Only
Connaître l’attitude
La « Motion API » permet de connaître l’orientation du téléphone dans un
espace 3D. Dans les informations retournées, on peut récupérer le Quaternion
et la matrice de rotation de cette attitude.
MotionReading reading = args.SensorReading;
// Récupération du Quaternion
reading.Quaternion;
// Récupération de la matrice de rotation
reading.RotationMatrix;

#mstechdays

Code/developpement

Nokia Internal Use Only
REALITE AUGMENTEE : GART
Regarder le monde sous un nouveau jour, n’est-ce pas Wayne ?

#mstechdays

Code/developpement

Nokia Internal Use Only
Qu’est-ce que GART ?
Un SDK Open Source développer
par un employé de Microsoft.
Permet de faire de la réalité
augmentée Géo localisée.

Disponible à cette adresse :
http://gart.codeplex.com/
#mstechdays

Compatible :
- Windows Phone 7 et 8
- Windows 8 et 8.1

Code/developpement

Nokia Internal Use Only
NOKIA JOB HUB
Application Pilote Windows Phone réalisée avec GART

#mstechdays

Code/developpement

Nokia Internal Use Only
#mstechdays

Code/developpement

Nokia Internal Use Only
Comment ça marche ?
<phone:PhoneApplicationPage xmlns:gart="clr-namespace:GART.Controls;assembly=GART.WP8">
<Grid>
<gart:ARDisplay x:Name="ARDisplay"
AttitudeRefreshRate="50"
MovementThreshold="10">
<gart:VideoPreview />
<gart:WorldView FarClippingPlane="300.0"
MaxItemScale="1.0"
MinItemScale="0.1"
NearClippingPlane="1.0">
<gart:WorldView.ItemTemplate>
<DataTemplate>
<Border Background="White"
BorderBrush="Green"
BorderThickness="1"
Padding="5">
<TextBlock FontSize="20"
Foreground="Black"
Text="{Binding Content}" />
</Border>
</DataTemplate>
</gart:WorldView.ItemTemplate>
</gart:WorldView>
</gart:ARDisplay>
</Grid>

#mstechdays

Code/developpement

Nokia Internal Use Only
Comment ça marche ?
// On crée une liste de point a afficher
items = new ObservableCollection<ARItem>();
// Création d’un élément a afficher
// Mettre ici des éléments valide en coordonnée pour les voir apparaitre
// Pour trouver des coordonnées, allez sur Bing Maps
ARItem point = new ARItem();
point.Content = "Un objet a afficher";
point.GeoLocation = new System.Device.Location.GeoCoordinate(48.821229, 2.254397, 0);
items.Add(point);
// On affecte la source
this.ARDisplay.ARItems = items;

#mstechdays

Code/developpement

Nokia Internal Use Only
Comment ça marche ?
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
this.ARDisplay.StopServices();
base.OnNavigatedFrom(e);
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
this.ARDisplay.StartServices();
base.OnNavigatedTo(e);
}

#mstechdays

Code/developpement

Nokia Internal Use Only
DES QUESTIONS ?
N’hésitez pas on sera ravi de vous répondre.

#mstechdays

Code/developpement

Nokia Internal Use Only
Restez en contact
Nicolas Calvi
Blog > blog.nicolascalvi.com
Twitter > @nicolascalvi
Page Facebook > Black Blog

Nicolas Delabarre
Blog > www.nokiadevblog.fr
Twitter > @NokiaDev_France
Page Facebook > NokiaDevFrance
Code source : http://sdrv.ms/1coyrnH
#mstechdays

Code/developpement

Nokia Internal Use Only
Digital is
business

Nokia Internal Use Only

Mais conteúdo relacionado

Semelhante a Photos et autres sensors sur Windows Phone

[FR] Capture vidéo avec HTML5
[FR] Capture vidéo avec HTML5[FR] Capture vidéo avec HTML5
[FR] Capture vidéo avec HTML5Thomas Bassetto
 
Kinect en moins de 10 Minutes
Kinect en moins de 10 MinutesKinect en moins de 10 Minutes
Kinect en moins de 10 MinutesMicrosoft
 
Optimisation des applications Windows 8/HTML5/WinJS
Optimisation des applications Windows 8/HTML5/WinJSOptimisation des applications Windows 8/HTML5/WinJS
Optimisation des applications Windows 8/HTML5/WinJSMicrosoft
 
Formation logiciel Isadora TROIKATRONIX
Formation logiciel Isadora TROIKATRONIXFormation logiciel Isadora TROIKATRONIX
Formation logiciel Isadora TROIKATRONIXGuillaume Lecreux
 
Initiation au code : Introduction et installation des outils
Initiation au code : Introduction et installation des outilsInitiation au code : Introduction et installation des outils
Initiation au code : Introduction et installation des outilsStéphanie Hertrich
 
Utiliser l'EDI pour développer en multiplateforme
Utiliser l'EDI pour développer en multiplateformeUtiliser l'EDI pour développer en multiplateforme
Utiliser l'EDI pour développer en multiplateformepprem
 
10 tips pour améliorer les performances de vos applications Windows 8
10 tips pour améliorer les performances de vos applications Windows 810 tips pour améliorer les performances de vos applications Windows 8
10 tips pour améliorer les performances de vos applications Windows 8Microsoft
 
Retour d'expérience AdobeMC 2011
Retour d'expérience AdobeMC 2011Retour d'expérience AdobeMC 2011
Retour d'expérience AdobeMC 2011jonasmonnier
 
Projet de-recherche-Tuteuré
Projet de-recherche-TuteuréProjet de-recherche-Tuteuré
Projet de-recherche-TuteuréRullier Anthony
 
Migrer de Windows XP à Windows 8.1 avec MDT 2013
Migrer de Windows XP à Windows 8.1 avec MDT 2013 Migrer de Windows XP à Windows 8.1 avec MDT 2013
Migrer de Windows XP à Windows 8.1 avec MDT 2013 Microsoft Technet France
 
Etendre ses applications aux smartwatches et TVs android
Etendre ses applications aux smartwatches et TVs androidEtendre ses applications aux smartwatches et TVs android
Etendre ses applications aux smartwatches et TVs androidXavier Hallade
 
CGTech VERICUT 2014
CGTech VERICUT 2014CGTech VERICUT 2014
CGTech VERICUT 2014CGTech
 
FAN, Fully Automated Nagios, Paris Capitale du Libre 2008
FAN, Fully Automated Nagios, Paris Capitale du Libre 2008FAN, Fully Automated Nagios, Paris Capitale du Libre 2008
FAN, Fully Automated Nagios, Paris Capitale du Libre 2008FAN Fully Automated Nagios
 
Visual studio 2017 Launch keynote - Afterworks@Noumea
Visual studio 2017 Launch keynote - Afterworks@NoumeaVisual studio 2017 Launch keynote - Afterworks@Noumea
Visual studio 2017 Launch keynote - Afterworks@NoumeaJulien Chable
 
Le Web mobile avec ASP.Net MVC et jQuery Mobile
Le Web mobile avec ASP.Net MVC et jQuery MobileLe Web mobile avec ASP.Net MVC et jQuery Mobile
Le Web mobile avec ASP.Net MVC et jQuery MobileMicrosoft
 
Firefox OS, le web de demain - Epita - 2014-06-06
Firefox OS, le web de demain - Epita - 2014-06-06Firefox OS, le web de demain - Epita - 2014-06-06
Firefox OS, le web de demain - Epita - 2014-06-06Frédéric Harper
 
Transitions et Animations – Donnez une nouvelle dimension à vos applications ...
Transitions et Animations – Donnez une nouvelle dimension à vos applications ...Transitions et Animations – Donnez une nouvelle dimension à vos applications ...
Transitions et Animations – Donnez une nouvelle dimension à vos applications ...Microsoft
 
Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?
Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?
Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?Microsoft Technet France
 
Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?
Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?
Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?Microsoft Décideurs IT
 

Semelhante a Photos et autres sensors sur Windows Phone (20)

[FR] Capture vidéo avec HTML5
[FR] Capture vidéo avec HTML5[FR] Capture vidéo avec HTML5
[FR] Capture vidéo avec HTML5
 
Kinect en moins de 10 Minutes
Kinect en moins de 10 MinutesKinect en moins de 10 Minutes
Kinect en moins de 10 Minutes
 
Optimisation des applications Windows 8/HTML5/WinJS
Optimisation des applications Windows 8/HTML5/WinJSOptimisation des applications Windows 8/HTML5/WinJS
Optimisation des applications Windows 8/HTML5/WinJS
 
Formation logiciel Isadora TROIKATRONIX
Formation logiciel Isadora TROIKATRONIXFormation logiciel Isadora TROIKATRONIX
Formation logiciel Isadora TROIKATRONIX
 
Initiation au code : Introduction et installation des outils
Initiation au code : Introduction et installation des outilsInitiation au code : Introduction et installation des outils
Initiation au code : Introduction et installation des outils
 
Utiliser l'EDI pour développer en multiplateforme
Utiliser l'EDI pour développer en multiplateformeUtiliser l'EDI pour développer en multiplateforme
Utiliser l'EDI pour développer en multiplateforme
 
10 tips pour améliorer les performances de vos applications Windows 8
10 tips pour améliorer les performances de vos applications Windows 810 tips pour améliorer les performances de vos applications Windows 8
10 tips pour améliorer les performances de vos applications Windows 8
 
Retour d'expérience AdobeMC 2011
Retour d'expérience AdobeMC 2011Retour d'expérience AdobeMC 2011
Retour d'expérience AdobeMC 2011
 
Projet de-recherche-Tuteuré
Projet de-recherche-TuteuréProjet de-recherche-Tuteuré
Projet de-recherche-Tuteuré
 
Migrer de Windows XP à Windows 8.1 avec MDT 2013
Migrer de Windows XP à Windows 8.1 avec MDT 2013 Migrer de Windows XP à Windows 8.1 avec MDT 2013
Migrer de Windows XP à Windows 8.1 avec MDT 2013
 
Etendre ses applications aux smartwatches et TVs android
Etendre ses applications aux smartwatches et TVs androidEtendre ses applications aux smartwatches et TVs android
Etendre ses applications aux smartwatches et TVs android
 
Windows Phone 8 et la sécurité
Windows Phone 8 et la sécuritéWindows Phone 8 et la sécurité
Windows Phone 8 et la sécurité
 
CGTech VERICUT 2014
CGTech VERICUT 2014CGTech VERICUT 2014
CGTech VERICUT 2014
 
FAN, Fully Automated Nagios, Paris Capitale du Libre 2008
FAN, Fully Automated Nagios, Paris Capitale du Libre 2008FAN, Fully Automated Nagios, Paris Capitale du Libre 2008
FAN, Fully Automated Nagios, Paris Capitale du Libre 2008
 
Visual studio 2017 Launch keynote - Afterworks@Noumea
Visual studio 2017 Launch keynote - Afterworks@NoumeaVisual studio 2017 Launch keynote - Afterworks@Noumea
Visual studio 2017 Launch keynote - Afterworks@Noumea
 
Le Web mobile avec ASP.Net MVC et jQuery Mobile
Le Web mobile avec ASP.Net MVC et jQuery MobileLe Web mobile avec ASP.Net MVC et jQuery Mobile
Le Web mobile avec ASP.Net MVC et jQuery Mobile
 
Firefox OS, le web de demain - Epita - 2014-06-06
Firefox OS, le web de demain - Epita - 2014-06-06Firefox OS, le web de demain - Epita - 2014-06-06
Firefox OS, le web de demain - Epita - 2014-06-06
 
Transitions et Animations – Donnez une nouvelle dimension à vos applications ...
Transitions et Animations – Donnez une nouvelle dimension à vos applications ...Transitions et Animations – Donnez une nouvelle dimension à vos applications ...
Transitions et Animations – Donnez une nouvelle dimension à vos applications ...
 
Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?
Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?
Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?
 
Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?
Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?
Comment intégrer votre Surface Pro 3 dans votre réseau d’entreprise ?
 

Mais de Microsoft

Uwp + Xamarin : Du nouveau en terre du milieu
Uwp + Xamarin : Du nouveau en terre du milieuUwp + Xamarin : Du nouveau en terre du milieu
Uwp + Xamarin : Du nouveau en terre du milieuMicrosoft
 
La Blockchain pas à PaaS
La Blockchain pas à PaaSLa Blockchain pas à PaaS
La Blockchain pas à PaaSMicrosoft
 
Tester, Monitorer et Déployer son application mobile
Tester, Monitorer et Déployer son application mobileTester, Monitorer et Déployer son application mobile
Tester, Monitorer et Déployer son application mobileMicrosoft
 
Windows 10, un an après – Nouveautés & Démo
Windows 10, un an après – Nouveautés & Démo Windows 10, un an après – Nouveautés & Démo
Windows 10, un an après – Nouveautés & Démo Microsoft
 
Prenez votre pied avec les bots et cognitive services.
Prenez votre pied avec les bots et cognitive services.Prenez votre pied avec les bots et cognitive services.
Prenez votre pied avec les bots et cognitive services.Microsoft
 
Office 365 Dev PnP & PowerShell : exploitez enfin le potentiel de votre écosy...
Office 365 Dev PnP & PowerShell : exploitez enfin le potentiel de votre écosy...Office 365 Dev PnP & PowerShell : exploitez enfin le potentiel de votre écosy...
Office 365 Dev PnP & PowerShell : exploitez enfin le potentiel de votre écosy...Microsoft
 
Créer un bot de A à Z
Créer un bot de A à ZCréer un bot de A à Z
Créer un bot de A à ZMicrosoft
 
Microsoft Composition, pierre angulaire de vos applications ?
Microsoft Composition, pierre angulaire de vos applications ?Microsoft Composition, pierre angulaire de vos applications ?
Microsoft Composition, pierre angulaire de vos applications ?Microsoft
 
Les nouveautés SQL Server 2016
Les nouveautés SQL Server 2016Les nouveautés SQL Server 2016
Les nouveautés SQL Server 2016Microsoft
 
Conteneurs Linux ou Windows : quelles approches pour des IT agiles ?
Conteneurs Linux ou Windows : quelles approches pour des IT agiles ?Conteneurs Linux ou Windows : quelles approches pour des IT agiles ?
Conteneurs Linux ou Windows : quelles approches pour des IT agiles ?Microsoft
 
Administration et supervision depuis le Cloud avec Azure Logs Analytics
Administration et supervision depuis le Cloud avec Azure Logs AnalyticsAdministration et supervision depuis le Cloud avec Azure Logs Analytics
Administration et supervision depuis le Cloud avec Azure Logs AnalyticsMicrosoft
 
Retour d'expérience de projets Azure IoT "large scale" (MicroServices, portag...
Retour d'expérience de projets Azure IoT "large scale" (MicroServices, portag...Retour d'expérience de projets Azure IoT "large scale" (MicroServices, portag...
Retour d'expérience de projets Azure IoT "large scale" (MicroServices, portag...Microsoft
 
Plan de Reprise d'Activité avec Azure Site Recovery
Plan de Reprise d'Activité avec Azure Site RecoveryPlan de Reprise d'Activité avec Azure Site Recovery
Plan de Reprise d'Activité avec Azure Site RecoveryMicrosoft
 
Modélisation, déploiement et gestion des infrastructures Cloud : outils et bo...
Modélisation, déploiement et gestion des infrastructures Cloud : outils et bo...Modélisation, déploiement et gestion des infrastructures Cloud : outils et bo...
Modélisation, déploiement et gestion des infrastructures Cloud : outils et bo...Microsoft
 
Transformation de la représentation : De la VR à la RA, aller & retour.
Transformation de la représentation : De la VR à la RA, aller & retour.Transformation de la représentation : De la VR à la RA, aller & retour.
Transformation de la représentation : De la VR à la RA, aller & retour.Microsoft
 
Quelles architectures pour vos applications Cloud, de la VM au conteneur : ça...
Quelles architectures pour vos applications Cloud, de la VM au conteneur : ça...Quelles architectures pour vos applications Cloud, de la VM au conteneur : ça...
Quelles architectures pour vos applications Cloud, de la VM au conteneur : ça...Microsoft
 
Introduction à ASP.NET Core
Introduction à ASP.NET CoreIntroduction à ASP.NET Core
Introduction à ASP.NET CoreMicrosoft
 
Open Source et Microsoft Azure, rêve ou réalité ?
Open Source et Microsoft Azure, rêve ou réalité ?Open Source et Microsoft Azure, rêve ou réalité ?
Open Source et Microsoft Azure, rêve ou réalité ?Microsoft
 
Comment développer sur la console Xbox One avec une application Universal Win...
Comment développer sur la console Xbox One avec une application Universal Win...Comment développer sur la console Xbox One avec une application Universal Win...
Comment développer sur la console Xbox One avec une application Universal Win...Microsoft
 
Azure Service Fabric pour les développeurs
Azure Service Fabric pour les développeursAzure Service Fabric pour les développeurs
Azure Service Fabric pour les développeursMicrosoft
 

Mais de Microsoft (20)

Uwp + Xamarin : Du nouveau en terre du milieu
Uwp + Xamarin : Du nouveau en terre du milieuUwp + Xamarin : Du nouveau en terre du milieu
Uwp + Xamarin : Du nouveau en terre du milieu
 
La Blockchain pas à PaaS
La Blockchain pas à PaaSLa Blockchain pas à PaaS
La Blockchain pas à PaaS
 
Tester, Monitorer et Déployer son application mobile
Tester, Monitorer et Déployer son application mobileTester, Monitorer et Déployer son application mobile
Tester, Monitorer et Déployer son application mobile
 
Windows 10, un an après – Nouveautés & Démo
Windows 10, un an après – Nouveautés & Démo Windows 10, un an après – Nouveautés & Démo
Windows 10, un an après – Nouveautés & Démo
 
Prenez votre pied avec les bots et cognitive services.
Prenez votre pied avec les bots et cognitive services.Prenez votre pied avec les bots et cognitive services.
Prenez votre pied avec les bots et cognitive services.
 
Office 365 Dev PnP & PowerShell : exploitez enfin le potentiel de votre écosy...
Office 365 Dev PnP & PowerShell : exploitez enfin le potentiel de votre écosy...Office 365 Dev PnP & PowerShell : exploitez enfin le potentiel de votre écosy...
Office 365 Dev PnP & PowerShell : exploitez enfin le potentiel de votre écosy...
 
Créer un bot de A à Z
Créer un bot de A à ZCréer un bot de A à Z
Créer un bot de A à Z
 
Microsoft Composition, pierre angulaire de vos applications ?
Microsoft Composition, pierre angulaire de vos applications ?Microsoft Composition, pierre angulaire de vos applications ?
Microsoft Composition, pierre angulaire de vos applications ?
 
Les nouveautés SQL Server 2016
Les nouveautés SQL Server 2016Les nouveautés SQL Server 2016
Les nouveautés SQL Server 2016
 
Conteneurs Linux ou Windows : quelles approches pour des IT agiles ?
Conteneurs Linux ou Windows : quelles approches pour des IT agiles ?Conteneurs Linux ou Windows : quelles approches pour des IT agiles ?
Conteneurs Linux ou Windows : quelles approches pour des IT agiles ?
 
Administration et supervision depuis le Cloud avec Azure Logs Analytics
Administration et supervision depuis le Cloud avec Azure Logs AnalyticsAdministration et supervision depuis le Cloud avec Azure Logs Analytics
Administration et supervision depuis le Cloud avec Azure Logs Analytics
 
Retour d'expérience de projets Azure IoT "large scale" (MicroServices, portag...
Retour d'expérience de projets Azure IoT "large scale" (MicroServices, portag...Retour d'expérience de projets Azure IoT "large scale" (MicroServices, portag...
Retour d'expérience de projets Azure IoT "large scale" (MicroServices, portag...
 
Plan de Reprise d'Activité avec Azure Site Recovery
Plan de Reprise d'Activité avec Azure Site RecoveryPlan de Reprise d'Activité avec Azure Site Recovery
Plan de Reprise d'Activité avec Azure Site Recovery
 
Modélisation, déploiement et gestion des infrastructures Cloud : outils et bo...
Modélisation, déploiement et gestion des infrastructures Cloud : outils et bo...Modélisation, déploiement et gestion des infrastructures Cloud : outils et bo...
Modélisation, déploiement et gestion des infrastructures Cloud : outils et bo...
 
Transformation de la représentation : De la VR à la RA, aller & retour.
Transformation de la représentation : De la VR à la RA, aller & retour.Transformation de la représentation : De la VR à la RA, aller & retour.
Transformation de la représentation : De la VR à la RA, aller & retour.
 
Quelles architectures pour vos applications Cloud, de la VM au conteneur : ça...
Quelles architectures pour vos applications Cloud, de la VM au conteneur : ça...Quelles architectures pour vos applications Cloud, de la VM au conteneur : ça...
Quelles architectures pour vos applications Cloud, de la VM au conteneur : ça...
 
Introduction à ASP.NET Core
Introduction à ASP.NET CoreIntroduction à ASP.NET Core
Introduction à ASP.NET Core
 
Open Source et Microsoft Azure, rêve ou réalité ?
Open Source et Microsoft Azure, rêve ou réalité ?Open Source et Microsoft Azure, rêve ou réalité ?
Open Source et Microsoft Azure, rêve ou réalité ?
 
Comment développer sur la console Xbox One avec une application Universal Win...
Comment développer sur la console Xbox One avec une application Universal Win...Comment développer sur la console Xbox One avec une application Universal Win...
Comment développer sur la console Xbox One avec une application Universal Win...
 
Azure Service Fabric pour les développeurs
Azure Service Fabric pour les développeursAzure Service Fabric pour les développeurs
Azure Service Fabric pour les développeurs
 

Photos et autres sensors sur Windows Phone

  • 2. Photos et autres Sensors sur Windows Phone Nicolas CALVI Consultant / Formateur MVP Hardware Interaction Design & Development Wygwam Nicolas DELABARRE Relations techniques développeurs Code/Developpement Code/developpement Nokia Internal Use Only
  • 3. Donnez votre avis ! Depuis votre smartphone sur : http://notes.mstechdays.fr De nombreux lots à gagner toute les heures !!! Claviers, souris et jeux Microsoft… Merci de nous aider à améliorer les Techdays ! #mstechdays Code/developpement Nokia Internal Use Only
  • 4. WINDOWS PHONE Un téléphone plein de ressources #mstechdays Code/developpement Nokia Internal Use Only
  • 5. Qu’est-ce que Windows Phone ? Un OS créer par Microsoft à destination des Constructeurs de SmartPhone. Une expérience unique grâce a Modern UI Des usages multiples • • Grand public Entreprise #mstechdays Code/developpement Nokia Internal Use Only
  • 6. Qu’est-ce que Windows Phone ? Un concentré de technologie - Caméra jusqu’à 41 MP - Flash - GPS - Accéléromètre - Baromètre (Altimètre) - Gyroscope - Wifi, Bluetooth, 4G - NFC - Magnétomètre (Boussole) - Capteur de lumière ambiant - Capteur de proximité -… #mstechdays Code/developpement Nokia Internal Use Only
  • 7. Qu’allons nous aborder ? Les senseurs Non accessible - Caméra > Vidéo > Photo - Accéléromètre - Compas - GPS - Gyroscope - Inclinomètre - Motion API - Capteur de proximité - Capteur de luminosité On finira par de la Réalité Augmentée avec GART Le capteur NFC ne sera pas traiter dans cette session #mstechdays Code/developpement Nokia Internal Use Only
  • 8. SENSEUR : LA CAMÉRA Il sait voir au-delà de votre perception #mstechdays Code/developpement Nokia Internal Use Only
  • 9. Comment afficher le flux vidéo ? // Le namespace using System.Windows.Media; // Création du device de capture vidéo CaptureSource captureSource = new CaptureSource(); VideoCaptureDevice device = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); // On vérifie si la capture est possible if (device != null) { // On crée un Brush pour afficher la vidéo dans notre UI VideoBrush videoBrush = new VideoBrush(); videoBrush.SetSource(captureSource); VideoRect.Fill = videoBrush; // Rectangle dans notre XAML // On démarre la préview Vidéo captureSource.Start(); } #mstechdays Code/developpement Nokia Internal Use Only
  • 10. Comment afficher le flux vidéo ? Ne pas oublier de fermer la camera video ! protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { if (captureSource != null) captureSource.Stop(); base.OnNavigatingFrom(e); } #mstechdays Code/developpement Nokia Internal Use Only
  • 11. Comment prendre une photo ? // On vérifie si la caméra est disponible if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) || (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true)) { PhotoCamera photoCamera; // Initialise la caméra en fonction des capacitées trouvées if (PhotoCamera.IsCameraTypeSupported(CameraType.Primary)) photoCamera = new PhotoCamera(CameraType.Primary); else photoCamera = new PhotoCamera(CameraType.FrontFacing); // On se branche sur les événements photoCamera.Initialized += OnPhotoCameraInitialized; photoCamera.CaptureCompleted += OnPhotoCameraCaptureCompleted; photoCamera.CaptureImageAvailable += OnPhotoCameraCaptureImageAvailable; photoCamera.CaptureThumbnailAvailable += OnPhotoCameraCaptureThumbnailAvailable; // Création d'un Brush pour afficher le buffer dans notre UI VideoBrush photoBrush = new VideoBrush(); photoBrush.SetSource(photoCamera); // Affectation du Brush a notre zone de rendu PhotoRect.Fill = photoBrush; // Rectangle dans notre XAML } #mstechdays Code/developpement Nokia Internal Use Only
  • 12. Comment prendre une photo ? // Déclenche la prise de photo photoCamera.CaptureImage(); OnPhotoCameraCaptureImageAvailable OnPhotoCameraCaptureCompleted OnPhotoCameraCaptureThumbnailAvailable #mstechdays Code/developpement Nokia Internal Use Only
  • 13. Comment prendre une photo ? // On sauvegarde la photo dans la média MediaLibrary librarylibrary = new MediaLibrary(); library.SavePictureToCameraRoll("MonFichier.jpg", e.ImageStream); // On se repositionne au début du flux de l'image e.ImageStream.Seek(0, SeekOrigin.Begin); // Enregistrement de la photo en JPEG dans le répertoire local using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write)) { // Initialisation du buffer (4ko) byte[] readBuffer = new byte[4096]; int bytesRead = -1; // On copie l'image dans le répertoire local while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0) targetStream.Write(readBuffer, 0, bytesRead); } } // On ferme le fichier e.ImageStream.Close(); #mstechdays Code/developpement Nokia Internal Use Only
  • 14. Comment prendre une photo ? Ne pas oublier de fermer la camera photo ! protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { if (photoCamera != null) { photoCamera.Initialized -= OnPhotoCameraInitialized; photoCamera.CaptureCompleted -= OnPhotoCameraCaptureCompleted; photoCamera.CaptureImageAvailable -= OnPhotoCameraCaptureImageAvailable; photoCamera.CaptureThumbnailAvailable -= OnPhotoCameraCaptureThumbnailAvailable; photoCamera.Dispose(); } base.OnNavigatingFrom(e); } #mstechdays Code/developpement Nokia Internal Use Only
  • 15. Prise de photo haute résolution Lumia 1020 7712 x 4352 (16:9) 7136 x 5360 (4:3) Lumia 1520 5376 x 3024 (16:9) 4992 x 3744 (4:3) #mstechdays Code/developpement Nokia Internal Use Only
  • 16. NOKIA IMAGING SDK 1.0 Allez plus loin avec ses photos #mstechdays Code/developpement Nokia Internal Use Only
  • 17. Qu’est-ce que le SDK Nokia Imaging ? • Librairie native Windows Phone 8, accessible depuis des projets WP8 C#, VB et C++ • Inclus plus de 50 filtres de traitement d’images et effets visuels paramétrables • Ne nécessite aucune connaissance particulière en traitement algorithmique d’images • Décodage JPEG partiel – basée sur la technologie RAJPEG, afin d’accéder aux données sans décoder toute l’image JPEG : • Prévisualisation rapide • Application d’effets, tels que la rotation ou le cropping d’images haute résolution #mstechdays Code/developpement Nokia Internal Use Only
  • 18. Liste de filtres et effets (1/3) #mstechdays Code/developpement Nokia Internal Use Only
  • 19. Liste de filtres et effets (2/3) #mstechdays Code/developpement Nokia Internal Use Only
  • 20. Liste de filtres et effets (3/3) #mstechdays Code/developpement Nokia Internal Use Only
  • 22. Architecture générale • Cette librairie est architecturée en 3 blocs : • Image sources (e.g. bitmaps, streams, files) • Effect (e.g. 50+ filtres) • Renderers (outputs bitmaps or files) • En combinant ces blocs, on va créer un tunnel de traitement d’image ( ou “rendering pipeline”) • Une fois le tunnel créé, il est possible de modifier les paramètres de filtres ou leur #mstechdays Code/developpement séquencement. Nokia Internal Use Only Image Source Filter Effects MagicPen Filter Filter Flip Rotation Filter Renderer
  • 24. Comment appliquer un filtre à une photo ? // Création d'un nokia stream à partir d'un IO Stream using(var source = new StreamImageSource(e.ChosenPhoto)) // Création d'un effet initial à partir de la source stream nokia using (var effect = new FilterEffect(source)) // Instanciation d'un render de type "WriteableBitmap" using( var render = new WriteableBitmapRenderer(effect, _writeableBitmapTarget)) { // Création de la liste des filtres var filters = new List<IFilter>(); filters.Add(new MagicPenFilter()); // Affectation de la liste de filtres à notre objet "effet" effect.Filters = filters; // Exécution du rendu await render.RenderAsync(); // Force le repaint de l'image résultante _writeableBitmapTarget.Invalidate(); } #mstechdays Code/developpement Nokia Internal Use Only
  • 25. Et plusieurs filtres ? // Création d'un nokia stream à partir d'un IO Stream using( var source = new StreamImageSource(e.ChosenPhoto)) // Création d'un effet initial à partir de la source stream nokia using( var effect = new FilterEffect(source)) // Instanciation d'un render de type "WriteableBitmap" using( var render = new WriteableBitmapRenderer(effect, _writeableBitmapTarget)) { // Création de la liste des filtres var filters = new List<IFilter>(); filters.Add(new MagicPenFilter()); filters.Add(new RotationFilter(15)); // Affectation de la liste de filtres à notre objet "effet" effect.Filters = filters; // Exécution du rendu await render.RenderAsync(); // Force le repaint de l'image résultante _writeableBitmapTarget.Invalidate(); } #mstechdays Code/developpement Nokia Internal Use Only
  • 26. Modifier les paramètres de filtre Les paramètres peuvent être changés sans reconstruire le tunnel de traitement. • Néanmoins il faut garder à l’esprit : • Que le rendu est asynchrone, les paramètres ne peuvent pas être changés en cours. • Attention avec certains contrôles UI (e.g. sliders) qui peuvent générer des événements n’importe quand ! • Astuce : utiliser une file d’attente d’événements de type Queue<Action>. #mstechdays Code/developpement Nokia Internal Use Only
  • 27. Modifier les paramètres de filtre UI (Slider) Imaging SDK ValueChanged event Rendering a new preview ValueChanged event ValueChanged event #mstechdays Code/developpement Nokia Internal Use Only Rendering a new preview
  • 28. Modifier les paramètres de filtre Définir une queue d’attente: Queue<System.Action> _toDo = new Queue<System.Action>(); Quand la ressource est occupée, empiler l’action dans la queue d’attente: _toDo.Enqueue( () => { _warpFilter.Level = newValue; } ); Lambda expression directement mise en queue Quand la ressource est dispo, traitement des actions en attente : while (_toDo.Count > 0) { Action action = _toDo.Dequeue(); action(); } await _renderer.RenderAsync(); #mstechdays Exécution des lambda expression Code/developpement Nokia Internal Use Only
  • 29. Image Source Type de source Class ImageSource Name Stream System.IO.Stream StreamImageSource Image Bitmap Windows.Media.Imaging.WriteableBitmap BitmapImageSource Nokia.Graphics.Imaging.Bitmap Windows Buffer Windows.Storage.Streams.IBuffer BufferImageSource Camera Windows.Phone.Media.Capture. ICameraCaptureDevice CameraPreviewImageSource Flat Color Windows.Ui.Color ColorImageSource File Windows.Storage.IStorageFile StorageFileImageSource Random Access Stream Windows.Storage.Streams. IRandomAccessStream RandomAccessStreamImage Source #mstechdays Code/developpement Nokia Internal Use Only Image Source Filter Effects MagicPen Filter Filter Flip Rotation Filter Renderer
  • 30. Renderer Image Source Type de Destination Class ImageSource Name Imaging SDK Bitmap Nokia.Graphics.Imaging.Bitmap BitmapRenderer Writeable Bitmaps (XAML Image ) WriteableBitmap WriteableBitmapRenderer JPEG Windows.Storage.Streams.IBuffer Filter Effects JpegRenderer MagicPen Filter Filter Flip Rotation Filter Renderer #mstechdays Code/developpement Nokia Internal Use Only
  • 31. Implémentation de filtre personnalisé // Création d'un effet personnalisé public class MyCustomFilter : CustomEffectBase { public MyCustomFilter(IImageProvider source): base(source) { } protected override void OnProcess(PixelRegion sourcePixelRegion, PixelRegion targetPixelRegion) { sourcePixelRegion.ForEachRow((index, width, pos) => { for (int i = 0; i < width; ++i, ++index) { Windows.UI.Color c = ToColor(sourcePixelRegion.ImagePixels[index]); c.R = (byte)Math.Min(255, c.R * 2); c.G = (byte)Math.Min(255, c.G * 2); c.B = (byte)Math.Min(255, c.B * 2); targetPixelRegion.ImagePixels[index] = FromColor(c); } }); } } #mstechdays Code/developpement Nokia Internal Use Only
  • 32. APIs pour créer des images sources de type gradients • Facilité d’utilisation • Faible empreinte mémoire Radial Gradient #mstechdays Linear Gradient Code/developpement Nokia Internal Use Only
  • 33. Création d’image source gradient // Affectation de la source de notre Image XAML avec un writeable bitmap imageTarget.Source = _writeableBitmapTarget; // Création d'un gradient de couleur de type "radial" var rad = new RadialGradient(new Windows.Foundation.Point(0.5, 0.5), new EllipseRadius(0.3, 0.3)); rad.Stops = new GradientStop[] { new GradientStop() { Color = Windows.UI.Color.FromArgb(255, 255, 0, 0), Offset = 0 }, new GradientStop() { Color = Windows.UI.Color.FromArgb(255, 0, 255, 0), Offset = 1 } }; // Création d'une image source de type gradient à partir du gradient using (var grad = new GradientImageSource( new Windows.Foundation.Size(imageTarget.Width, imageTarget.Height), rad)) { // Instantiation d'un render de type "WriteableBitmap" initialisé avec notre gradient // source et le writeable bitmap de sortie var render = new WriteableBitmapRenderer(grad, _writeableBitmapTarget); // Exécution du rendu await render.RenderAsync(); } #mstechdays Code/developpement Nokia Internal Use Only
  • 34. Blend modes 1ère image Blend mode: Color Burn #mstechdays Blend mode: Color Code/developpement Nokia Internal Use Only 2nde image Blend mode: Add
  • 35. Blend d’une photo avec un gradient // Affectation de la source de notre Image XAML avec un writeable bitmap imageTarget.Source = _writeableBitmapTarget; // Création d'un nokia stream à partir d'un IO Stream using (var backgroundSource = new StreamImageSource(e.ChosenPhoto)) // Création d'une image source de type gradient à partir du gradient using(var foregroundSource = new GradientImageSource( ...)) // Création d'un filtre d'effet sourcé avec l'image choisie par l'utilisateur using(var filterEffect = new FilterEffect(backgroundSource)) // Création d'un filtre de blending sourcé avec l'image source gradient using(var blendFilter = new BlendFilter(foregroundSource)) // Instantiation d'un render de type "WriteableBitmap" initialisé avec notre filtre d'effet et le bitmap de sortie using(var renderer = new WriteableBitmapRenderer(filterEffect, _writeableBitmapTarget)) { // Configuration de notre filtre d'effet avec un seul effet ... notre effet blend blendFilter.BlendFunction = BlendFunction.Color; filterEffect.Filters = new IFilter[] { blendFilter }; // Exécution du rendu await renderer.RenderAsync(); // Force le repaint de l'image resultante _writeableBitmapTarget.Invalidate(); } #mstechdays Code/developpement Nokia Internal Use Only
  • 37. Pour aller plus loin Point d’entrée des ressources techniques relative au SDK Imaging : http://developer.nokia.com/resources/library/Lumia/nokia-imaging-sdk.html Projets d’exemples basés sur le SDK Imaging (avec code source) : http://developer.nokia.com/resources/library/Lumia/nokia-imagingsdk/sample-projects.html Forum de discussion dédié au SDK Imaging : http://developer.nokia.com/community/discussion Articles Wiki : http://developer.nokia.com/community/wiki/Portal:Windows_Phone_Multi media #mstechdays Code/developpement Nokia Internal Use Only
  • 38. SENSEUR : ACCELEROMETRE Une bonne raison de bouger utile #mstechdays Code/developpement Nokia Internal Use Only
  • 39. Qu’est-ce que c’est ? Un accéléromètre est un capteur qui, fixé à un mobile ou tout autre objet, permet de mesurer l’accélération linéaire de ce dernier. On parle encore d'accéléromètre même s'il s'agit en fait de 3 accéléromètres qui calculent les 3 accélérations linéaires selon 3 axes orthogonaux. Source Wikipédia : http://fr.wikipedia.org/wiki/Acc%C3%A9l%C3%A9rom%C3%A8tre #mstechdays Code/developpement Nokia Internal Use Only
  • 40. API spécifique Windows Phone 8 // Le namespace using Microsoft.Devices.Sensors; // Comment savoir si le téléphone supporte cette fonctionnalité if (!Accelerometer.IsSupported) return; // Comment l’instancier accelerometer = new Accelerometer(); accelerometer.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20); // Comment récupérer l’information accelerometer.CurrentValueChanged += OnAccelerometerCurrentValueChanged; // Comment le démarrer accelerometer.Start(); #mstechdays Code/developpement Nokia Internal Use Only
  • 41. API spécifique Windows Phone 8 private void OnAccelerometerCurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> args) { AccelerometerReading reading = args.SensorReading; this.Dispatcher.BeginInvoke(() => { TxtTimestamp.Text = reading.Timestamp.ToString(); TxtAccelerationX.Text = reading.Acceleration.X.ToString(); TxtAccelerationY.Text = reading.Acceleration.Y.ToString(); TxtAccelerationZ.Text = reading.Acceleration.Z.ToString(); }); } #mstechdays Code/developpement Nokia Internal Use Only
  • 42. API spécifique Windows Phone 8 Ne pas oublier de fermer le senseur ! protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { if (accelerometer != null) accelerometer.Stop(); base.OnNavigatingFrom(e); } #mstechdays Code/developpement Nokia Internal Use Only
  • 43. API partagées avec Windows 8 // Le namespace using Windows.Devices.Sensors; // Comment l’instancier accelerometer = Accelerometer.GetDefault(); // Comment savoir si le téléphone supporte cette fonctionnalité if (accelerometer != NULL) return; // Comment récupérer l’information accelerometer.ReadingChanged += OnAccelerometerReadingChanged; #mstechdays Code/developpement Nokia Internal Use Only
  • 44. API partagées avec Windows 8 private void OnAccelerometerReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args) { AccelerometerReading reading = args.SensorReading; this.Dispatcher.BeginInvoke(() => { TxtTimestamp.Text = reading.Timestamp.ToString(); TxtAccelerationX.Text = reading.Acceleration.X.ToString("0.00"); TxtAccelerationY.Text = reading.Acceleration.Y.ToString("0.00"); TxtAccelerationZ.Text = reading.Acceleration.Z.ToString("0.00"); } } #mstechdays Code/developpement Nokia Internal Use Only
  • 45. SENSEUR : COMPAS Pour que tout cela est un sens #mstechdays Code/developpement Nokia Internal Use Only
  • 46. Qu’est-ce que c’est ? le compas magnétique, dont le principe de fonctionnement est, comme une boussole, l'orientation d'une aiguille aimantée dans le champ du magnétisme terrestre. Source Wikipédia : http://fr.wikipedia.org/wiki/Compas_(navigation) #mstechdays Code/developpement Nokia Internal Use Only
  • 47. API spécifique Windows Phone 8 // Le namespace using Microsoft.Devices.Sensors; // Comment savoir si le téléphone supporte cette fonctionnalité if (!Compass.IsSupported) return; // Comment l’instancier compass = new Compass(); compass.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20); // Comment récupérer l’information compass.CurrentValueChanged += OnCompassCurrentValueChanged; compass.Calibrate += OnCompassCalibrate; // Comment le démarrer compass.Start(); #mstechdays Code/developpement Nokia Internal Use Only
  • 48. API spécifique Windows Phone 8 private void OnCompassCurrentValueChanged(object sender, SensorReadingEventArgs<CompassReading> args) { CompassReading reading = args.SensorReading; this.Dispatcher.BeginInvoke(() => { TxtTimestamp.Text = reading.Timestamp.ToString(); TxtMagneticHeading.Text = reading.MagneticHeading.ToString(); TxtTrueHeading.Text = reading.TrueHeading.ToString(); TxtAccuracy.Text = reading.HeadingAccuracy.ToString(); }); } #mstechdays Code/developpement Nokia Internal Use Only
  • 49. API spécifique Windows Phone 8 private void OnCompassCalibrate(object sender, CalibrationEventArgs args) { // Mettre votre code ici // Le compas a besoin d’être calibré } #mstechdays Code/developpement Nokia Internal Use Only
  • 50. API spécifique Windows Phone 8 Pour calibrer le compas, si la propriété « Accuracy » est supérieure à 15, il faut faire des « 8 » avec le téléphone. Ceci peut-être gérer dans l’interface, en affichant un texte d’aide invitant l’utilisateur a faire les « 8 ». Dès que la valeur descend en dessous de 15, on peut notifier l’utilisateur que le compas est calibré. #mstechdays Code/developpement Nokia Internal Use Only
  • 51. API spécifique Windows Phone 8 Ne pas oublier de fermer le senseur ! protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { if (compass != null) compass.Stop(); base.OnNavigatingFrom(e); } #mstechdays Code/developpement Nokia Internal Use Only
  • 52. API partagées avec Windows 8 // Le namespace using Windows.Devices.Sensors; // Comment l’instancier compass = Compass.GetDefault(); // Comment savoir si le téléphone supporte cette fonctionnalité if (compass != NULL) return; // Comment récupérer l’information compass.ReadingChanged += OnCompassReadingChanged; #mstechdays Code/developpement Nokia Internal Use Only
  • 53. API partagées avec Windows 8 private void OnCompassReadingChanged(Compass sender, CompassReadingChangedEventArgs args) { CompassReading reading = args.SensorReading; this.Dispatcher.BeginInvoke(() => { CompassTime.Text = reading.Timestamp.ToString(); CompassMagneticHeading.Text = reading.HeadingMagneticNorth.ToString(); CompassTrueHeading.Text = reading.HeadingTrueNorth.Value.ToString(); } } #mstechdays Code/developpement Nokia Internal Use Only
  • 54. SENSEUR : GPS Si vous n’avez pas le sens de l’orientation mieux vaut le consulter #mstechdays Code/developpement Nokia Internal Use Only
  • 55. Qu’est-ce que c’est ? Le Global Positioning System (GPS) – que l'on peut traduire en français par « système de localisation mondial » – est un système de géolocalisation fonctionnant au niveau mondial. Source Wikipédia : http://fr.wikipedia.org/wiki/Global_Positioning_System #mstechdays Code/developpement Nokia Internal Use Only
  • 56. API spécifique Windows Phone 8 // Le namespace using System.Device.Location; // Comment l’instancier gps = new GeoCoordinateWatcher(GeoPositionAccuracy.High); // Ou Default gps.MovementThreshold = 0; // Comment récupérer l’information gps.PositionChanged += OnGeoCoordinateWatcherPositionChanged; gps.StatusChanged += OnGeoCoordinateWatcherStatusChanged; // Comment le démarrer gps.Start(); #mstechdays Code/developpement Nokia Internal Use Only
  • 57. API spécifique Windows Phone 8 private void OnGeoCoordinateWatcherStatusChanged(object sender, GeoPositionStatusChangedEventArgs args) { this.Dispatcher.BeginInvoke(() => { GPSManualStatus.Text = e.Status.ToString(); }); } // Les valeurs de Status GeoPositionStatus.Disabled .Initializing .NoData .Ready #mstechdays Code/developpement Nokia Internal Use Only
  • 58. API spécifique Windows Phone 8 private void OnGeoCoordinateWatcherPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> args) { this.Dispatcher.BeginInvoke(() => { GPSTime.Text = e.Position.Timestamp.ToString(); GPSLatitude.Text = e.Position.Location.Latitude.ToString(); GPSLongitude.Text = e.Position.Location.Longitude.ToString(); GPSAltitude.Text = e.Position.Location.Altitude.ToString(); GPSHAccuracy.Text = e.Position.Location.HorizontalAccuracy.ToString(); GPSVAccuracy.Text = e.Position.Location.VerticalAccuracy.ToString(); GPSCourse.Text = e.Position.Location.Course.ToString(); GPSSpeed.Text = e.Position.Location.Speed.ToString(); GPSUnknown.Text = e.Position.Location.IsUnknown.ToString(); }); } #mstechdays Code/developpement Nokia Internal Use Only
  • 59. API spécifique Windows Phone 8 Ne pas oublier de fermer le senseur ! protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { if (gps != null) gps.Stop(); base.OnNavigatingFrom(e); } #mstechdays Code/developpement Nokia Internal Use Only
  • 60. API partagées avec Windows 8 // Le namespace using Windows.Devices.Geolocation; // Comment l’instancier gps = new Geolocator(); gps.DesiredAccuracy = PositionAccuracy.High; // Ou Default gps.DesiredAccuracyInMeters = 10; // En dessous de 10m ce n’est pas possible gps.MovementThreshold = 0; gps.ReportInterval = 1000; // Le GPS a un taux de rafraichissement d’1Hz // Comment récupérer l’information gps.PositionChanged += OnGeolocatorPositionChanged; gps.StatusChanged += OnGeolocatorStatusChanged; #mstechdays Code/developpement Nokia Internal Use Only
  • 61. API spécifique Windows Phone 8 private void OnGeolocatorStatusChanged(Geolocator sender, StatusChangedEventArgs args) { this.Dispatcher.BeginInvoke(() => { GPSManualStatus.Text = e.Status.ToString(); }); } // Les valeurs de Status PositionStatus.Disabled .Initializing .NoData .NotAvailable .NotInitialized .Ready #mstechdays Code/developpement Nokia Internal Use Only
  • 62. API spécifique Windows Phone 8 private void OnGeolocatorPositionChanged (Geolocator sender, PositionChangedEventArgs args) { this.Dispatcher.BeginInvoke(() => { GPSTime.Text = args.Position.Coordinate.Timestamp.ToString(); GPSLatitude.Text = args.Position.Coordinate.Latitude.ToString(); GPSLongitude.Text = args.Position.Coordinate.Longitude.ToString(); GPSAltitude.Text = args.Position.Coordinate.Altitude.ToString(); GPSAltitudeAccuracy.Text = args.Position.Coordinate.AltitudeAccuracy.ToString(); GPSAccuracy.Text = args.Position.Coordinate.Accuracy.ToString(); GPSSpeed.Text = args.Position.Coordinate.Speed.ToString(); } } #mstechdays Code/developpement Nokia Internal Use Only
  • 63. SENSEUR : GYROSCOPE Il ne vous fera pas tourner en bourrique celui là #mstechdays Code/developpement Nokia Internal Use Only
  • 64. Qu’est-ce que c’est ? Un gyroscope (du grec « qui observe la rotation ») est un appareil qui exploite le principe de la conservation du moment angulaire en physique (ou encore stabilité gyroscopique ou effet gyroscopique). Cette loi fondamentale de la mécanique veut qu'en l'absence de couple appliqué à un solide en rotation, celui-ci conserve son axe de rotation invariable Source Wikipédia : http://fr.wikipedia.org/wiki/Gyroscope #mstechdays Code/developpement Nokia Internal Use Only
  • 65. API spécifique Windows Phone 8 // Le namespace using Microsoft.Devices.Sensors; // Comment savoir si le téléphone supporte cette fonctionnalité if (!Gyroscope.IsSupported) return; // Comment l’instancier gyroscope = new Gyroscope(); gyroscope.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20); // Comment récupérer l’information gyroscope.CurrentValueChanged += OnGyroscopeCurrentValueChanged; // Comment le démarrer gyroscope.Start(); #mstechdays Code/developpement Nokia Internal Use Only
  • 66. API spécifique Windows Phone 8 private void OnGyroscopeCurrentValueChanged(object sender, SensorReadingEventArgs<GyroscopeReading> args) { GyroscopeReading reading = args.SensorReading; this.Dispatcher.BeginInvoke(() => { TxtTimestamp.Text = reading.Timestamp.ToString(); TxtRotationX.Text = reading.RotationRate.X.ToString(); TxtRotationY.Text = reading.RotationRate.Y.ToString(); TxtRotationZ.Text = reading.RotationRate.Z.ToString(); } } #mstechdays Code/developpement Nokia Internal Use Only
  • 67. API spécifique Windows Phone 8 Ne pas oublier de fermer le senseur ! protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { if (gyroscope != null) gyroscope.Stop(); base.OnNavigatingFrom(e); } #mstechdays Code/developpement Nokia Internal Use Only
  • 68. API partagées avec Windows 8 // Le namespace using Windows.Devices.Sensors; // Comment l’instancier gyroscope = Gyrometer.GetDefault(); // Comment savoir si le téléphone supporte cette fonctionnalité if (gyroscope != NULL) return; // Comment récupérer l’information gyroscope.ReadingChanged += OnGyroscopeReadingChanged; #mstechdays Code/developpement Nokia Internal Use Only
  • 69. API partagées avec Windows 8 private void OnGyroscopeReadingChanged (Gyrometer sender, GyrometerReadingChangedEventArgs args) { GyrometerReading reading = args.SensorReading; this.Dispatcher.BeginInvoke(() => { TxtTimestamp.Text = reading.Timestamp.ToString(); TxtRotationX.Text = reading.AngularVelocityX.ToString("0.00"); TxtRotationY.Text = reading.AngularVelocityY.ToString("0.00"); TxtRotationZ.Text = reading.AngularVelocityZ.ToString("0.00"); } } #mstechdays Code/developpement Nokia Internal Use Only
  • 70. SENSEUR : INCLINOMÈTRE Tel le bambou, il sait plier. #mstechdays Code/developpement Nokia Internal Use Only
  • 71. Qu’est-ce que c’est ? Un inclinomètre (ou clinomètre) est un capteur servant à mesurer des angles par rapport à la ligne d'horizon (ou horizontale). Là où le niveau à bulle (ou niveau) permet de détecter précisément où se situe l'horizontale, l'inclinomètre détermine en plus l'angle d'inclinaison par rapport à cette horizontale. Source Wikipédia : http://fr.wikipedia.org/wiki/Inclinom%C3%A8tre #mstechdays Code/developpement Nokia Internal Use Only
  • 72. API partagées avec Windows 8 // Le namespace using Windows.Devices.Sensors; // Comment l’instancier inclinometer = Inclinometer.GetDefault(); // Comment savoir si le téléphone supporte cette fonctionnalité if (inclinometer!= NULL) return; // Comment récupérer l’information inclinometer.ReadingChanged += OnInclinometerReadingChanged; #mstechdays Code/developpement Nokia Internal Use Only
  • 73. API partagées avec Windows 8 private void OnInclinometerReadingChanged (Inclinometer sender, InclinometerReadingChangedEventArgs args) { InclinometerReading reading = args.SensorReading; this.Dispatcher.BeginInvoke(() => { TxtTimestamp.Text = reading.Timestamp.ToString(); TxtPitch.Text = reading.PitchDegrees.ToString("0.00"); TxtRoll.Text = reading.RollDegrees.ToString("0.00"); TxtYaw.Text = reading.YawDegrees.ToString("0.00"); } } #mstechdays Code/developpement Nokia Internal Use Only
  • 74. MOTION API Avoir tous ses sens en éveils #mstechdays Code/developpement Nokia Internal Use Only
  • 75. Qu’est-ce que c’est ? Vous pouvez utiliser la « Motion API » pour créer des applications Windows Phone qui utilisent l'orientation et le mouvement de l'appareil dans l'espace comme un mécanisme d'entrée. La plate-forme Windows Phone inclut des APIs pour obtenir des données brutes du capteur de la boussole de l'appareil, gyroscope, accéléromètre et des capteurs. Cependant la « Motion API » gère le calcul complexe nécessaire pour combiner les données de ces capteurs et produire des valeurs facile à utiliser pour l'attitude et le mouvement de l'appareil. #mstechdays Code/developpement Nokia Internal Use Only
  • 76. Comment ça marche ? // Le namespace using Microsoft.Devices.Sensors; // Comment savoir si le téléphone supporte cette fonctionnalité if (!Motion.IsSupported) return; // Comment l’instancier motion = new Motion(); motion.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20); // Comment récupérer l’information motion.CurrentValueChanged += OnMotionCurrentValueChanged; // Comment le démarrer motion.Start(); #mstechdays Code/developpement Nokia Internal Use Only
  • 77. Comment ça marche ? private void OnGyroscopeCurrentValueChanged(object sender, SensorReadingEventArgs<MotionReading> args) { MotionReading reading = args.SensorReading; this.Dispatcher.BeginInvoke(() => { TxtTimestamp.Text = reading.Timestamp.ToString(); TxtPitch.Text = reading.Attitude.Pitch.ToString(); // En radian TxtRoll.Text = reading.Attitude.Roll.ToString(); // En radian TxtYaw.Text = reading.Attitude.Yaw.ToString(); // En radian TxtAccellerationX.Text = reading.DeviceAcceleration.X.ToString(); TxtAccellerationY.Text = reading.DeviceAcceleration.Y.ToString(); TxtAccellerationZ.Text = reading.DeviceAcceleration.Z.ToString(); } } #mstechdays Code/developpement Nokia Internal Use Only
  • 78. Connaître l’attitude La « Motion API » permet de connaître l’orientation du téléphone dans un espace 3D. Dans les informations retournées, on peut récupérer le Quaternion et la matrice de rotation de cette attitude. MotionReading reading = args.SensorReading; // Récupération du Quaternion reading.Quaternion; // Récupération de la matrice de rotation reading.RotationMatrix; #mstechdays Code/developpement Nokia Internal Use Only
  • 79. REALITE AUGMENTEE : GART Regarder le monde sous un nouveau jour, n’est-ce pas Wayne ? #mstechdays Code/developpement Nokia Internal Use Only
  • 80. Qu’est-ce que GART ? Un SDK Open Source développer par un employé de Microsoft. Permet de faire de la réalité augmentée Géo localisée. Disponible à cette adresse : http://gart.codeplex.com/ #mstechdays Compatible : - Windows Phone 7 et 8 - Windows 8 et 8.1 Code/developpement Nokia Internal Use Only
  • 81. NOKIA JOB HUB Application Pilote Windows Phone réalisée avec GART #mstechdays Code/developpement Nokia Internal Use Only
  • 83. Comment ça marche ? <phone:PhoneApplicationPage xmlns:gart="clr-namespace:GART.Controls;assembly=GART.WP8"> <Grid> <gart:ARDisplay x:Name="ARDisplay" AttitudeRefreshRate="50" MovementThreshold="10"> <gart:VideoPreview /> <gart:WorldView FarClippingPlane="300.0" MaxItemScale="1.0" MinItemScale="0.1" NearClippingPlane="1.0"> <gart:WorldView.ItemTemplate> <DataTemplate> <Border Background="White" BorderBrush="Green" BorderThickness="1" Padding="5"> <TextBlock FontSize="20" Foreground="Black" Text="{Binding Content}" /> </Border> </DataTemplate> </gart:WorldView.ItemTemplate> </gart:WorldView> </gart:ARDisplay> </Grid> #mstechdays Code/developpement Nokia Internal Use Only
  • 84. Comment ça marche ? // On crée une liste de point a afficher items = new ObservableCollection<ARItem>(); // Création d’un élément a afficher // Mettre ici des éléments valide en coordonnée pour les voir apparaitre // Pour trouver des coordonnées, allez sur Bing Maps ARItem point = new ARItem(); point.Content = "Un objet a afficher"; point.GeoLocation = new System.Device.Location.GeoCoordinate(48.821229, 2.254397, 0); items.Add(point); // On affecte la source this.ARDisplay.ARItems = items; #mstechdays Code/developpement Nokia Internal Use Only
  • 85. Comment ça marche ? protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e) { this.ARDisplay.StopServices(); base.OnNavigatedFrom(e); } protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { this.ARDisplay.StartServices(); base.OnNavigatedTo(e); } #mstechdays Code/developpement Nokia Internal Use Only
  • 86. DES QUESTIONS ? N’hésitez pas on sera ravi de vous répondre. #mstechdays Code/developpement Nokia Internal Use Only
  • 87. Restez en contact Nicolas Calvi Blog > blog.nicolascalvi.com Twitter > @nicolascalvi Page Facebook > Black Blog Nicolas Delabarre Blog > www.nokiadevblog.fr Twitter > @NokiaDev_France Page Facebook > NokiaDevFrance Code source : http://sdrv.ms/1coyrnH #mstechdays Code/developpement Nokia Internal Use Only

Notas do Editor

  1. Image source: Utilisé en début de traitement, cette source fournit l’image originale générée ou créée depuis un stockage .Toutes les sources d’image implémentent l’interface IImageProvider.Effect: Prends une ou plusieurs images en entrée , exécute un traitement et délivre une nouvelle image en sortie. Toutes les classes de type « Effect » implémentent l’interface IImageConsumer, prenant en entrée une image source originale ; par ailleurs tout comme les classes de type « images sources », un objet « Effect » implémente l’interface IImageProvider pour la génération de l’image résultanteRenderer: Intervient à la fin du traitement. Il a pour rôle de convertir l’image résultante du traitement dans un format particulier (JPEG, bitmap …) consommé par l’application. Ce type d’objet implémente l’interface IImageConsumer
  2. Queue : FIFO appartenant au namespaceSystem.Collections.GenericAction : Classe delegate appartenant au namespace System
  3. Camera : Implementations de l’interfaceICameraCaptureDeviceinclut les objets de type PhotoCaptureDevice et AudioVideoCaptureDevice.Sourced’imagescompressées (PNG/JPEG) : StreamImageSource / BufferImageSource / StorageFileImageSource / RandomAccessStreamImageSource
  4. Exemple implémentant une nouvelle classe, dérivée de CustomEffectBaseIl faudra surcharger la méthode OnProcess, donnant directement accès aux pixels d’originePixelRegionest utilisée comme “helper class” afin de parcourir les pixels de la source et la cible Dans l’exemple ci-joint, MyCustomFilterdouble la valeur de chaque composante RGB
  5. Paramètres du filterChromakeyFilter :Couleur qui sera remplacée par de la transparenceTolérancedans la valeur de couleurremplacée (0 : tolerance faible, 1 : tolerance large)Niveau de suppression de bruit (0 : bruit faible, 1 : bruit visible)