Showing posts with label Webcam. Show all posts
Showing posts with label Webcam. Show all posts

Thursday, June 16, 2011

Cubelicious - Silverlight 5 + Balder + Physics + SLARToolkit Augmented Reality = Triple Win!

Two months ago I released a new Silverlight 5 sample for my open source Silverlight Augmented Reality Toolkit - SLARToolkit. It uses the new Silverlight 5 hardware accelerated 3D API. You can read more about the new Silverlight 5 XNA 3D API in this blog post.
This post here provides a new demo for SLARToolkit which uses the open source 3D engine Balder by my friend Einar Ingebrigsten. This demo also leverages the open source physics engine JigLibX my buddy Andy Beaulieu ported over to Silverlight. You can try the live sample if you have the Silverlight 5 beta installed or watch a video instead.

I actually spent most of the time on this project a couple of weeks ago. My good Silverlight MVP friend Einar Ingebrigtsen used it in his talk at The Gathering 2011. Now I finally had a bit time to finish the demo, make a video and this blog post.

The SLARToolkit project description from the CodePlex site:
SLARToolkit is a flexible Augmented Reality library for Silverlight with the aim to make real time Augmented Reality applications with Silverlight as easy and fast as possible. It can be used with Silverlight's Webcam API or with any other CaptureSource or a WriteableBitmap. SLARTookit is based on the established NyARToolkit and ARToolkit


Live
A webcam and at least the Silverlight 5 beta runtime must be installed to run the sample. It's available here. Alternatively there is also a video of the new sample embedded below.
If you want to try it yourself you need do download the SLAR and / or L marker, print them and hold them in front of the camera. The marker(s) should be printed non-scaled at the original size (80 x 80 mm) and centered for a small white border. As an alternative it's also possible to open a marker file on a mobile device and to use the device's screen as marker. Also make sure the camera is set up properly and the scene is illuminated well without hard shadows. See the SLARToolkit Markers documentation for more details.


Simply press the "Start Cam" Button to start the webcam. The properties of the particle system can  be changed with Sliders. The "Flip x-axis" Checkbox can be used to flip the video (the webcam output is mirror-reversed by default). 
If you click the "Start Cam" Button for the first time you need to give your permission for the capturing. This application uses the default Silverlight capture device. You can specify the video and audio devices that are used by default with the Silverlight Configuration. Just press the right mouse button over the application, click "Silverlight" in the context menu and select the "Webcam / Mic" tab to set them.

Video
I've recorded a short video of the new sample with Expression Encoder's Screen Capture feature. Please keep in mind that the screen recording software eats up a lot of resources while recording and that the actual frame rate is even better. The video is also available at YouTube.



Background music is Lullaby by _ghost

This demo shows how the new Silverlight 5 3D API, the Balder engine and the JigLibX physics library can be used to augment the reality with the help of SLARToolkit.

How it works
This sample uses the webcam video stream which fills a Rectangle shape, the video stream is also constantly captured and fed to the SLARToolkit BitmapMarkerDetector to detect the markers. The detection result contains a transformation matrix for each found marker which is then used to apply a global transformation to the cubes and the plane.
I implemented a particle system with a flexible directed emitter which can be controlled through various properties. The particle system is quite generic and can be used for all kinds of particles (3D objects). The particle collision detection and resolving is based on rigid body physics that was implemented with the help of the JigLibX library my Silverlight MVP buddy Andy Beaulieu ported over to Silverlight.
The rendering and the model loading is done by the 3D engine Balder. It's a fantastic open source engine by Einar Ingebrigtsen. You just need to write a couple lines of XAML and you're good to go. This sample only uses a simple cube model, but Balder has built-in model loaders to load complex 3D models and Einar provides a big sample library. He also brought the engine to a few more platforms like Windows Phone 7, OpenGL and has even a neat software rendering fallback. Read his blog post here.
As part of this sample I needed some vector and quaternion methods which were missing in Balder. I contributed those and the generic particle system to the Balder project. Feel free to use the particle system and the other methods in your Balder projects.

Download it, build your app and augment your reality
The open source SLARToolkit library and all samples are hosted at CodePlex. If you have any comments, questions or suggestions don't hesitate and write a comment, use the Issue Tracker on the CodePlex site or contact me via any other media.
Have fun with the library and please keep me updated if you use it anywhere so I can put a link on the project site.

Wednesday, May 25, 2011

Unity 3D and Silverlight in Harmony with SLARToolkit's Augmented Reality

If you read this blog regularly, you might have noticed a lot of SLARToolkit posts recently. But I'm not the only one using the open source Silverlight Augmented Reality Toolkit. There's great stuff happening out there and I see quite a few projects, especially in the academic field. You can find a full list of projects (I know of) on the SLARToolkit project site at CodePlex.
I love when people use my open source work, adapt or learn from it. This is what open source is all about for me.



One project recently caught my attention in particular. Ioulian Alexeev made a very amazing action game using the Unity 3D game engine and he combined it with SLARToolkit to control the spaceship with a marker. Ioulian studies Multimedia at the Arteveldehogeschool in Belgium and the game "StarFighter" was his bachelors test.

He recorded this nice video.


Note how he compares the performance of the Flash Augmented Reality Tookit and SLARToolkit:
Performance FLARManager: Not good enough for action games
Performance SLARToolkit: Very fast and accurate marker tracking
Both toolkits use the same marker-based AR algorithms from the ARToolkit.

