| (2 intermediate revisions by one user not shown) | |||
| Line 387: | Line 387: | ||
| ? | </code> | ? | </code> |
| ? | ? | ||
| ? | Our camera stream will look like this now | + | Our camera stream will look like this now. That is awesome! |
| ? | ? | ||
| ? |
| + | [[File:8bit_effect.png]] |
| ? | ? | ||
| ? | {{Note|You can find both variants of the algorithm in the attached sample project.}} | ? | {{Note|You can find both variants of the algorithm in the attached sample project.}} |
Revision as of 11:59, 29 July 2013
This article explains how to efficiently read a live stream from the camera on Windows Phone 7 and 8 devices and how to apply an effect filter on this stream.
Introduction
Most of the photo apps on the market are pretty simple. They allow users to take a photo, then apply some interesting vintage filter and save the photo. But only a few applications have a true live viewfinder with a real-time applied filter. Would it be nice to see how the photo will look like, even before you press the shutter button? What about some other live effects, like a pixelated 8-bit style screen?
We will show you in this article how to make an app (in C# language) that can run on both Windows Phone 7 and Windows Phone 8 devices. Our goal will be to design a sufficiently fast implementation that can run flawlessly even on the oldest and slowest devices. We will go through several ideas and implementations and we will compare them.
The main ideas
- We will use a VideoBrush component at first. We will demonstrate its limitations.
- We will read ARGB values directly from the camera, and see how this values can be efficiently packed and unpacked.
- We will discover a faster solution (reading values from the YCbCr buffer).
- We will discuss how to make this processing even better (to work with a smaller resolution).
- We will see an idea how to make an interesting 8-bit style photo app based on these methods.
We will be demonstrating these methods on the Windows Phone 7 (WP7) project. In the last chapter we will cover the differences between WP7 and Windows Phone 8 (WP8):
- We will see how to use this approach on WP8 thanks to MonoGame Framework
- We will compare all methods and measure the rendering time
VideoBrush component
The most simple solution for showing a direct stream from the camera is the VideoBrush component. The code is the same on WP7 and WP8. You can add this code into your XAML page:
<Rectangle Width="320" Height="320">
<Rectangle.Fill>
<VideoBrush x:Name="viewfinderBrush" />
</Rectangle.Fill>
</Rectangle>
In the code-behind you can initialize the camera and set the stream to the VideoBrush:
PhotoCamera camera;
?
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// Initialize a camera object, set stream to the VideoBrush
camera = new PhotoCamera();
viewfinderBrush.SetSource(camera);
}
?
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
camera.Dispose();
}
Do not forget to add an ID_CAP_ISV_CAMERA capability. This is a very simple solution. The stream from the camera is quite distorted and wrongly rotated, but you can fix this by setting a RelativeTransform on the Rectangle. But what is a real pity, you can't modify this stream in any way. You can't apply any filter or effect on the VideoBrush object, you don't have an access to the raw data of the pixels.
Reading from the buffer
We will use a different approach. As you can discover, there are some GetPreviewBuffer methods on the PhotoCamera object. This is the way how we can get the raw data from the camera. But we would like also to display this data somewhere, in some fast and efficient way. WritableBitmap component from the Silverlight is very slow, writing data pixel by pixel using this component can take a hundreds of milliseconds. We will need to find another solution.
We will create a new combined Silverlight/XNA project for Windows Phone 7 (we will talk about WP8 later). We would like to combine the ease of XAML and Silverlight with the power of the XNA in one solution. We will use a very similar approach to one described in the article Use Camera with XNA.
You need to have installed a Windows Phone SDK 7.1. Open your Visual Studio 2010 (Express or the Professional/Ultimate) and create a new Windows Phone Silverlight and XNA Application project.
To be able to read from the camera we need to place a fake Canvas to our XAML code. Add to GamePage.xaml page this line of code:
<Canvas x:Name="cameraDisplayFake" Width="0" Height="0"></Canvas> We will create a helper object now. Lets create a new class CamReader.cs and place into it these declarations:
PhotoCamera camera;
int[] previewBuffer, outputBuffer;
Point previewSize, outputSize;
As you can see, there is some preview buffer and the output buffer. The preview buffer will contain the raw values from the camera and will be usually 640x480 pixels big. Applying effects on this large resolution would be very resource intensive and slow. We do not need such a big resolution for the live preview. Our output buffer will be smaller, for example only 240x240 px. All computations and filter calculations will be executed on this smaller resolution. We can scale up this image later, it will be a little blurred, but that does not matter much for us.
This is how the CamReader.StartCamera method can look like:
public void StartCamera(Dispatcher dispatcher, Canvas fakeCamCanvas, Point outputSize)
{
this.outputSize = outputSize;
?
if (camera != null)
StopCamera(fakeCamCanvas);
?
// Create a PhotoCamera instance
if (PhotoCamera.IsCameraTypeSupported(CameraType.Primary))
camera = new PhotoCamera(CameraType.Primary);
else if (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing))
camera = new PhotoCamera(CameraType.FrontFacing);
else
{
System.Windows.MessageBox.Show("Cannot find a camera on this device");
return;
}
?
// Wait camera initialization before create the buffer image
camera.Initialized += (a, b) =>
{
// Move to UI thread
dispatcher.BeginInvoke(() =>
{
outputBuffer = new int[outputSize.X * outputSize.Y];
previewSize = new Point((int)camera.PreviewResolution.Width, (int)camera.PreviewResolution.Height);
previewBuffer = new int[previewSize.X * previewSize.Y];
}
);
};
?
// Initialize camera
// - we need to initialize VideoBrush to given Canvas, otherwise the stream wouldn't be loaded
var brush = new VideoBrush();
brush.SetSource(camera);
fakeCamCanvas.Background = brush;
}
Reading ARGB data
Now we can design a method for reading ARGB data from the camera:
public int[] GetBufferFromARGB()
{
if (camera != null && previewBuffer != null)
{
// Get preview Image buffer (640x480)
try { camera.GetPreviewBufferArgb32(previewBuffer); }
catch { return null; }
?
// Select outputBuffer pixels (outputSize = smaller than 640x480 preview pixels)
CopyValuesToOutputBuffer();
?
// Swap Red and Blue channel (Silverlight -> XNA's texture)
SwapRedBlueChannel(outputBuffer);
return outputBuffer;
}
return null;
}
This method retrieves the data from the camera to preview buffer (640x480). Then the selected values are copied to the smalled output buffer (see the next paragraph for the method implementation). Output colors are swapped to correct XNA's Texture2D format and finally the output buffer is returned.
The output buffer is a linear array of integer values. Every integer has the compressed info about the whole RGB value of the pixel and its alpha (transparency). In the field outputSize we have the X and Y size of the output image.
Helper methods
The first method is used to copy values from the preview to output buffer. Here you can find quite a complex variant. This implementation automatically crops the image by the correct output ratio. The image is also auto-rotated and scaled.
private void CopyValuesToOutputBuffer()
{
// Copies data from preview buffer (640x480) to smaller output buffer in correct ratio
Point start = Point.Zero;
Point incr = new Point(previewSize.X / outputSize.Y, previewSize.Y / outputSize.X);
?
if (previewSize.X / (float)previewSize.Y > outputSize.Y / (float)outputSize.X)
{
// Preview is wider, output buffer will be cropped at left/right side
start.X = (int)((previewSize.X - outputSize.Y * previewSize.Y / (float)outputSize.X) / 2);
incr.X = (previewSize.X - 2 * start.X) / outputSize.Y;
}
else
{
// Output buffer is wider (preview is taller, crop at top/bottom)
start.Y = (int)((previewSize.Y - outputSize.X * previewSize.X / (float)outputSize.Y) / 2);
incr.Y = (previewSize.Y - 2 * start.Y) / outputSize.X;
}
?
// Inserts values to the output buffer
for (int y = 0; y < outputSize.Y; y++)
for (int x = 0; x < outputSize.X; x++)
{
// Auto flip / rotate the image to output
int sourceX = Math.Min(start.X + y * incr.X, previewSize.X - 1);
int sourceY = Math.Min(previewSize.Y - (start.Y + x * incr.Y) - 1, previewSize.Y - 1);
int i = sourceX + sourceY * previewSize.X;
outputBuffer[x + y * outputSize.X] = previewBuffer[i];
}
}
Note:?We are using the integer division for calculating the increment (for performance reasons). This will work fine if the output buffer is sufficiently smaller than the camera preview. If the output and preview sizes are almost similar, this method may give you poor results.
The next method converts the image buffer into XNA format:
private void SwapRedBlueChannel(int[] buffer)
{
for (int i = 0; i < buffer.Length; ++i)
{
// Converts a packed RGB integer value from Silverlight's to XNA format
// - we need to switch a red and blue channel
buffer[i] = (int)((uint)buffer[i] & 0xFF00FF00)
| (buffer[i] >> 16 & 0xFF)
| (buffer[i] & 0xFF) << 16;
}
}
And finally, we should include to our CamReader class the method for stopping the camera. It will be called when we leave the app, or when the app was switched to background:
public void StopCamera(Canvas fakeCamCanvas)
{
if (camera != null)
camera.Dispose();
camera = null;
previewBuffer = null;
fakeCamCanvas.Background = null;
}
Rendering the live stream
Now we have prepared a helper class CamReader.cs. We would like to integrate this logic into our app.
Lets open a GamePage.xaml.cs file. This is the place where we can write the code for the XNA Framework.
Add these declarations to this file:
Point outputSize;
CamReader camReader;
Texture2D texture;
And add this inicialization logic to method OnNavigatedTo:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//...
// Initialize the camera reader + XNA's texture (of the correct size)
GraphicsDevice device = SharedGraphicsDeviceManager.Current.GraphicsDevice;
outputSize = new Point(240, 240);
texture = new Texture2D(device, outputSize.X, outputSize.Y);
?
camReader = new CamReader();
camReader.StartCamera(this.Dispatcher, cameraDisplayFake, outputSize);
//...
}
Our CamReader object and the texture will be initialized. Note that we are passing a cameraDisplayFake object to our StartCamera method. This is the one component that we have already added into our XAML code.
We can insert a similar logic into OnNavigatedFrom:
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
camReader.StopCamera(cameraDisplayFake);
//...
}
Now we can finally render our photo stream on the display! Method OnDraw is called 30 times per second by default. We obtain a data from CamReader object every frame, then copy this data to the texture and draw this texture.
private void OnDraw(object sender, GameTimerEventArgs e)
{
GraphicsDevice device = SharedGraphicsDeviceManager.Current.GraphicsDevice;
device.Clear(Color.CornflowerBlue);
?
// Get camera values, draw image directly on screen by SpriteBatch (by converting into Texture2D)
int[] buffer = camReader.GetBufferFromARGB();
if (buffer != null)
{
//ApplyEffect(buffer, outputSize, effect); // Applies special filter on image
device.Textures[0] = null;
texture.SetData<int>(buffer);
?
spriteBatch.Begin();
spriteBatch.Draw(texture, new Vector2(0, 0), Color.White);
spriteBatch.End();
}
}
Note:?We can change the interval of the drawing loop from standard 30 frames per second (FPS) to a different value. You only need to change the timer.UpdateInterval in the GamePage contructor into TimeSpan.FromTicks(166666); and the rendering will run at amazing 60 FPS!
Note:?We can combine a XAML code (Silverlight) and the XNA content on one page together. XAML elements can be rendered into texture and displayed even over the content from the XNA. Similar situation is on the WP8, C#/XAML content can be also combined with MonoGame Framework at one page.
Working with image data
XNA is a very powerfull framework for manipulating with images. In this sample we are drawing the texture on a point 0,0 (into the upper left corner), in 100% zoom. We can easily change the rendering code to draw this image two times bigger (= in 200% zoom):
spriteBatch.Draw(texture, Vector2.Zero, null, Color.White, 0f, Vector2.Zero,
2f, SpriteEffects.None, 0);
For this texture - we can also set the scale, the rotation, transparency... Before we convert our buffer into the texture, we can also apply any special filter on these data, for example: grayscale, sepia, lomo, vintage... Anything what we can imagine.
8-bit style renderer
So, we have a raw data from the camera. We do not need to convert them to the texture directly. We can work with this values and, for example, we can draw an extra image for every pixel!
We can make an interesting 8-bit looking app with a real live preview. The power of the XNA Framework will handle it (the slowest Windows Phones can draw around 120x120 non-transparent textures at once, in more than 20 FPS).
This 8-bit effect can look like this:
Note:?These sample images have been generated with some advanced filters. Colors were restricted to a limited palette (for example only 16 specific colors) with a specified treshold. Variants of the Ordered Dithering and Floyd-Steinberg algorithm were applied.
Rendering pixels from images
We will show here the most simple version of this 8-bit renderer. Every pixel obtained from the camera will be drawn as a small image, colored with the RGB data. For example - our sample image will be 6x6 pixels big. If we set the output buffer of the camera to 80x80 pixels, the final image will be 480x480 px big.
You can download the sample image here:
And add this image to your Content project:
Now we can load this image into our app. Add to your GamePage.xaml.cs this declaration:
Modify the OnNavigated method like this:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//...
// Initialize the camera reader + small Sprite texture
sprite = contentManager.Load<Texture2D>("sample_sprite");
outputSize = new Point(80, 80);
camReader = new CamReader();
camReader.StartCamera(this.Dispatcher, cameraDisplayFake, outputSize);
//...
}
The image will be loaded to the sprite variable.
Note:?We are using a standard XNA Content pipeline, the image is converted to the uncompressed .xnb file, then loaded into the texture. We can also load this image directly from .png file.Now we can draw the values. Modify the OnDraw method like this:
private void OnDraw(object sender, GameTimerEventArgs e)
{
//...
// Get camera values, draw image
int[] buffer = camReader.GetBufferFromARGB();
if (buffer != null)
{
// Draw a pixelated 8-bit effect
spriteBatch.Begin();
Draw8BitStyle(spriteBatch, buffer);
spriteBatch.End();
}
}
Our method Draw8BitStyle will simply read the values from the buffer, extract the color data and draw the sprite for every pixel:
private void Draw8BitStyle(SpriteBatch spriteBatch, int[] buffer)
{
// Draw a pixelated 8-bit effect from the buffer
for (int y = 0; y < outputSize.Y; y++)
for (int x = 0; x < outputSize.X; x++)
{
int val = buffer[y * outputSize.X + x];
?
// Convert value into color, draw the sprite
int a = val >> 24;
int b = (val & 0x00ff0000) >> 16;
int g = (val & 0x0000ff00) >> 8;
int r = (val & 0x000000ff);
?
Vector2 position = new Vector2(x * sprite.Width, y * sprite.Height);
spriteBatch.Draw(sprite, position, new Color(r, g, b));
}
}
Our camera stream will look like this now. That is awesome!
Note:?You can find both variants of the algorithm in the attached sample project.
Summary
Remove Category:Draft when the page is complete or near complete
The "platform categories" will be displayed here in preview only - Copy paste relevant categories into text here
Version Hint
Windows Phone: [[Category:Windows Phone]]
[[Category:Windows Phone 7.5]]
[[Category:Windows Phone 8]]
Nokia Asha: [[Category:Nokia Asha]]
[[Category:Nokia Asha Platform 1.0]]
Series 40: [[Category:Series 40]]
[[Category:Series 40 1st Edition]] [[Category:Series 40 2nd Edition]]
[[Category:Series 40 3rd Edition (initial release)]] [[Category:Series 40 3rd Edition FP1]] [[Category:Series 40 3rd Edition FP2]]
[[Category:Series 40 5th Edition (initial release)]] [[Category:Series 40 5th Edition FP1]]
[[Category:Series 40 6th Edition (initial release)]] [[Category:Series 40 6th Edition FP1]] [[Category:Series 40 Developer Platform 1.0]] [[Category:Series 40 Developer Platform 1.1]] [[Category:Series 40 Developer Platform 2.0]]
Symbian: [[Category:Symbian]]
[[Category:S60 1st Edition]] [[Category:S60 2nd Edition (initial release)]] [[Category:S60 2nd Edition FP1]] [[Category:S60 2nd Edition FP2]] [[Category:S60 2nd Edition FP3]]
[[Category:S60 3rd Edition (initial release)]] [[Category:S60 3rd Edition FP1]] [[Category:S60 3rd Edition FP2]]
[[Category:S60 5th Edition]]
[[Category:Symbian^3]] [[Category:Symbian Anna]] [[Category:Nokia Belle]]
Add categories below using category selector.
Adam Lanza Facebook the hobbit Newton Shooting Newtown Shooting Gangnam Style Ryan Lanza Sandy Hook
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.