Category Archives: Knowledge Base

Remote Android emulator

Update: According to a comment, this does no longer work due to cryptographical authentication!

I often use the Android emulator to check my apps with different display configurations and to stress-test them. But the problem is that it is really slow on my development laptop. So I installed the Android emulator on my desktop PC running Windows and connect to it over my LAN. The major advantage is that you can continue using your development machine while a “server” deals with emulating – one could even emulate several devices at once and still continue programming.

The approach in a nutshell: Forward the emulator’s port so that it is accessible in the local network. Then connect the ADB to it.

On your desktop – the “server”:

  1. Store the executable of Trivial Portforward on the desktop system (e.g. directly in C:\trivial_portforward.exe).
  2. Create a virtual device to emulate (HowTo) and name it “EmulatedAndroid”.
  3. Create a batch file:
    <your-android-sdk-path>\tools\emulator -avd EmulatedAndroid &amp; 
    echo 'On the development machine: adb kill-server and then: adb connect <desktop-pc-name>:5585'
    C:\trivial_portforward 5585 127.0.0.1 5555

  4. If you execute this batch file on your desktop PC, it will open the emulator with the specified virtual device.

Now on your laptop – the “client”:

  1. Now – given that both systems are in the same network – you can connect to the emulator from your laptop by typing in a terminal:
    adb kill-server
    adb connect <desktop-pc-name>:5585

  2. Now you can upload apps, access the logcat and execute adb commands on your remote emulator like on any other Android device. And all without performance impairments on your workstation.
  3. If you are experiencing communication losses, increase the emulator timeout in the eclipse settings to maybe 5000 ms (Window → Preferences → Android → DDMS → ADB connection time out (ms)).

Hello World for Android computer vision

Every once in a while I start a new computer vision project with Android. And I am always facing the same question: “What do I need again to retrieve a camera image ready for processing?”. While there are great tutorials around I just want a downloadable project with a minimum amount of code – not taking pictures, not setting resolutions, just the continuous retrieval of incoming camera frames.

So here they are – two different “Hello World” for computer vision. I will show you some excerpts from the code and then provide a download link for each project.

Pure Android API

The main problem to solve is how to store the camera image into a processable image format – in this case the android.graphics.Bitmap .

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
		int height) {
	if(camera != null) {
		camera.release();
		camera = null;
	}
	camera = Camera.open();
	try {
		camera.setPreviewDisplay(holder);
	} catch (IOException e) {
		e.printStackTrace();
	}
	camera.setPreviewCallback(new PreviewCallback() {

		public void onPreviewFrame(byte[] data, Camera camera) {
			System.out.println("Frame received!"+data.length);
			Size size = camera.getParameters().getPreviewSize();
			/*
			 * Directly constructing a bitmap from the data would be possible if the preview format
			 * had been set to RGB (params.setPreviewFormat() ) but some devices only support YUV.
			 * So we have to stick with it and convert the format
			 */
			int[] rgbData = convertYUV420_NV21toRGB8888(data, size.width, size.height);
			Bitmap bitmap = Bitmap.createBitmap(rgbData, size.width, size.height, Bitmap.Config.ARGB_8888);
			/*
			 * TODO: now process the bitmap
			 */
		}
	});
	camera.startPreview();
}

Notice the function convertYUV420_NV21toRGB8888() which is needed since the internal representation of camera frames does not match any supported Bitmap format.

Using OpenCV

This is even more straight-forward. We just use OpenCV’s JavaCameraView. If you are new to Android+OpenCV, here is a good tutorial for you.

cameraView = (CameraBridgeViewBase) findViewById(R.id.cameraView);
cameraView.setCvCameraViewListener(this);

OpenCV Image Watch for cv::Matx