Live
You can play the game here. If you want to try it yourself you need do download the SLAR and / or L marker, print them and point the camera toward these. The marker(s) should be printed non-scaled at the original size (80 x 80 mm) and centered for a small white border. As an alternative it's also possible to open a marker file on a different device and to use the device's screen as marker.
See the SLARToolkit Markers documentation for more details.

Wednesday, April 13, 2011

Silverlight 5 3D + SLARToolkit Augmented Reality = Win!

It's almost been a year since I wrote a sample for my open source Silverlight Augmented Reality Toolkit - SLARToolkit. The release of the new Silverlight 5 hardware accelerated 3D API was a nice occasion to finally make a new one.
In my last blog post I wrote a summary of all the Silverlight 5 beta features and some notes about the new low-level, XNA 3D API.
This post provides the new demo for SLARToolkit which leverages this fast GPU-based rendering to draw some nice effects with 60 frames per second. You can try the live sample if you have the Silverlight 5 beta installed or watch a video instead.

The SLARToolkit project description from the CodePlex site:
SLARToolkit is a flexible Augmented Reality library for Silverlight with the aim to make real time Augmented Reality applications with Silverlight as easy and fast as possible. It can be used with Silverlight's Webcam API or with any other CaptureSource or a WriteableBitmap. SLARTookit is based on the established NyARToolkit and ARToolkit
Live
A webcam and at least the Silverlight 5 beta runtime must be installed to run the sample. It's available here. Alternatively there is also a video of the new sample embedded below.
If you want to try it yourself you need do download the SLAR and / or L marker, print them and hold them in front of the camera. The marker(s) should be printed non-scaled at the original size (80 x 80 mm) and centered for a small white border. As an alternative it's also possible to open a marker file on a mobile device and to use the device's screen as marker. Also make sure the camera is set up properly and the scene is illuminated well without hard shadows. See the SLARToolkit Markers documentation for more details.



Simply press the "Start Fun" Button to start the webcam. The size of the objects can be changed with the "Scale" Sliders. The "Flip x-axis" Checkbox could be used to flip the video (the webcam output is mirror-reversed by default). Click the "Glass" Checkbox to apply a glass effect to the sun model.
If you click the "Start Fun" Button for the first time you need to give your permission for the capturing. This application uses the default Silverlight capture device. You can specify the video and audio devices that are used by default with the Silverlight Configuration. Just press the right mouse button over the application, click "Silverlight" in the context menu and select the "Webcam / Mic" tab to set them.

Video
I've recorded a short video of the new sample with Expression Encoder's Screen Capture feature. Please keep in mind that the screen recording software eats up a lot of resources while recording and that the actual frame rate is even better. The video is also available at YouTube.



Background music is Neon Aurora by Alpha C

This demo shows how the new Silverlight 5 3D API can be used  to augment the reality with the help of SLARToolkit. It also demonstrates how the 3D DrawingSurface can be combined with the webcam video stream and overlaid with ordinary TextBoxes. This can be nice for educational projects and it's actually no problem to add correctly transformed videos or other content to the demo.

How it works
This sample uses the webcam video stream which is used to fill a Rectangle shape, the video stream is also constantly captured and fed to the SLARToolkit BitmapMarkerDetector to detect the markers. The detection result contains a transformation matrix for each found marker which is then used to transform the 3D objects and the TextBoxes.
A couple of vertex and pixel shaders are used to get the desired effects. Techniques like Phong shading, Bump mapping and Refraction mapping (glass) were implemented. The snapshots from the webcam are passed as a texture to the refraction pixel shader to simulate the glass effect.
See the source code if you're interested in the nitty-gritty details. Please note that I wrote an introduction to Pixel Shaders for Coding4Fun a while ago.
The current Silverlight 5 beta doesn't implement RenderTargets, therefore effects like bloom aren't really possible with the limitations of the Shader Model 2. You can add a faded billboard around the sun, but it wouldn't look that nice and when RenderTargets are added we can do way more nice effects in future releases of Silverlight 5.
I also added a new simple anti-jittering functionality to SLARToolkit to prevent the jiggling that mostly occurred due to the varying lightning conditions and noise in the video stream.

Credits
The SolarWind sample by the Silverlight team was used as a base and extended. The sample uses earth textures from the NASA. The pixel shader for the sun uses textures and concepts from an article by Nicolas Menzel. The moon textures are from the Celestia project.

Download it, build your app and augment your reality
The open source SLARToolkit library and all samples are hosted at CodePlex. If you have any comments, questions or suggestions don't hesitate and write a comment, use the Issue Tracker on the CodePlex site or contact me via any other media.
Have fun with the library and please keep me updated if you use it anywhere so I can put a link on the project site.

Monday, June 7, 2010

Interview on .Net Rocks!

About a month ago Richard Campbell asked me if I'd like to give an interview about SLARToolkit on the .Net Rocks talk show. Of course I agreed right away. .Net Rocks! is the largest .Net developer podcast out there and Carl Franklin and Richard Campbell always have great guests. It's a real honor for me to have been on show #564.
We mainly talked about the Silverlight Augmented Reality Toolkit (SLARToolkit), but also about some of my other projects and articles.
You can download the podcast in various formats from here. I hope you like it. Also make sure you subscribe to .Net Rocks!

Thursday, June 3, 2010

Push and Pull - Silverlight Webcam Capturing Details

