New Blog at ThreeConstants.com

June 13, 2015

Hi Everyone,

I now have my own website and have created my own blog there. You will find some interesting new posts there. The URL is:

http://threeconstants.com/blog/

Please check it out 🙂

Thanks,

Ian


Kinect Point Cloud Normals Rendering – Part 1

November 21, 2014

That’s a bit of a mouthfull as a title – but it encapsulates all the things I’m hoping to cover in this post and the end goal.

The first step is to create a point cloud using the depth data that we get from the Kinect camera. To do this we’ll need the calibration details we obtained previously (see Kinect V2 Depth Camera Calibration) and the geometry of the “Pinhole Camera”.

If you look up the Wikipedia article on the Pinhole camera model you will find that this model describes the mathematical relationship between the coordinates of a 3D point and its projection onto the image plane. We’re going to use this model to get the X and Y values in the 3D world for a given depth value (the Z co-ordinate in the 3D world); X and Y co-ordinates in the image plane; and the depth camera intriniscs we obtained previously.

This is a picture of the pinhole camera geometry:

Pinhole camera geometry

Pinhole camera geometry

If we look at this from just the X2 plane we see this:

Pinhole camera geometry from the X2 plane

Pinhole camera geometry from the X2 plane

If we look at this we can see two similar triangles, both having parts of the projection line (green) as their hypotenuses. This then leads us to the following equation:

PinholeEquation_2

Which is an expression that describes the relation between the 3D coordinates (x_1,x_2,x_3) of point P and its image coordinates (y_1,y_2) given by point Q in the image plane. To obtain this particular equation we have rotated the coordinate system in the image plane 180° and placed the image plane so that it intersects the X3 axis at f instead of at -f (this is the equation given in the “Rotated image and the virtual image plane” section of the Wikipedia article).

If we re-arrange this equation (using simple algebra) so that everything we know is on one side and the things we’re looking to obtain are on the other side we get:

PinholeEquation_3

And we can re-arrange this again so that the things we’re looking to obtain are on the left-hand side of the formula and the things we know are on the right-hand side of the formula:

PinholeEquation_4

Everything in this equation that has an “x” is in the 3D world (x1=x, x2=y, x3=z in 3D). Everything that has a “y” in the equation is in the image view (y1=x, y2=y in the image view). The Wikipedia article seems to have gone out of its way to make things more complicated!

If you look at the original Pinhole camera model geometry you will notice that the point in the image plane is actually located at the principle point (i.e. the middle of the image) and the point in the View is located at the focal length. The co-ordinates we’ll be obtaining from the image have (0,0) in the top left-hand corner rather than in at the principle point. So we’ll need to do a conversion of our co-ordinates to get it into the correct position for our formula (we’ll simply subtract the principle point).

x_3D = (x_image - camera_principle_point_x) * z_3D / camera_focal_length_x
y_3D = (y_image - camera_principle_point_y) * z_3D / camera_focal_legnth_y

In the above formula z_3D is the depth value at the given (x_image,y_image) point.

That’s all we need to generate our point cloud from our depth image. We could then go on to render that point cloud in 3D if we wanted. This is what the Depth-D3D sample did with version 1.8 of the Kinect SDK. Version 2.0 of the SDK doesn’t yet provide an updated version of this sample.

What I propose to do is calculate the normals for the 3D point cloud and then render that in 2D by mapping the (x,y,z) normal vector values to R-G-B channel values. I’ll do that in Part 2 of this article as I’ve already done a lot just to get here!


Kinect V2 Depth Camera Calibration

November 9, 2014

I wanted to calibrate my Kinect V2 Depth Camera in order to obtain it’s intrinsics. With those I can then create point clouds, normals, etc.. It’s the starting place for a lot of interesting computer vision things. We can calibrate the Kinect V2 Depth Camera in a similar way to how we would calibrate the Colour Camera.

There’s an excellent program called GML C++ Camera Calibration Toolbox which is just what you need to do the calibration. It’s produced by the Graphics and Media Lab at Lomonosov Moscow State University.

Once you’ve downloaded and installed the toolkit it needs a sequence of images of a checkerboard pattern taken from varying positions. There’s a link on their website that will help you with how best to do these sequences. I used the “Infrared-WPF” Kinect Sample to generate my images. You only need to click on the “Screenshot” button on that sample to take the pictures. They’re stored in your user’s Pictures folder as PNGs. The toolkit has no problem loading these.