When developing for/with OpenCV using Visual Studio, the Image Watch plug-in is very useful. However, it does not support the better-typed cv::Matx types (e.g. cv::Matx33f which is the same as cv::Matx<float,3,3> ). Here is how I made use of Visual Studio’s debugger type visualizers to customize the plugin:

  1. Go to the folder <VS Installation Directory>\Common7\Packages\Debugger\Visualizers\ and create a new file called Matx.natvis
  2. Open the file and insert the following:
    &lt;?xml version="1.0" encoding="utf-8"?&gt;
    &lt;!-- Philipp Hasper, http://www.hasper.info--&gt;
    &lt;AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010"&gt;
    &lt;UIVisualizer ServiceId="{A452AFEA-3DF6-46BB-9177-C0B08F318025}" Id="1" MenuName="Add to Image Watch"/&gt;
    
    &lt;Type Name="cv::Matx&amp;lt;*,*,*&amp;gt;"&gt;
    &lt;UIVisualizer ServiceId="{A452AFEA-3DF6-46BB-9177-C0B08F318025}" Id="1" /&gt;
    &lt;/Type&gt;
    
    &lt;Type Name="cv::Matx&amp;lt;*,*,*&amp;gt;"&gt;
    &lt;DisplayString Condition='strcmp("float", "$T1") == 0'&gt;{{FLOAT32, size = {$T3}x{$T2}}}&lt;/DisplayString&gt;
    &lt;DisplayString Condition='strcmp("double", "$T1") == 0'&gt;{{FLOAT64, size = {$T3}x{$T2}}}&lt;/DisplayString&gt;
    
    &lt;Expand&gt;
    &lt;Synthetic Name="[type]" Condition='strcmp("float", "$T1") == 0'&gt;
    &lt;DisplayString&gt;FLOAT32&lt;/DisplayString&gt;
    &lt;/Synthetic&gt;
    &lt;Synthetic Name="[type]" Condition='strcmp("double", "$T1") == 0'&gt;
    &lt;DisplayString&gt;FLOAT64&lt;/DisplayString&gt;
    &lt;/Synthetic&gt;
    
    &lt;Item Name="[channels]"&gt;1&lt;/Item&gt;
    &lt;Item Name="[width]"&gt;$T3&lt;/Item&gt;
    &lt;Item Name="[height]"&gt;$T2&lt;/Item&gt;
    &lt;Item Name="[data]"&gt;(void*)val&lt;/Item&gt;
    &lt;Item Name="[stride]"&gt;$T3*sizeof($T1)&lt;/Item&gt;
    &lt;/Expand&gt;
    
    &lt;/Type&gt;
    
    &lt;/AutoVisualizer&gt;
  3. You do not even have to restart Visual Studio. Just start a new debugging session and you can look at your cv::Matx types in a nice little graphical window.

Image Watch for cv::Matx

More about customizing the Image Watch plug-in can be found on the official Image Watch documentation page.

OpenCV and Visual Studio: Empty Call Stack

For a couple of years I have used OpenCV for Android and developed with Eclipse. But a while back I started a bigger project which will run on stationary machines so I began to learn how to use Visual Studio 2013. The integration of OpenCV 2.4.8 was fairly easy and I was quickly able to run my code.

(Just as a service since the library names on the given site are outdated – here are all the names for easy copying:)

opencv_calib3d248.lib
opencv_contrib248.lib
opencv_core248.lib
opencv_features2d248.lib
opencv_flann248.lib
opencv_gpu248.lib
opencv_highgui248.lib
opencv_imgproc248.lib
opencv_legacy248.lib
opencv_ml248.lib
opencv_nonfree248.lib
opencv_objdetect248.lib
opencv_ocl248.lib
opencv_photo248.lib
opencv_stitching248.lib
opencv_superres248.lib
opencv_ts248.lib
opencv_video248.lib
opencv_videostab248.lib
opencv_calib3d248d.lib
opencv_contrib248d.lib
opencv_core248d.lib
opencv_features2d248d.lib
opencv_flann248d.lib
opencv_gpu248d.lib
opencv_highgui248d.lib
opencv_imgproc248d.lib
opencv_legacy248d.lib
opencv_ml248d.lib
opencv_nonfree248d.lib
opencv_objdetect248d.lib
opencv_ocl248d.lib
opencv_photo248d.lib
opencv_stitching248d.lib
opencv_superres248d.lib
opencv_ts248d.lib
opencv_video248d.lib
opencv_videostab248d.lib