Photo (CC) by  MShades
It's not a secret that one of my favorite Silverlight 4 features is the webcam support and I already played endless hours with it. There are many blog posts out there demonstrating how to use the webcam and how to take a screenshot with the CaptureImageAsync method. Only a few cover the VideoSink.
This blog post will show how to use the webcam, the CaptureImageAsync method and also how to implement and use the VideoSink. But most important I'll cover what the differences between the CaptureImageAsync and VideoSink are and when to use which.



Silverlight Webcam 101
The Silverlight 4 webcam API is pretty easy to use and just a few lines of code are needed to show a webcam video stream on screen.
Silverlight's CaptureSource class provides the webcam stream that is used as the source of a VideoBrush, which in turn fills a Rectangle with the video feed from the webcam. It's also possible to use any other Shape with a Fill property.
The CaptureDeviceConfiguration class can be used to retrieve a list of all installed video and audio devices on the system. Most of the time it's sufficient to use the GetDefaultVideoCaptureDevice to get the default device. The user can specify the default video and audio devices with the Silverlight configuration; he or she only has to press the right mouse button over the Silverlight application, click "Silverlight" in the context menu and select the "Webcam / Mic" tab to set them.

Silverlight Webcam / Mic configuration dialog.

The following C# code initializes the webcam (captureSource) in the Loaded event of the page and fills a rectangle (Viewport) with a VideoBrush:
// Member variable (webcam reference)
CaptureSource captureSource;

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
   // Initialize the webcam
   captureSource = new CaptureSource();
   captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

   // Fill the Viewport Rectangle with the VideoBrush
   var vidBrush = new VideoBrush();
   vidBrush.SetSource(captureSource);
   Viewport.Fill = vidBrush;
}

Now that the webcam is initialized, the streaming can be started. This is done in an event handler of a Button because RequestDeviceAccess has to be called from an user initiated event. Otherwise it would be possible to start the webcam without the user's permission. Of course nobody wants to experience something like what happened to the students with their MacBooks provided by their high school.

Here's the C# code:
private void StartButton_Click(object sender, RoutedEventArgs e)
{
   // Request webcam access and start the capturing
   if (CaptureDeviceConfiguration.RequestDeviceAccess())
   {
      captureSource.Start();
   }
} 

This will open a webcam permission dialog asking the user for the device access. This setting is consent and Silverlight can remember if the user has previously allowed that certain application.

Webcam permission dialog

Capturing The Webcam 
There are two different approaches to capture the webcam in Silverlight. The CaptureSource's CaptureImageAsync method and CaptureImageCompleted event provide a snapshot on demand and can be considered as a pull-based technology. A custom VideoSink implementation on the other hand constantly gets the raw stream from the webcam and can be considered as a push-based approach.

Pull: CaptureImageAsync Webcam Capture
When the CaptureSource's CaptureImageAsync method is called an asynchronous capturing task is started. After the snapshot is completed, the CaptureImageCompleted event is fired. The event provides a WriteableBitmap as EventArgs.

The following C# code should be added after the captureSource initialization code above:
// Wiring the CaptureImageCompleted event handler
captureSource.CaptureImageCompleted += (s, e) =>
{
   // Do something with the camera snapshot
   // e.Result is a WriteableBitmap
   Process(e.Result);
};

Another button is used to start the asynchronous capturing:
private void SnapshotButton_Click(object sender, RoutedEventArgs e)
{
   // CaptureImageAsync fires the CaptureImageCompleted event
   captureSource.ImageCaptureAsync();
} 

Push: VideoSink Webcam Capture
The other capturing approach constantly pushes every frame from the webcam into a VideoSink. The abstract VideoSink class has four methods that have to be implemented in an own subclass in order to use it.

The basic set-up of a custom VideoSink looks like this:
// MyVideoSink is derived from Silverlight's VideoSink
public class MyVideoSink : VideoSink
{
   VideoFormat vidFormat;
   
   // Could be used to initialize a container for the webcam stream data
   protected override void OnCaptureStarted() { }
   
   // Could be used to dispose a container for the webcam stream data
   // or to write a header of a video file format
   protected override void OnCaptureStopped() { }

   // Is called when the VideoFormat was changed
   protected override void OnFormatChange(VideoFormat videoFormat)
   {
      this.vidFormat = videoFormat;
   }

   // Is called every time the webcam provides a complete frame (Push)
   protected override void OnSample(long sampleTime, long frameDuration, 
                                    byte[] sampleData)
   {
      // Process the webcam snapshot 
      // sampleData contains the raw byte stream
      // according to the videoFormat from OnFormatChange
      Process(sampleData, this.vidFormat);
   }
}

The following C# code initializes MyVideoSink with the webcam. It should be added after the captureSource initialization code above:
// Wire the VideoSink and the webcam together
var sink = new MyVideoSink { CaptureSource = captureSource };

The VideoSink's OnCaptureStarted and OnFormatChange are raised after the captureSource.Start() method was called. The OnSample method is constantly called as long as the webcam is activated. The actual interval OnSample will be called is defined in VideoFormat.FramesPerSecond which is provided through the OnFormatChange method. The OnCaptureStopped is raised after the captureSource.Stop() method was called.

Push vs. Pull
Obviously the two approaches have different characteristics.

Pull: CaptureImageAsync

Push: Custom VideoSink
  • Direct usage of the raw byte stream
  • Less overhead
  • OnSample is called on a background thread
  • Automatically called for every frame
  • Might support more than one PixelFormat in the future
  • More information like frame number and duration (accurate sample times)
  • Slightly faster than CaptureImageAsync if every frame is needed
  • Push: Constant sampling