GML Toolkit Calibrate All

GML Toolkit Calibrate All

Once you’ve run the calibration click on the Results tab to see your Camera Intrinsics:

Calibration Results

Calibration Results

You can see in that picture the camera intrinsics I obtained. These are:

Focal Length (x,y) : 391.096, 463.098
Principle Point (x,y): 243.892, 208.922

On a good calibration the Principle Point would normally be in the middle of the image space. The Depth Image we get from the IR camera has the dimensions 512 x 424 so we would expect a Principle Point of 256.0, 212.0. Ah well! The Toolkit website recommends taking lots and lots of images to improve the calibration. I’m sure you could get better results than I did 🙂 But this is good enough for the things I’m planning next.

In my next post I’ll show you how to generate a point cloud and render it. I’ve already implemented this and have got 30FPS without using shaders. I just need to put together the post to show you how I did it.


Polymorphism and Abstract in C#

November 2, 2014

Let’s say you want to define a base class that other classes will inherit from:

    public class ColorMapBase
    {
        protected byte _alphaValue = 255;
        protected double _yMin = 0;
        protected double _yMax = 1;
        protected SolidColorBrush[] _colormapBrushes;
        public int Length { get; set; }

        public ColorMapBase(int colorMapLength,double yMin, double yMax)
        {
            Length = colorMapLength;
            _yMin = yMin;
            _yMax = yMax;
            CreateBrushes();
        }

        public ColorMapBase()
            :  this(256, 0, 1)
        {
        }

        /// <summary>
        /// Everything that inherits from this class must define its own
        /// version of this function.
        /// </summary>
        public virtual void CreateBrushes()
        {
            throw new NotImplementedException();
        }
    }

We want to make sure that everything that inherits from this class will implement its own version of the CreateBrushes() method. If this method isn’t implemented then we will get a runtime exception every time our inherited class is instantiated. This is one way of ensuring that inherited classes provide an implementation of a method. However, we only find out the problem at runtime. A better solution would be to get an error at compile time. This is where the abstract keyword comes in. Let’s change our method definition of CreateBrushes() to be abstract like this:

        /// <summary>
        /// Everything that inherits from this class must define its own
        /// version of this function.
        /// </summary>
        public abstract void CreateBrushes();

You’ll notice that I’ve replace the virtual keyword with the abstract keyword. This has a similar effect, but we no longer need to provide a default body. The compiler will make sure that anything that inherits from this class implements the CreateBrushes() method.

If you try and compile now you will see the following error:

error CS0513: 'ColorMapBase.CreateBrushes()' is abstract but it is contained in non-abstract class

The only way you can use the abstract keyword within a class is if the class itself is also defined as abstract. So you need to add abstract to your class definition. Our updated class definition now becomes:

    public abstract class ColorMapBase
    {
        protected byte _alphaValue = 255;
        protected double _yMin = 0;
        protected double _yMax = 1;
        protected SolidColorBrush[] _colormapBrushes;
        public int Length { get; set; }

        public ColorMapBase(int colorMapLength,double yMin, double yMax)
        {
            Length = colorMapLength;
            _yMin = yMin;
            _yMax = yMax;
            CreateBrushes();
        }

        public ColorMapBase()
            :  this(256, 0, 1)
        {
        }

        /// <summary>
        /// Everything that inherits from this class must define its own
        /// version of this function.
        /// </summary>
        public abstract void CreateBrushes();
    }

When a class inherits from this base class it must provide an implementation of the CreateBrushes() method. It’s also important that when defining this method it uses the override keyword. See my previous post about the difference between polymorphism in C++ and C# to understand why (see Polymorphism in C++ and C# ). Here’s an example of an inherited class:

    public class ColorMapHot : ColorMapBase
    {
        public ColorMapHot(int colorMapLength, double yMin, double yMax)
            : base(colorMapLength, yMin, yMax)
        {
             // any other initialisation can go here
        }

        public override void CreateBrushes()
        {
            // TODO: implement functionality here....
        }
    }

Parallel Processing and Lambda expressions in C++11 – Part 2

October 24, 2014