But then I experienced a strange behaviour: Every time an exception or assertion was thrown inside of an OpenCV method, I would have no clue what happened since the call stack had only four entries: Something about KernelBase.dll, msvcr120d.dll, opencv_core248.dll and the last one “Frames below may be incorrect and/or missing, no symbols loaded for opencv_core248d.dll“.

Frames below may be incorrect and/or missing, no symbols loaded for opencv_core248d.dll

Upon further examination (clicking on the opencv_core248d.dll entry) Visual Studio revealed that the .pdb file was missing: it said “opencv_core248d.pdb not loaded” and “opencv_core248d.pdb could not be found in the selected paths“.

opencv_core248d.pdb not loaded. opencv_core248d.pdb could not be found in the selected paths

I quickly found some .pdb files in C:\opencv248\build\x86\vc12\staticlib but since they did not match the .dlls, they did not work either. So what to do? Essentially we have to build OpenCV ourselves but we will leave out any 3rd party libraries since we only want to debug, not to have fast code (of course you can build a complete version but I didn’t do it in order to save time). In the following I will describe only the basic steps, for a full documentation including pictures and how to add performance-improving 3rd party libraries visit the original tutorial.

  1. I assume you have an OpenCV copy, e.g. under C:\opencv248\ . The folder contains a build and a sources folder.
  2. Install CMake
  3. Start CMake (cmake-gui). It should be in your start menu. Enter C:\opencv248\sources in the first field (“Where is the source code:”) and a freely chosen path e.g. C:\opencv248\ownBuild\ in the second one.
  4. Press “Configure” and select your compiler – for Visual Studio 2013 32-bit it would be “Visual Studio 12”. I then ignored a warning about Java AWT and python missing and pressed the “Generate” button.
  5. Wait for the process to finish, then open C:\opencv248\ownBuild\OpenCV.sln. Build both Debug and Release configuration which should take some time.
  6. After the build, go into C:\opencv248\ownBuild\bin. There are two folders containing all files you will need. Now you have two options:
    1. Remove any directory previously leading to the OpenCV dlls from your PATH (e.g. in my case I removed C:\opencv248\build\x86\vc12\bin ) and then add C:\opencv248\ownBuild\bin\Debug and C:\opencv248\ownBuild\bin\Release to your PATH.
    2. Remove any directory previously leading to the OpenCV dlls from your PATH. Then move all .dll and .pdb files from the Debug and Release folder to a “save” place, e.g. C:\opencv248\debuggableDLL. Add this folder to your PATH, then delete the whole C:\opencv248\ownBuild\ folder to free disk space.
  7. Restart Visual Studio and start a debug session. Now the call stack shows exactly what happened: The call stack now shows the correct lines
  8. Remember to switch back to the optimized dlls when doing performance testing!

If you don’t want to build this all by yourself, here is the result of the build process for Visual Studio 2013 32-bit (the original size of >800MB is compressed to 80MB). To download the archive, activate JavaScript, enter “vsopencv” in the following field and then click the download button. Uncompress the archive with 7-zip and then perform step 6.b.

OpenCV: Reading an image sequence backwards

Here is a small code snippet for OpenCV which reads an image sequence backwards. It needs a sequence of images 000.png, 001.png, 002.png, … in the project’s folder.

cv::Mat frame;
cv::VideoCapture capture("000.png");
capture.set(CV_CAP_PROP_POS_AVI_RATIO, 1);
while (true)
{
	capture >> frame;
	capture.set(CV_CAP_PROP_POS_FRAMES, capture.get(CV_CAP_PROP_POS_FRAMES) - 2);

	cv::imshow("image", frame);
	cv::waitKey(30);
}

So what does the code do?

  1. Setting the property CV_CAP_PROP_POS_AVI_RATIO to 1 means starting at the end of the sequence (0 = at the beginning).
  2. The property CV_CAP_PROP_POS_FRAMES defines the index of the next image to load. Since it is automatically increased after each image retrieval, we have to decrement it by the value of 2.