Please note that the CaptureImageAsync method can also be called periodically. Thereby it's possible to get a snapshot in a defined interval which might be faster than using a VideoSink that fires every 30 or even 60 frames per second (fps).

The following C# code calls CaptureImageAsync every 100 milliseconds, which means every 10 fps a snapshot is taken:
var dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); // 10 fps
dispatcherTimer.Tick += (s, e) =>
{
   // Process camera snapshot if started
   if (captureSource.State == CaptureState.Started)
   {
      // CaptureImageAsync fires the CaptureImageCompleted event
      captureSource.CaptureImageAsync();
   }
};
// Start the timer
dispatcherTimer.Start();

Conclusion
Both approaches are helpful for different scenarios. The pull-based CaptureImageAsync method is useful for taking single snapshots, whereas a push-based custom VideoSink can be used for capturing complete sequences and encoding the webcam stream.

Monday, May 17, 2010

SLARToolkit Beginner's Guide

Since I released SLARToolkit I often get similar, basic questions. This is a sign that the SLARToolkit documentation and the samples might be too complex for a beginner. That's why I wrote an easy step by step Beginner's Guide which hopefully closes the gap. The tutorial shows how to build the simplest Silverlight Augmented Reality application possible.

The guide is part of the SLARToolkit documentation at CodePlex. Please read the Beginner's Guide here and let me know your feedback so I can improve it further.

Thursday, March 25, 2010

Coding4Fun - Silverlight Real Time Face Detection

A while ago Clint Rutkas (yes, the guy that built the awesome MIX T-Shirt cannon) asked me if I could write an article for Microsoft's Coding4Fun site. I felt honored and of course I agreed. Today I'm proud to announce that my first Coding4Fun article was published.


The article demonstrates how to implement a simple facial recognition system using Silverlight 4’s new webcam feature. The method I've implemented searches for a certain sized skin color region in a webcam snapshot. This technique is not as perfect as a professional computer vision library like OpenCV and the Haar-like features they use, but it runs in real time and works for most webcam scenarios.

The complete source code for the article is available at CodePlex and licensed under the Ms-PL.
If you like the article, I’ll write a follow-up that might cover a more stable (better) segmentation approach, how to optimize the performance further and more.

Update 04-06-2010
The article was translated into Russian and is available at the Russian Coding 4 Fun site.

Update 04-15-2010
Updated the application to the final Silverlight 4 RTW build.

Monday, March 15, 2010

The Silverlight 4 Release Candidate

Scott Guthrie et al. announced many awesome new things during the keynotes at Microsoft's MIX10 conference. One of it was the Silverlight 4 Release Candidate which replaces the beta version and is now available for download. Beside all the great new features that were added, it's now finally possible to use the Visual Studio 2010 RC for Silverlight 4 development. Kudos to the Silverlight team for catching up with Visual Studio 2010 and all the cool new features they implemented. 

The final Silverlight 4 RTW version will be available next month (April 2010). Additonaly the first CTP of the Winows Phone SDK was released and Silverlight is THE platform for Windows Phone 7 series development and it's free! Silverlight for Symbian is also now available for Nokia S60 5th Edition devices like the N97. So Silverlight is becoming more and more a full multi platform technology. Awesome!

This blog post focuses on the Silverlight 4 RC and contains a summary of all the new features that were added since the Silverlight 4 Beta to the Silverlight 4 RC and the breaking changes that naturally come along with betas. Plus some details about the CaptureSource's new capture usage pattern.


New Silverlight 4 RC features

Rich Text
  • RichTextBox rename
  • Text position and selection APIs
  • XAML property for serializing text content
  • XAML clipboard format
  • FlowDirection support on Runs
  • "Format then type" support
  • Thai / Vietnamese / Indic support
  • UI Automation Text pattern
Networking
  • UploadProgress support (Client stack)
  • Caching support (Client stack)
  • Sockets security restrictions removal (Full Trust)
  • Sockets policy file retrieval via HTTP
  • Accept-Language header
Out of Browser (Full Trust)
  • XAP signing
  • Silent install and emulation mode
  • Custom window chrome
  • Better support for COM Automation
  • Cancelable shutdown event
  • Updated security dialogs
Media
  • Pinned full-screen mode on secondary display
  • Webcam / Mic configuration preview
  • More descriptive MediaSourceStream errors
  • Content & Output protection updates
  • Updates to H.264 content protection (ClearNAL)
  • Digital Constraint Token
  • CGMS-A
  • Multicast
  • Graphics card driver validation & revocation
Graphics and Printing
  • Hardware accelerated perspective transformations
  • Ability to query page size and printable area
  • Memory usage and performance improvements
Data
  • Entity-level validation support of INotifyDataErrorInfo for DataGrid
  • XPath support for XML
Parser
  • New architecture enables future innovation
  • Performance and stability improvements
  • XmlnsPrefix & XmlnsDefinition attributes
  • Support setting order-dependent properties
Globalization & Localization
  • Support for 31 new languages
  • Arabic, Hebrew and Thai input on Mac
  • Indic support
More
  • Update to DeepZoom code base with hardware acceleration
  • Support for Private mode browsing
  • Google Chrome support (Windows)
  • FrameworkElement.Unloaded event
  • HTML Hosting accessibility
  • IsoStore performance improvements
  • Native hosting performance improvements (e.g. Bing Toolbar)
  • Consistency with Silverlight for Mobile APIs and Tooling
  • System.Numerics.dll
  • Dynamic XAP support (MEF)
  • Frame / Navigation refresh support
