Patrick Bader's Blog a blog about software development

18Apr/111

Negating Booleans in C#

I was recently asked whether there is a short way to negate the value of a boolean variable. Surely you can simply asign the result of the negated variable to itself:

bool a;
[...]
a = !a;

So what is the problem here? Absolutely nothing of course. But now think of some common use case, for example in UI code:

MyForm.MyCheckbox.Checked = !MyForm.MyCheckbox.Checked;

Now, can you think of a way in C# to only write the variable name once?

There is indeed a way using compound assignment operators. The following code does the negation:

MyForm.MyCheckbox.Checked ^= true;

Well, I admit that this is not the clearest solution to the problem of negation, but it surely solves it. There is also an advantage or difference between this code and the initial. In the initial code "MyForm.MyCheckbox.Checked" will be evaluated twice and in the latter only once. Eric Lippert already wrote about this in his Blog.
Whether you will be using this obscure syntax or not is up to you. I for myself favour code where the intentions of the author are obvious which clearly is not the case here.

Tagged as: , 1 Comment
9Dec/100

foreach and lambdas in C#

I recently encountered a bug in a C# application I was writing and it took me quite a while to fix. The situation is as follows: I had an array with some kind of data I wanted to be processed by a thread pool. So my first approach was iterating over the array with a foreach loop and passing a lambda to the thread pool as argument. The code looked like this:

1
2
3
4
5
6
7
8
9
object someState;
int items[] = {1, 2, 3, 4, 5};
 
foreach(int item in items)
{
	ThreadPool.QueueUserWorkItem((unused) => {
		System.Console.WriteLine(item);
	});
}

so, what's wrong with this code? Without the thread pool, nothing at all, it runs just fine, but with the thread pool the following text was written to the console:

5
5
5
5
5

When I saw the output, I was like: "what the hell is going wrong here?". The problem with the code above is: lambdas in C# capture their variables by-reference. For each iteration of the loop, a new value will be assigned to the item variable, an since this variable is captured by the lambda by-reference, all WorkItems in the thread pool will be influenced by the assignment of the loop. In my case the loop run completely, before the first WorkItem was executed. So the value of item was always the value which was last assigned by the loop.
A quick fix for this was assigning the loop variable to a local variable in the for loop:

1
2
3
4
5
6
7
8
9
10
object someState;
int items[] = {1, 2, 3, 4, 5};
 
foreach(int item in items)
{
        int localItem = item;
	ThreadPool.QueueUserWorkItem((unused) => {
		System.Console.WriteLine(localItem);
	});
}

so, each lambda references its own local variable. Another solution is to pass the item explicitly to each WorkItem:

1
2
3
4
5
6
7
8
9
10
object someState;
int items[] = {1, 2, 3, 4, 5};
 
foreach(int item in items)
{
	ThreadPool.QueueUserWorkItem((localItem) => {
		System.Console.WriteLine(localItem);
	},
        localItem);
}

The disadvantage here is: You have to make the variable explicitly available in the lambda, by passing it as a parameter.

Side note:
The upcoming C++0x release will also contain lambda expressions but it will allow you to specify whether a variable shall be bound by value or reference.

Filed under: C#, Uncategorized No Comments
12Sep/103

Master Thesis Presentation [2nd Update]

This time a posting in German since the presentation will be held in German:
Am Dienstag den 14.09.2010 werde ich eine Präsentation über meine Master Thesis mit dem Titel: "GPU-unterstützte Bildverarbeitung und Bilderkennung
im Kontext einer Multi-Touch-Anwendung" halten.
Der Vortrag findet an der Hochschule der Medien in Stuttgart statt.
Beginn ist 10:30 Uhr und der Vortrag wird ca. 45 Minuten dauern.
[Update]Das ganze findet in Raum 135 statt.[/Update]
Interessierte sind herzlich eingeladen teilzunehmen.

[2. Update]Der Vortrag ist als Videostream hier abrufbar.[/2. Update]

7Sep/102

it’s about time…

I finally finished my Master's Thesis about GPU based image processing in the context of a multi-touch application. As I wrote in older posts I have built a prototype of an LCD based multi-touch screen. The PlayStation Eye camera is used to track blobs and fiducials using IR light and the images from the cam are processed on the GPU to extract positions, IDs, etc. For the implementation which will possibly be published in a later post, I used OpenCL, which allows programming on various heterogenous hardware. The visualization is done using solely OpenGL 3.2 Core Profile.

The thesis in in german and can be downloaded here. Feel free to read and comment it.

23Jan/1024

Adjusting screen brightness with shortcuts

A while ago I installed Windows 7 on my Sony laptop. The good thing about it is it runs quite stable and most things just work. The bad thing some of the shortcuts with the blue "Fn" key don't work anymore. Adjusting the volume works perfectly fine, but setting the brightness of the LCD backlight does not.
Since Sony is not going to release any Windows 7 64 bit drivers for my model, I finally decided to write a little programm myself. This took several hours of searching for the right API to use. There are actualy three different ones:

  1. The first API I tried is called the Monitor Configuration of the Win32 API but did not work for my laptop (some kind of I2C transmission error occured)
  2. The Backlight Control Interface using IOCTL was the first approach that worked for me, but getting the current brightness is not supported on newer Windows versions
  3. So I ended up using WMI which is available for .NET and works surprisingly quite well.