Start AfterEffects in a different language

If you want to start AfterEffects CS4 in a different language than you have it installed (i.e. if you want to follow an English tutorial and cannot find the effects), open the program with the additional command  -L en_US .

Just create a link on your desktop and add this command after the target: "C:\...\AfterFX.exe" -L en_US.

You can find all available language codes by looking into the installation directory of AfterEffects and opening the AMT folder.

Repair a destroyed Windows 7 UEFI boot sector

I recently destroyed my Windows 7 UEFI boot sector by overwriting the corresponding EFI partition. This resulted in an error “Reboot and select proper boot device or insert boot media in selected”. This is how I fixed it (please be careful when dealing with partitioning and boot sectors, backup your data beforehand):

  1. Delete what is remaining of the Windows boot partition (not the Windows partition but the partition of around 128 MB size) and the EFI partition – you can use GParted for this. In the end, you should have at least 229 MB of free space on your hard drive – preferably at the beginning.
  2. Reboot from your Windows 7 DVD. Make sure you boot the UEFI part of the disk: When you open your boot menu by pressing F8, you will see two entries for your Windows 7 disk. One with “UEFI:” in front and one without. Select the former and then don’t forget to press any key if you are asked to – otherwise, the non-UEFI part would be booted.
  3. When Windows starts from the DVD, select the desired language and then press Shift+F10 to open the terminal.
  4. Now we will create the two missing partitions: the EFI boot sector and the Windows Boot sector. Type into the terminal (but leave the #… parts out – they are only comments by me):
    diskpart
    list disk
    select disk 0 #Select the desired disk
    create partition efi size=100
    list partition #Make sure that the 100mb partition is selected
    format quick fs=fat32 label="System"
    assign letter=B
    create partition msr size=128
    list partition #Check for errors
    list vol
    select vol 3 #Use the number corresponding to your windows installation
    assign letter=C
    exit
  5. Now copy the EFI files by typing:
    mkdir B:\EFI\Microsoft\Boot
    xcopy /s C:\Windows\Boot\EFI\*.* B:\EFI\Microsoft\Boot
  6. Now we will set the boot configuration data by typing:
    b:
    cd EFI\Microsoft\Boot
    bcdedit /createstore BCD
    bcdedit /store BCD  /create {bootmgr} /d “Windows Boot Manager”
    bcdedit /store BCD /create /d “Windows 7” /application osloader
    #This will return a GUID, referred to later as {guid}
    bcdedit /store BCD /set {bootmgr} default {guid}
    bcdedit /store BCD /set {bootmgr} path \EFI\Microsoft\Boot\bootmgfw.efi
    bcdedit /store BCD /set {bootmgr} displayorder {default}
    #Now it's not {bootmgr} anymore but {default}!
    bcdedit /store BCD /set {default} device partition=c:
    bcdedit /store BCD /set {default} osdevice partition=c:
    bcdedit /store BCD /set {default} path \Windows\System32\winload.efi
    bcdedit /store BCD /set {default} systemroot \Windows
    exit
  7. Restart. Additionally, I had two partitions with the boot flag which also caused trouble. I changed this with GParted.
  8. [Update] Configure the boot priority the UEFI menu so that the boot partition is the topmost.
  9. [Update] If you still have the problem that Windows is not booting automatically (i.e. the message “Reboot and select proper boot device or insert boot media in selected” is still displayed) but everything works fine when you open the boot menu and select the Windows bootloader yourself, this is the solution which worked for me:
    1. Power off the computer
    2. Unplug your hard drive
    3. Restart the computer, watch the booting fail and then power off again
    4. Replug your hard drive, restart and watch the booting succeed!


After Effects: Split-flap text animation

Here is a code snippet which allows you to animate text changes similar to a split-flap display using AfterEffects. The animation does not look exactly like those displays because I wanted a slightly different behavior for texts of different lengths. This is how the effect will look like (click on the following image to start the animation):
splitFlapDisplay

So how to do this in AfterEffects?

  1. Create a new text layer and add a slider control to the layer by searching for it in the Effects&Presets field.
  2. Now we have to enter an expression for the source text: open the layer properties and then the text property. Alt-click on the stop watch next to “Source Text”. Now, it should look like this:Split-Flap Display Tutorial 02
  3. Then enter the following code into the expression field (the field on the right which currently says “text.sourceText”):
    var oldText = "the old text";
    var newText = "new content";
    
    
    var result = "";
    var percentage = Math.min(Math.max(0,&amp;lt;code&amp;gt;effect("Slider Control")("Slider"&amp;lt;/code&amp;gt;),100);
    //Iterate through charcodes
    var maxLength = Math.max(oldText.length, newText.length);
    for(var i=0; i&amp;lt;maxLength; i++) {
    	if(i&amp;gt; oldText.length-1) {
    		//The old text is shorter
    		var toomuch= maxLength-oldText.length;
    		var additional = percentage/100*toomuch;
    		if(i &amp;lt; oldText.length+ additional) {
    			result += String.fromCharCode(newText.charCodeAt(i));
    		}
    	} else if( i &amp;gt; newText.length-1) {
    		//The new text is shorter
    		var toomuch= maxLength-newText.length;
    		var additional = (100-percentage)/100*toomuch;
    		if(i &amp;lt; newText.length+ additional) {
    			result += String.fromCharCode(oldText.charCodeAt(i));
    		}
    	} else {
    		result += String.fromCharCode(oldText.charCodeAt(i) + percentage/100*(newText.charCodeAt(i)-oldText.charCodeAt(i)));
    	}
    }
    result
    
  4. Note: if you have started AfterEffects in a different language than English you will get an exception. This is because effect("Slider Control")("Slider") in line 5 cannot be found. Find the slider control in the text layer, write down the right names and enter them into line 5 (i.e. in German: effect("Einstellungen für Schieberegler")("Schieberegler") ).
  5. Change the variables oldText and newText to your desired values.
  6. Now you can animate the slider with values between 0 (old text) and 100 (new text).

You can also download an example project:

Protect your email address from crawlers

I have come up with my own way to protect private data like email addresses, postal addresses or telephone numbers you want to or have to publish on your website. I was wondering if anybody else does it this way and what could be possible pitfalls. So please comment this post or write me if you have any remarks.

A simple solution would be hiding it via JavaScript (technically this would rather be “revealing via JS”) – but this does not work for me since I don’t want to exclude users with disabled JavaScript, for example blind people using screen reader. Plus, German law requires you to provide contact information barrier-free. The same holds for displaying the address as image.

My approach works with simple HTML+CSS only:

  1. One long-known technique for “encryption” of email addresses which I included into my approach is the substitution of some characters in your HTML code by their hexadecimal counterpart, i.e. mail@example.com → ma&#105;&#108;&#64;exa&#109;&#112;&#108;&#101;.com. This will break poorly-programmed crawlers but it is a pretty old trick so I assume it is not that effective anymore.
  2. Another simple method are HTML comments which won’t affect your readers but (hopefully) some crawlers: mail@example.com → ma<!-- just one comment -->il@example.com.
  3. And here comes the new part: include invisible boxes containing useless text in your code: mail@example.com → mail@ex<span style="visibility:hidden;float:right;">useless</span>ample.com.
  4. Please don’t forget to exclude sites with such disguised information from legitimate web crawlers via your robots.txt file – otherwise your site would look broken.

Altogether this disguises your email address as

ma&#105;&#108;&#64;<span style="visibility:hidden; float:right;"> useless </span>examp&#108;<!-- just one comment -->&#101;.com.

As you may notice this approach is not very pleasant for screen reader users either but I think if you include a personal message via

<div style="visibility:hidden; float:right; height:0px;">
Dear screen reader user. I have included some invisible boxes
in the following contact information to puzzle spam crawlers.
I apologize for your extra work but I am sure you will
be able to decode the text.
</div>

it will work for them. Displaying your address as image or disguising via JavaScript would not.