The new webcam and microphone configuration preview is pretty neat. The user can now select the default webcam & microphone device really comfortable and we only need to use CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice() or CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice() to get the selected default video and audio device.


The webcam permission dialog is now consent and can remember if the user has previously allowed that certain application. Tim Heuer's blog post has more details about this handy new feature.


Breaking Changes since the Silverlight 4 beta
The first and most important take away: As usual all Silverlight 4 beta applications have to be updated to the RC and recompiled, otherwise the new RC runtime won't execute them.
  • Renamed RichTextArea to RichTextBox
  • Changes to DRM API
  • TextSelection.SetPropertyValue is now named .ApplyPropertyValue
  • INotifyDataErrorInfo moved to core (System.Windows.dll)
  • WebBrowser.ScriptNotify signature change
  • NotificationWindow.Visible and NotificationWindow.Closed were changed
  • Webcam and output protection change
  • COM Interop API changes (name and namespace)
  • RichTextBox.TextWrapping default value changed
  • Binding declarations in XAML where the target is a DependencyObject
  • HtmlBrush renamed to WebBrowserBrush

The official breaking changes document contains all the details and Koen Zwikstra (@kozw) has made some useful diff lists.

Changed usage pattern for AsyncCaptureImage
The biggest difference in the webcam API besides the renaming of some enums, properties and other members is the change of the AsyncCaptureImage method which was renamed to CaptureImageAsync. Additionally the usage pattern of the CaptureImageAsync method was updated to the standard .Net / Silverlight asynchronous event pattern.

Before the Silverlight 4 RC, AsyncCaptureImage was used like this:
// Initialization
captureSource = new CaptureSource();
captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

// Capture image
captureSource.AsyncCaptureImage(bitmap =>
{
   // Process camera snapshot
   Process(bitmap);
});

The new RC CaptureImageAsync usage pattern:
// Initialization
captureSource = new CaptureSource();
captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
// Wiring the CaptureImageCompleted event handler
captureSource.CaptureImageCompleted += (s, e) =>
{
   // Process camera snapshot (e.Result is a WriteableBitmap)
   Process(e.Result);
};

// CaptureImageAsync fires the CaptureImageCompleted event
captureSource.ImageCaptureAsync();

Although the pre-RC pattern was smaller and easier, it's overall more consistent now and I welcome the changes.

Blog.SL4++
I already updated SLARToolkit and the samples and I will continue to update some of my Silverlight 4 beta samples during the next days. Furthermore I will make a Silverlight 4 RC build of the Matrix3DEx sample that should take advantage of the new hardware accelerated perspective transformations.

Wednesday, February 24, 2010

SLARToolkit - Silverlight Augmented Reality Toolkit

In my last blog post I've preannounced SLARToolkit: The open source Silverlight Augmented Reality Toolkit. Today I'm proud to announce that SLARToolkit is now available at CodePlex.
The aim of SLARToolkit is to make Augmented Reality with Silverlight as easy as possible so that everyone will be able to make Silverlight Augmented Reality applications. Therefore the SLARToolkit release not only includes the full Balder sample you might know from this blog post, it also comes with a brand new sample that uses Silverlight's 3D projection capabilities through my Matrix3DEx library to project different UIElements on the marker.

The SLARToolkit project description from the CodePlex site:
SLARToolkit is a flexible Augmented Reality library for Silverlight with the aim to make real time Augmented Reality applications with Silverlight as easy and fast as possible. It can be used with Silverlight's Webcam API or with any other CaptureSource or a WriteableBitmap. SLARTookit is based on the established NyARToolkit and ARToolkit. SLARToolkit uses a dual license model and could be used for open or closed source applications under certain conditions. See the License page for details.
Features:
Live
A webcam and at least the Silverlight 4 runtime must be installed to run the sample. It's available for Windows and Mac. Alternatively there is also a new video of the Silverlight projection sample embedded below.
If you want to try it yourself you need do download the SLAR and / or L marker, print them and hold them in front of the camera. The marker(s) should be printed non-scaled at the original size (80 x 80 mm) and centered for a small white border. Also make sure the camera is set up properly and the scene is illuminated well without hard shadows. See the SLARToolkit Markers documentation for more details.




Simply press the "Start Fun" Button to start the webcam. Use the ComboBox to select a different UIElement that will be mapped on the marker. The size and the orientation can be changed with the "Scale" and "Rotation" Sliders. The "Threshold" Slider controls the threshold for the marker detection. The "Flip x-axis" Checkbox could be used to flip the video (the webcam output is mirror-reversed by default).
If you click the "Start Fun" Button for the first time you need to give your permission for the capturing. This application uses the default Silverlight capture device. You can specify the video and audio devices that are used by default with the Silverlight Configuration. Just press the right mouse button over the application, click "Silverlight" in the context menu and select the "Webcam / Mic" tab to set them.

Video
I've recorded a short video of the new sample with Expression Encoder's Screen Capture feature. Please keep in mind that the screen recording software eats up a lot of resources while recording and that the actual frame rate is way better.


Background music is leandi by mosaik.


How it works
This sample uses the SLARToolkit CaptureSourceMarkerDetector to detect the markers in each webcam frame. The detection result contains a transformation matrix for each found marker which is then used to transform the selected UIElement. The tracked marker region is highlighted with a red quad through the WriteableBitmapEx library.