Further usage information and a downloadable binary can be found on my Projects page
If you encounter bugs or have any suggestions please do not hesitate and give some feedback.

3Nov/091

Blob Detection Reloaded

Today, I finally got the 50 Osram SFH 4350 LEDs I ordered. These shine at 850 nm, a wavelength at which the PS3 Eye is quite sensitive. The first thing to do with these LEDs was to test them somehow. Since I haven't got an IR bandpass filter for the cam (I ordered one from ebay), I had to test them without the filter.

So how did I run the test? A few days ago I ordered a sample of some Plexiglass EndLighten, which is available here. It's a special glass that shines diffuse when light shines from the side into the sheet. The final setup was simple: I connected 8 LEDs in row with a 1 ohm resistor and powered the setting with 12 Volts, the LEDs were attached to the Plexiglass and and everything was filmed with the cam.

A Screenshot with blobs detected on my hands is below, the other blobs in the surface come from a screw clamp.

blob_detection_hand

stay tune for some more news in the near future 😉

2Nov/090

Paper “On Language Support for Application Scalability”

I finally finished my work on a paper for the lecture "Ultra-large scale Sites". The paper is about programming language requirements for building highly scalable systems.

The paper can be downloaded here.

19Oct/090

Upgrading PS3 Eye Camera and Blob Detection

As noted in my last posting, the images of the modified Eye camera were quite blurry. That was the case because the IR filter was missing and so the camera got out of focus. I was asking myself for the reason, since the filter is not a lense at all. Glass has a different refraction index than air resulting in diagonal rays becoming offset. I tried to visualize the effect in the following picture:

Camera_offset

More on that can be found on wikipedia.

I have finally managed to correct this issue. I had to find a replacement for the filter. It had to be of glass or a similar material with the same width as the filter. Quite tough to find a piece of glass or plastic with a depth of about a millimeter. Suprisingly the cap of a CD case did the job as a filter replacement. I first sawed a piece off and afterwards filed it into shape.

The room was quite dark but the results are  better than without the replacement, I think:

PS3 Eye Capture with IR filter replacement

PS3 Eye Capture with IR filter replacement

Now the second part of this posting, blob detection. Blob detection is about finding bright or dark spots in an image. I used some kind of global flood fill algorithm to find the blobs. Sadly I was not able to programm this part in the pixel shader so I implemented an algorithm on the CPU. On my laptop CPU power is fairly restricted so it took me a few attempts to do blob detection at 60 fps. The algorithm is a scanline algorithm which searches for horizontal lines of bright pixels. After the complete image has been scanned, one or more connected lines become a blob. The blob center is the barycenter of the pixels, at the moment without regard of their brightness. I have to test this algorithm for robustness, but can already give you a first impression:

A first test of blob detection. The red dots are centers of detected blobs.

A first test of blob detection. The red dots are centers of detected blobs.

Hope I could help anyone with the camera focus problem. Maybe I release the source code of the project when it is out of experimental stage, or to say it straight: When it's a bit less messy. 😉

Tagged as: No Comments
15Oct/090

Edge detection with PS3 Eye cam

I recently bought a Playstation Eye camera because I would like to get my hands on multitouch surfaces. At first, I disassembled my camera according to Peter Kirn's instruction videos to remove the IR filter. I was quite lucky since I bought the cam at Saturn in Germany and did not know that there are two versions of the cam. The filter of the one mostly sold in the USA can be removed easily, as seen in the video. The other version cannot be modified that way, so the complete lens has to be exchanged.
With the help of Alex Popovich's Driver which nicely works on Windows 7 64 bit edition and two days of learning some Direct3D programming, I was finally able to render the captured images on screen. After some experimenting with HLSL I had my very first realtime edge detector running.
The detection is quite simple, only a simple 3x3 filter matrix is applied to each frame. Here is the matrix:

0.0,   -1.0,    0.0,
F=  -1.0,    4.0,   -1.0,
0.0,   -1.0,    0.0

And some threshold operations afterwards leads to these results:

Screenshot without edge detection

Screenshot with edge detection enabled

As you can see, the picture is quite blurry which has a negative impact on corner detection. That is because of the missing IR filter, now I am unable to set the focus right, maybe I can put a piece of glass into the lens to correct the error.

29Aug/090

… but how is it called in English?

English is not my mother tounge as you can surely guess. So I often have to translate some words from German to English and vica verse or look up words I don't know. I had a nice tool called Babylon Translator. It was just a trial version and ceased to work after the trial period. After living without a translation program for some years and having to look up words in online dictionaries I decided to write a translation program myself since I did not want to open my browser everytime I wanted to look up a word.
The result of a few C# programming hours was a little tool called Translator. At the moment it uses the dictionary at Leo.org to look up words maybe some more dictionaries will follow.
You can find the tool and source code here.

Have fun testing it and don't forget to give some feedback