If you’ve made the changes to the code from Part 1 then you already have code that should be working dramatically faster. In the next steps I’m going to use C++ templates to further enhance the code. I love C++ templates! I try and use them whenever I can. One of the great things about them is that only the code that is actually used gets generated and compiled. And with C++11 you’ve got the ability to use lambda functions in templates. This is useful if you’re using STL. It’s also useful for us here.

Before I do that I want to show you the combined version of the Concurrency::for_each I mentioned in my last post. I’ve included the lambda expression as the last parameter rather then putting it into a separate variable first (as I said I would):

void CDepthBasics::ProcessDepth(INT64 nTime, const UINT16* pBuffer, int nWidth, int nHeight, USHORT nMinDepth, USHORT nMaxDepth)
{
    // Skipped the bit of code about the Status Message.........

    // Make sure we've received valid data
    if (m_pDepthRGBX && pBuffer && (nWidth == cDepthWidth) && (nHeight == cDepthHeight))
    {
        RGBQUAD* pRGBX = m_pDepthRGBX;

		Concurrency::parallel_for(0u, (UINT)cDepthHeight, [&](UINT y)
		{
			const UINT16* pIn = pBuffer + y * nWidth;
			RGBQUAD* pOut = pRGBX + y * nWidth;
			for (UINT x = 0; x < nWidth; ++x, ++pIn, ++pOut)
			{
				UINT16 depth = *pIn;
				BYTE intensity = static_cast<BYTE>((depth >= nMinDepth) && (depth <= nMaxDepth) ? (depth % 256) : 0);
				pRGBX->rgbRed = intensity;
				pRGBX->rgbGreen = intensity;
				pRGBX->rgbBlue = intensity;
			}
		});
        // Code continues below here.....

This is going to help with understanding what I’m going to do next.

At the top of DepthBasics.cpp, just after all the headers have been included, create the following template:

template <typename TIn, typename TOut, typename TFunc>
inline void parallel_for_each_pixel(
	const TIn* pSrc,
	const UINT nWidth,
	const UINT nHeight,
	TOut* pDst,
	TFunc func)
{
	Concurrency::parallel_for(0u, nHeight, [&](UINT y)
	{
		const TIn* pIn = pSrc + y * nWidth;
		TOut* pOut = pDst + y * nWidth;
		for (UINT x = 0; x < nWidth; ++x, ++pIn, ++pOut)
			*pOut = func(*pIn);
	});
}

It will really help you to understand what this is doing if you compare it with the updated code I’ve shown at the start of this post. You’ll notice that I’ve kept all the variables UINT as before. But I’ve also added 3 new parameters: pSrc, pDst and func. These are of types TIn, TOut and TFunc respectively. The beauty of templates is that we can use the same template with different types and the compiler will work out the rest. func is actually going to be a lambda function, as I’ll show you in a minute. I’m going to use something called a Higher-order Lambda Function.

With this new template defined we’re going to change our pixel processing to the following:

void CDepthBasics::ProcessDepth(INT64 nTime, const UINT16* pBuffer, int nWidth, int nHeight, USHORT nMinDepth, USHORT nMaxDepth)
{
    // Skipped the bit of code about the Status Message.........
 
    // Make sure we've received valid data
    if (m_pDepthRGBX && pBuffer && (nWidth == cDepthWidth) && (nHeight == cDepthHeight))
    {
        RGBQUAD* pRGBX = m_pDepthRGBX;
 
		parallel_for_each_pixel(pBuffer, cDepthWidth, cDepthHeight, pRGBX, [&](UINT16 depth) -> RGBQUAD
		{
			RGBQUAD quad;
			BYTE intensity = static_cast<BYTE>((depth >= nMinDepth) && (depth <= nMaxDepth) ? (depth % 256) : 0);
			quad.rgbRed = intensity;
			quad.rgbGreen = intensity;
			quad.rgbBlue = intensity;
			return quad;
		});
        // Code continues below here.....

If you look at the syntax of the lambda function at the end, you’ll see that we take in a UINT16 depth value (in millimetres) and then transform this into an RGBQUAD value. This is what we were doing at the beginning, but now we’re doing it in a much faster way with parallel processing. Because we’re using a lambda function that then goes on to be part of another lambda function this is called a Higher-order Lambda Function. Thanks to templating we have something that I think (please feel free to disagree!) is much easier to read and use. We’ve also opened up the way for us to do other transformations in a parallel way – such as using Color Maps or creating a Normal Map. I’m planning on doing articles about these in the future. Watch this space 🙂


Parallel Processing and Lambda expressions in C++11 – Part 1

October 24, 2014

One of the exciting new features introduced with C++11 is lambda expressions. .NET has had these for a while so its nice to be able to use them in C++ too.

A common task in video processing and graphics is to perform some operation over an image. When doing this you’ll typically process the image buffer a row at a time as this speeds up processing. Microsoft have introduced the Concurrency Runtime with their C++11 compiler. This gives you the ability to process the image in a parallel fashion. If you’ve got Visual Studio 2013 and have installed the help, just do a search for “Concurrency Runtime”.

What I’d like to do is take one of the Kinect Native Samples that has some basic video processing in C++. I’ll then convert it to parallel processing using the Concurrency Runtime and some lambda functions. I’m hoping by the end to have something that will look straightforward at the high level.

The sample I’m starting with is the DepthBasics-D2D Native Sample. If you open up the DepthBasics.cpp file and go up to the top, add the following code underneath the #include “stdafx.h” to include the Concurrency Runtime:

#include "stdafx.h"

#pragma warning(push)
#pragma warning(disable:6255)
#pragma warning(disable:6263)
#pragma warning(disable:4995)
#include "ppl.h"
#pragma warning(pop)

You’ll notice I’m hiding the warning messages you’ll get when you include ppl.h. I like to keep my compilations free of warnings. If you don’t mind the warnings then don’t bother with the #pragma statements.

The bit of code we’re going to be changing is in the ProcessDepth method. Here’s a cut down version of the method so you can see the bit we’ll be changing:

void CDepthBasics::ProcessDepth(INT64 nTime, const UINT16* pBuffer, int nWidth, int nHeight, USHORT nMinDepth, USHORT nMaxDepth)
{
    // Skipped the bit of code about the Status Message.........

    // Make sure we've received valid data
    if (m_pDepthRGBX && pBuffer && (nWidth == cDepthWidth) && (nHeight == cDepthHeight))
    {
        RGBQUAD* pRGBX = m_pDepthRGBX;

        // end pixel is start + width*height - 1
        const UINT16* pBufferEnd = pBuffer + (nWidth * nHeight);

        while (pBuffer < pBufferEnd)
        {
            USHORT depth = *pBuffer;

            // To convert to a byte, we're discarding the most-significant
            // rather than least-significant bits.
            // We're preserving detail, although the intensity will "wrap."
            // Values outside the reliable depth range are mapped to 0 (black).

            // Note: Using conditionals in this loop could degrade performance.
            // Consider using a lookup table instead when writing production code.
            BYTE intensity = static_cast<BYTE>((depth >= nMinDepth) && (depth <= nMaxDepth) ? (depth % 256) : 0);

            pRGBX->rgbRed   = intensity;
            pRGBX->rgbGreen = intensity;
            pRGBX->rgbBlue  = intensity;

            ++pRGBX;
            ++pBuffer;
        }
        // Code continues below here.....

This code is going through the input depth buffer (which contains 16-bit unsigned short integer values of the depth in millimetres) one value at a time. It is then converting them to an 8-bit byte value (0-255) that will correspond to the intensity. By putting the same 8-bit value into the red, green and blue channels we’ll end up with a grayscale image. If you compile and run the sample that’s what you’ll see.

Our first change is to split this processing up into rows and then to execute the same process on the rows in parallel. We can do this because it doesn’t matter in which order we process the rows. To accomplish this we’ll use the Concurrency::parallel_for method and a lambda expression for our row processing. Here’s the change:

void CDepthBasics::ProcessDepth(INT64 nTime, const UINT16* pBuffer, int nWidth, int nHeight, USHORT nMinDepth, USHORT nMaxDepth)
{
    // Skipped the bit of code about the Status Message.........

    // Make sure we've received valid data
    if (m_pDepthRGBX && pBuffer && (nWidth == cDepthWidth) && (nHeight == cDepthHeight))
    {
        RGBQUAD* pRGBX = m_pDepthRGBX;

		auto rowLambda = [&](UINT y)
		{
			const UINT16* pIn = pBuffer + y * nWidth;
			RGBQUAD* pOut = pRGBX + y * nWidth;
			for (UINT x = 0; x < nWidth; ++x, ++pIn, ++pOut)
			{
				UINT16 depth = *pIn;
				BYTE intensity = static_cast<BYTE>((depth >= nMinDepth) && (depth <= nMaxDepth) ? (depth % 256) : 0);
				pRGBX->rgbRed = intensity;
				pRGBX->rgbGreen = intensity;
				pRGBX->rgbBlue = intensity;
			}
		};
		Concurrency::parallel_for(0u, (UINT)cDepthHeight, rowLambda);
        // Code continues below here.....

C++11 has introduced the new auto variable type. This is similar to the var variable type in C#. Here I’m assigning my row lambda expression to the auto variable rowLambda. I’m doing this to (hopefully) make it easier to understand what’s going on. Later on (in part 2) I won’t be using an interim variable – I’ll simply put the lambda expression itself as the last parameter of the parallel_for.

One important thing to note is that the parameters for the parallel_for and the lambda function must have exactly the same type. Here I’m using UINT. Note how I cast the second parameter to a UINT because it’s actually a signed int. If you don’t do this you’ll get a compiler error that is difficult to interpret – but this is what it will be trying to tell you, in it’s own special way 🙂

In my next post I’ll complete the transformation of this code.


Polymorphism in C++ and C#

October 16, 2014

I went for an interview for a C++ job one time and they showed me the following code and asked me what the output would be:

class description
{
protected:
	char * _information;
public:
	description(char *info) : _information(info){};

	virtual void print()
	{
		printf("%s\n", _information);
	}
};

class sphere : public description
{
protected:
	double _radius;
public:
	sphere(char *info, double radius)
		:description(info), _radius(radius)
	{};
	void print()
	{
		description::print();
		printf("radius %g\n", _radius);
	}
};

class cube : public description
{
protected:
	double _length;
public:
	cube(char *info, double length)
		:description(info), _length(length)
	{};
	void print()
	{
		description::print();
		printf("edge %g\n", _length);
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	sphere beachBall("Beach Ball", 20.0);
	cube rubiksCube("Rubiks Cube", 10.0);
	description *shapes[] = { &beachBall, &rubiksCube };
	beachBall.print();
	rubiksCube.print();
	for (int i = 0; i < sizeof(shapes) / sizeof(shapes[0]); i++)
	{
		shapes[i]->print();
	}
}

Really this is a question about inheritance and polymorphism in C++. The class description is the base class and the classes sphere and cube inherit from it. Because the description has declared it’s method print() as virtual a vtable is created under the hood for that class and method. Any class that derives from description is allowed to override it’s definition of print() and use its own. The definition of the print() method must exactly match the base class’ print(). Whenever this happens the overriden method is put in the base class’ vtable. In this way it is always called instead of the base class print().

The output from the program is:

Beach Ball
radius 20
Rubiks Cube
edge 10
Beach Ball
radius 20
Rubiks Cube
edge 10

Now on to C#. Here’s the same question, but in the .NET world:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShapesTest
{
    public class description
    {
        protected string _information;
        public description(string info)
        {
            _information = info;
        }

        public virtual void print()
        {
            Console.WriteLine(_information);
        }
    }

    class sphere : description
    {
        protected double _radius;
        public sphere(string info, double radius)
            : base(info)
        {
            _radius = radius;
        }
        public void print()
        {
            base.print();
            Console.WriteLine("radius {0:G}", _radius);
        }
    }

    public class cube : description
    {
        protected double _length;
        public cube(string info, double length)
            : base(info)
        {
            _length = length;
        }
        public void print()
        {
            base.print();
            Console.WriteLine("edge {0:G}", _length);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            sphere beachBall = new sphere("Beach Ball", 20.0);
            cube rubiksCube = new cube("Rubiks Cube", 10.0);
            description[] shapes = { beachBall, rubiksCube };
            beachBall.print();
            rubiksCube.print();
            for (int i = 0; i < shapes.Length; i++)
            {
                shapes[i].print();
            }
        }
    }
}

The output from this program is:

Beach Ball
radius 20
Rubiks Cube
edge 10
Beach Ball
Rubiks Cube

It’s different! What’s going on?!

When you compile the program you’ll notice 2 warning messages that come up:

warning CS0114: 'ShapesTest.sphere.print()' hides inherited member 'ShapesTest.description.print()'
warning CS0114: 'ShapesTest.cube.print()' hides inherited member 'ShapesTest.description.print()'

Instead of overriding the base class’ print() method it has hidden it with it’s own. This means that when we recast the objects as description objects we get the base class version of print(). To get the same behaviour that we saw in C++ we have to use the override keyword when giving our method definitions. For both sphere and cube the print() method needs to be defined as:

        public override void print()

With that change done you will get the same output as the C++ code.

Unfortunately in my interview I gave the C# answer for a C++ question! I was gutted when I realised what I’d done. I kept muttering in the interview “But there’s no override. There’s no override statement”. I thought it was a trick question, as most interview questions are. So I’ve put it here as a reminder for me – and maybe it will help someone else too.


Developing with kinect v2 on a MacBook Pro

September 28, 2014

I came across the following article on the Kinect For Windows Blog:

Developing with Kinect v2 on a mac

I own a MacBook Pro on which I dual-boot between Mac OS-X and Windows 8.1. I’ve split the hard disk in two and have allocated one half to each of those operating systems. When I saw the title of the blog I got quite excited about the possibility of using the Kinect v2 sensor from a Mac OS-X environment. Would it use OpenGL? Would it use any of the open source libraries?

However, as I read the article in depth, I realised it was simply talking about using a Kinect v2 sensor on a Mac that is running Windows 8.1. Not quite the same as running OS-X. Nonetheless I decided to give it a go.

I bought my MacBook Pro laptop last summer and it has 2 USB slots. It turns out that both of these are USB3 slots. This is good news when it comes to connecting the Kinect v2 sensor. I booted my Mac into Windows 8.1 and then installed the Kinect v2 SDK. When I plugged in my Kinect v2 Sensor everything worked! I was very pleased – in fact it was a much better experience than trying to connect the same sensor to my desktop PC. Now I am doing all my Kinect development on my Apple Mac and am getting good FPS.


Kinect For Windows v2 Sensor – Now it works!

September 27, 2014

I did say in my last post that I would let you know how I got on with ordering a compatible USB3 card for my PC. I found one that matched the list and ordered it from Amazon. It took a few weeks to arrive but when I plugged it in to my PC it all worked successfully! What a relief. I was disappointed to find that the SDK at the time didn’t include Kinect Fusion – but the latest version available now does include it.


Kinect For Windows v2 Sensor – First Impressions

July 19, 2014

This week my Kinect For Windows v2 Sensor arrived. I had pre-ordered it from Microsoft. It consists of 3 main parts: The sensor itself, a mains power supply, and a USB3/Kinect Sensor connection box.

The PC I want to use it on is running Windows 8.1 (64-bit) on a fairly modern AMD motherboard with an NVIDIA 610 graphics card (I’m going to upgrade this graphics card so I can run Kinect Fusion on it and do some 3D scanning). This meets the system requirements specified by Microsoft. I downloaded the Kinect for Windows SDK 2.0 Public Preview from here: http://www.microsoft.com/en-us/download/details.aspx?id=43661 . I then ran the installer before connecting my sensor, restarted the PC, and plugged everything into my USB3 port on my computer. When I fired up Kinect Studio and “connected” to my device to monitor it, nothing appeared on any of the streams. I can’t tell you how disappointed I was at this point! Out-of-the-box it doesn’t work 😦

Having tracked down the support forum I found the “Common problems” section. And that’s where I found the issue. The Kinect For Windows v2 Sensor only works on Intel or Renesas USB3 devices! If that’s the case, surely they should put that as part of the system requirements too? If you trawl through their forums there is a post where they list the USB3 cards that have been found to work with the developer preview version of the sensor. Here’s a link: Confirmed List of USB 3.0 PCI-e cards/Laptops/configurations which work for Kinect v2 (during preview).

So I ordered one of the recommended cards from Amazon and that should hopefully arrive this week. I’ll let you know how I get on.


Create your own website, free on WordPress.com.Create your own website.
Start free