Download it, build your app and augment your reality
The open source SLARToolkit library and the samples are hosted at CodePlex. If you have any comments, questions or suggestions don't hesitate and write a comment, use the Issue Tracker on the CodePlex site or contact me via any other media.
Have fun with the library and please keep me updated if you use it anywhere so I can put a link on the project site.

Update 03-15-2010
Updated to the Silverlight 4 Release Candidate.

Update 04-15-2010
Updated to the final Silverlight 4 RTW build.

Monday, February 15, 2010

SLARToolkit Preannouncement

SLARToolkit has been released. Please read this blog post.

In my latest blog posts, the comments and on Twitter I hinted at on one of the projects I'm currently working on: SLARToolkit - The Silverlight Augmented Reality Toolkit. My aim for SLARToolkit is to make Augmented Reality with Silverlight as easy as possible, fast and open source. With this everyone will be able to make Silverlight Augmented Reality applications like that one. SLARToolkit is based on NyARToolkit which is a extented port of the famous ARToolkit. I'm almost done with the implementation and in contact with ARToolworks, which are holding the license for ARToolkit, to get a license agreement. I hope I'll be able to release SLARToolkit within the next two or three weeks at CodePlex. Please stay tuned.


Two weeks ago Julien Dollon contacted me and asked if I could help him with an Augmented Reality demo for his Silverlight 4 talk at Microsoft TechDays 2010 in Paris. Since I'm a nice guy, I've built a special SLARToolkit version for him and send it along with the source code of the SLARToolkit Silverlight projection sample. The sample uses my Matrix3DEx library to project UIElements on the markers. Actually the Matrix3DEx library has its roots there.
Julien altered the sample a bit and showed it at MS TechDays 2010 during his Silverlight 4 talk last week. The presentation was recorded and the official video is available, but you can also watch Julien's self recorded video of the session. The SLARToolkit demo starts at 39:02.





And the official screen cast:

Wednesday, December 30, 2009

Ye Olde Kamera - Silverlight 4 Webcam & Old Movie Shader

Another great and successful year comes to an end and I hope that the next year will get even better. We all don't get younger and we change over the years, but the last Silverlight demo I made for this year allows you take some fake aged memories with your webcam. The Silverlight 4 webcam and microphone support is always fun and even more when it's combined with a pixel shader. This demo uses my Old Movie Pixel Shader to create a neat real time webcam effect that simulates scratches, noise and other effects you might have seen in old movies. I also brushed things up a bit by framing the video output with a filmstrip and using some nice new icons from eggheadcafe.

Live
The Silverlight 4 runtime must be installed to run the demo. It's available for Windows and Mac.



The Webcam capturing could be started and stopped with the camera Button. If you press it for the first time you need to give your permission for the capturing. This application uses the default Silverlight capture device. You can specify the video and audio devices that are used by default with the Silverlight Configuration. Just press the right mouse button over the application, click "Silverlight" in the context menu and select the new "Webcam / Mic" tab to set them.
Press the disk Button to take a framed snapshot and save it to a JPEG file on your harddisk.
The amount of noise can be changed using the Slider and the movie ToggleButton allows you to disable the Old Movie Shader.

How it works
It's basically the Silverlight 4 CaptureSource class and my Old Movie Pixel Shader attached to the video output. I covered the Silverlight webcam and shader usage in this blog post and the JPEG encoding in this one. The Old Movie Shader was presented here.

Source code
The Visual Studio 2010 solution including the refactored Old Movie Shader is available here.

Final words
Thanks to my kids and especially to my wife for all her patience in 2009. I love her!
I also like to thank all the people and new friends I got to know this year and especially the Silverlight community. I hope you liked my blog posts and enjoyed the Silverlight demos I've made. I have more to come next year.
I wish you all a great new year, all the best in 2010 and peace!

Update 03-20-2010
Updated to the Silverlight 4 release candidate.

Update 04-15-2010
Updated to the final Silverlight 4 RTW build.

Thursday, December 17, 2009

World# - Real Time 3D Augmented Reality with Silverlight

Please read the Update at the end of this post.

In the Silverlight 4 Augmented Reality Proof Of Concept blog post I proved that it's possible to implement Augmented Reality applications with Silverlight 4 and the built-in webcam API. The proof of concept used an image showing a Silverlight logo that was attached to the tracked marker. With this blog post I'm back in this field, but this time with real 3D Augmented Reality in Silverlight!
I use the open source Augmented Reality library NyARToolkitCS again and implemented the necessary interfaces to make it work with Silverlight. The NyARToolkitCS library is a completely managed version of the well known ARToolkit. I also use the open source managed game engine Balder for the rendering of 3D models that augment the reality. Balder is mainly developed by the Silverlight MVP Einar Ingebrigtsen. He is working hard on his 3D game engine and provided quick fixes for some issues I encountered while using Balder and I also had a nice chat with him, so big shout out to Einar.

Live
A webcam and at least the Silverlight 4 runtime must be installed to run the sample. To view the application you need to install the Silverlight 4 runtime. It's available for Windows and Mac. You can also watch a video below.
If you want to try it yourself you need do download the SLAR and / or L marker, print them and hold them in front of the camera. The marker(s) should be printed non-scaled at the original size (80 x 80 mm) and centered for a small white border. Also make sure the camera is set up properly and the scene is illuminated well without hard shadows. See the SLARToolkit Markers documentation for more details.

Try it out here.

Simply press the "Start Fun" Button, hold the printed marker in front of the camera and move it around. Use the ComboBox to select a different 3D model. The "Flip x-axis" Checkbox could be used to flip the video (the webcam output is mirror-reversed by default).
If you click the "Start Fun" Button for the first time you need to give your permission for the capturing. This application uses the default Silverlight capture device. You can specify the video and audio devices that are used by default with the Silverlight Configuration. Just press the right mouse button over the application, click "Silverlight" in the context menu and select the "Webcam / Mic" tab to set them.
The Car model was made by Psionic, the Tank model by Ken Beyer. The Teapot is from the Balder samples and I guess it was made by Einar Ingebrigtsen. The rest was made by myself.

Video
This time I used Expression Encoder's Screen Capture feature to record a short video of the demo in action. Please keep in mind that the screen recording software eats up a lot of resources while recording and that the actual frame rate is way better.



How it works
Every time the CompositionTarget.Rendering event is fired, a webcam snapshot is taken asynchronously with the CaptureSource.AsyncCaptureImage method. This snapshot is converted in the right format and passed to the NyARToolkitCS library that outputs a transformation matrix. This matrix is used to transform the 3D model. The Balder viewport has a transparent background and the scene with the 3D objects is laid over the webcam video output. Another layer is an image that uses a WriteableBitmap and the WriteableBitmapEx library to highlight the tracked marker region with a red quad.
Sounds pretty easy, but actually it was not that easy and straight forward. One of the hardest parts was the initialization and to find the right parameters.

Results
I'm quite satisfied with the results and if you consider that all the heavy computation is done by the CPU, the performance is pretty good as well. The demo runs smoothly at 50-60 fps on a dual core machine utilizing its whole power and it should also scale up on more cores.

To be continued
If you expected source code this time I have to disappoint you. The code is not at that level where it should be, but I wanted to push this demo out. I'm not sure if I find enough time this year to work on the code and I don't want that someone tries to use it in the current state. But trust me, I will provide open source functionality to make Augmented Reality in Silverlight in the near future and I normally keep my promises, so stay tuned for more happy days...

Update 02-24-2010
This demo is now part of the open source SLARToolkit library which was announced in this blog post.

Update 03-15-2010
Updated to the Silverlight 4 Release Candidate.

Update 04-15-2010
Updated to the final Silverlight 4 RTW build.

Thursday, December 3, 2009

Silverlight 4 Augmented Reality Proof Of Concept

Please goto: World# - Real Time 3D Augmented Reality with Silverlight. Such demos are now easily possible with the open source SLARToolkit.

In this short blog post I want to present a demo I've actually made last week. Unfortunately I had no time to work on it since then. This demo is a proof of concept for doing Augmented Reality with Silverlight 4 and the built-in webcam API.
I use the open source Augmented Reality library NyARToolkitCS and implemented the necessary interfaces to make it work with Silverlight. The NyARToolkitCS library is a completely managed version of the well known ARToolkit.

Video
I've recorded a short video with my iPhone 3GS. The video was recorded at night and it's no secret that the iPhone camera is not the best, but I think it's good enough to see how the marker is tracked and the Silverlight logo moves with it.


Background music is "You have something in your scowl" by Henrik José / Bliss.


To be continued
The first results are quite good and the demo runs smoothly at 60-70 fps on a dual core machine utilizing both cores. I will continue my work on this project and provide more details, samples and of course source code.
Stay tuned...

Monday, November 23, 2009

EdgeCam Shots - Saving Silverlight 4 Webcam Snapshots to JPEG

In my last blog post I have covered the new Silverlight 4 Webcam API and provided a demo that used my edge detection pixel shader to create a nice real time webcam effect. In this post I make an extended version available which can save webcam snapshots as JPEG files and I also discuss some limitations of the webcam API's built-in CaptureSource.AsyncCaptureImage snapshot method. Furthermore I will give some ideas on how to build a Silverlight 4 video chat / conference application on top of the provided JPEG capturing and encoding code.


Live
To view the application you need to install the Silverlight 4 runtime. It's available for Windows and Mac.



The Webcam capturing could be started and stopped with the "Start Capture" Button. If you press it for the first time you need to give your permission for the capturing. This application uses the default Silverlight capture device. You can specify the video and audio devices that are used by default with the Silverlight Configuration. Just press the right mouse button over the application, click "Silverlight" in the context menu and select the new "Webcam / Mic" tab to set them.
Press the "Save Snapshot" Button to take a snapshot and save it to a JPEG file on your harddisk.
The threshold of the edge detection can be changed using the Slider and the "Bypass" Checkbox allows you to disable the shader.

How it works
The base Silverlight 4 webcam usage code was covered in my last blog post.

The new eventhandler for the "Save Snapshot" button:
private void BtnSnapshot_Click(object sender, RoutedEventArgs e)
{
   if (saveFileDlg.ShowDialog().Value)
   {
      using (Stream dstStream = saveFileDlg.OpenFile())
      {
         SaveSnapshot(dstStream);
      }
   }
}
The code is pretty obvious: A SaveFileDialog is shown and if the user enters a file name and hits OK, a stream to the file will be opened and passed to the SaveSnapshot method. There's only one think to keep in mind when using the SaveFileDialog.ShowDialog() method, it can only be called from user-initiated code like an event handler, otherwise a SecurityException is thrown.

The SaveSnapshot method including comments:
// Render Rectangle manually into WriteableBitmap
WriteableBitmap bmp = new WriteableBitmap(ViewportHost, null);

// Init buffer in FluxJpeg format
int w = bmp.PixelWidth;
int h = bmp.PixelHeight;
int[] p = bmp.Pixels;
byte[][,] pixelsForJpeg = new byte[3][,]; // RGB colors
pixelsForJpeg[0] = new byte[w, h];
pixelsForJpeg[1] = new byte[w, h];
pixelsForJpeg[2] = new byte[w, h];

// Copy WriteableBitmap data into buffer for FluxJpeg
int i = 0;
for (int y = 0; y < h; y++)
{
   for (int x = 0; x < w; x++)
   {
      int color = p[i++];
      pixelsForJpeg[0][x, y] = (byte)(color >> 16); // R
      pixelsForJpeg[1][x, y] = (byte)(color >> 8);  // G
      pixelsForJpeg[2][x, y] = (byte)(color);       // B
   }
}

//Encode Image as JPEG
var colModel = new ColorModel { colorspace = ColorSpace.RGB };
var jpegImage = new FluxJpeg.Core.Image(colModel, pixelsForJpeg);
var encoder = new JpegEncoder(jpegImage, 95, dstStream);
encoder.Encode();
The Rectangle's surrounding Grid "ViewportHost" is rendered into a WriteableBitmap and the WriteableBitmap's Pixels are copied into another buffer with a different format. The rendered image is then written as a JPEG encoded stream using the open source FJCore library which is distributed under the MIT License. I've found some code at Stackoverflow on how to use the library in combination with the WriteableBitmap, but I modified / shortened it.
See my post on how to Convert, Encode And Decode Silverlight WriteableBitmap Data if you are interested in more WriteableBitmap conversion and JPEG encoding code.

Why not CaptureSource.AsyncCaptureImage?
You might be wondering why I haven't used the Silverlight 4 webcam API's built-in AsyncCaptureImage snapshot method of the CaptureSource class.
  1. The AsyncCaptureImage method grabs a frame directly from the device and therefore any effects like the edge detection pixel shader won't be visible in the rendered image.
  2. It only works if the CaptureSource was started, so the user can't save the visible image when the capturing was stopped. See the MSDN for details.
Please keep in mind that the first beta version of Silverlight 4 was used for this blog post and that some things will be changed in subsequent releases.

Where to go from here
The code in the SaveSnapshot method could be optimized and also multithreaded. The rendering should run in it's own thread. The encoding in a separate thread too and the network transport also. This approach would utilize modern quad core CPUs. After that it might be a good starting point for a video chat / conferencing application that continuously renders JPEGs and transports them between Silverlight clients. This technique is similar to the M-JPEG video format that also uses separately compressed JPEGs.
To make this idea usable for a Silverlight video chat, only the rendering, the JPEG encoder and the transfer method  need to be fast enough for real time streaming.
Please leave a comment what you think about it.

Source code
Download the Visual Studio 2010 solution here.

Update 03-20-2010
Updated to the Silverlight 4 release candidate.

Update 04-15-2010
Updated to the final Silverlight 4 RTW build.

Friday, November 20, 2009

EdgeCam - Silverlight 4 Webcam & Edge Detection Shader

Only 4 months after Silverlight 3 RTM came out Microsoft released the first beta version of Silverlight 4 on 11-18-2009 at the PDC. The new features are just awesome and many of them were requested by the community. Tim Heuer's great blog post covers all the new goodies in detail and provides videos and source code for most of them.
One of my favorite new features is the webcam and microphone support and I've coded a small demo that uses the new Silverlight 4 CaptureSource class and applied my edge detection pixel shader to it to create a cool real time webcam effect.

Live
To view the application you need to install the Silverlight 4 runtime. It's available for Windows and Mac. You can also watch a video below.



The Webcam capturing could be started and stopped with the Button in the middle. If you press it for the first time you need to give your permission for the capturing. This application uses the default Silverlight capture device. You can specify the video and audio devices that are used by default with the Silverlight Configuration. Just press the right mouse button over the application, click "Silverlight" in the context menu and select the new "Webcam / Mic" tab to set them.
The threshold of the edge detection can be changed using the Slider and the "Bypass" Checkbox allows you to disable the shader.

Video
I've recorded a short video with my iPhone 3GS that shows the demo running on my Samsung NC 10 Atom Netbook. The built-in webcam is not very good and the video was recorded at night, but I think it's good enough to see how the effect looks.


How it works
The new Silverlight 4 webcam and microphone API is pretty easy to use:
// Init capture devices
captureSource = new CaptureSource();
captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
captureSource.AudioCaptureDevice = CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice();

// Create video brush that preserves the aspect ratio and fill a Rectangle with it
VideoBrush videoBrush = new VideoBrush();
videoBrush.Stretch = Stretch.Uniform;
videoBrush.SetSource(captureSource);
Viewport.Fill = videoBrush;

// Ask user for permission
if (CaptureDeviceConfiguration.AllowedDeviceAccess
|| CaptureDeviceConfiguration.RequestDeviceAccess())
{
   captureSource.Start();
}
The edge detection pixel shader is applied to the "Viewport" Rectangle in the XAML. For a more intuitive behavior I've also attached a negative ScaleTransform to flip the x axis of the Rectangle. Otherwise the webcam output would be mirror-reversed by default.

Source code
The Visual Studio 2010 solution including the edge detection shader is available for download.

Update 11-23-2009
Make sure to read the follow up blog post EdgeCam Shots - Saving Silverlight 4 Webcam Snapshots to JPEG

Update 03-20-2010
Updated to the Silverlight 4 release candidate.

Update 04-15-2010
Updated to the final Silverlight 4 RTW build.