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,<code>effect("Slider Control")("Slider"</code>),100);
    //Iterate through charcodes
    var maxLength = Math.max(oldText.length, newText.length);
    for(var i=0; i<maxLength; i++) {
    	if(i> oldText.length-1) {
    		//The old text is shorter
    		var toomuch= maxLength-oldText.length;
    		var additional = percentage/100*toomuch;
    		if(i < oldText.length+ additional) {
    			result += String.fromCharCode(newText.charCodeAt(i));
    		}
    	} else if( i > newText.length-1) {
    		//The new text is shorter
    		var toomuch= maxLength-newText.length;
    		var additional = (100-percentage)/100*toomuch;
    		if(i < 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.

.htaccess: redirect URLs containing php queries

I recently had to solve the problem of redirecting URLs with php queries, i.e. http://www.phillab.net/?page=programme&subpage=Passdraw → http://www.hasper.info/passdraw/ by using the .htaccess file.

Since most of the URLs did not have such a 1:1 translation like the example above, I did not work with wildcards – but this is also possible! I had the following constraints

  1. The php queries have to be removed from the redirected URL (this is not the standard!)
    RewriteEngine On
    RewriteCond %{QUERY_STRING} subpage=passdraw
    RewriteRule (.*) http://www.hasper.info/passdraw/? [R=301,L] #The question mark in the end does the trick!
    
  2. The php query check should be case-insensitive
    RewriteEngine On
    RewriteCond %{QUERY_STRING} subpage=passdraw [nocase]
    RewriteRule (.*) http://www.hasper.info/passdraw/? [R=301,L]
    
  3. Some queries have to point to the same new URL
    RewriteEngine On
    RewriteCond %{QUERY_STRING} subpage=passdraw [nocase,or]
    RewriteCond %{QUERY_STRING} subpage=bestAppEver [nocase]
    RewriteRule (.*) http://www.hasper.info/passdraw/? [R=301,L]
    
  4. Some queries contain special characters like dots or plus signs.
    RewriteEngine On
    RewriteCond %{QUERY_STRING} subpage=Ghostball\x2B3[nocase] #A plus sign has to be replaced by \x2B
    RewriteRule (.*) http://www.hasper.info/ghostball-3/? [R=301]
    RewriteCond %{QUERY_STRING} subpage=N\.T\. [nocase] #A dot has to be escaped by a slash
    RewriteRule (.*) http://www.hasper.info/n-t-a-commercial/? [R=301,L] #The L marks this as last rule
    

How to install and run an APK on Google Glass

Since Google Glass is currently only available for “Explorers”, the usability is quite limited and the device requires some hacking. Since the Glass-specific OS is updated regularly this will change soon but up until then, the following trick will come in handy:

Install and run an APK on Google Glass:

Well, currently the standard Glass launcher is quite limited and only allows for starting some pre-installed applications. You could either install a custom launcher like Launchy or do it without any modifications at all: In a nutshell, we will install the APK, find out the name of the app’s launching activity and then launch it. So no modifications and no prior knowledge of the application’s code is needed.

  1. Connect the Google Glass to your computer (you should have the Android SDK installed) and enable the debug mode on your device.
  2. Open a terminal and install the APK via adb install <apk path>.
  3. Find the android tool aapt (located in <sdk>\build-tools\<version>).
  4. Retrieve the package name and the activity to launch: aapt dump badging <apk path> | grep launchable-activity.
  5. Now you have all necessary information to launch the activity whenever you want: adb shell am start -a android.intent.action.MAIN -n <package name>/<activity name>.
  6. As an example with the password app Passdraw (currently not ported to Glass 🙂 ): adb shell am start -a android.intent.action.MAIN -n com.passdraw.free/com.passdraw.free.activities.LandingActivity

What I learned during the redesign

I have decided to update my website and turned it into a blog. All “portfolio” content is now presented as articles and is alternating with some tricks and tips mostly related to IT. This post is both the announcement of the new design and a collection of snippets I found while customizing WordPress and the theme.

  1. The sticky header is achieved by setting
    .imageBadge {
    	background-attachment:fixed;
    	min-height: 100px;
    }
    .textBadge {
    	position:fixed;
    }
    .mainContent {
    	z-index: 2;
    	position: relative;
    	background-color: #FFF;
    }
    
  2. The parallax effect for the header is done like this:
    /**
     * Creates a parallax effect for the header when scrolling
     */
    (
    function () {
    	var a = document.getElementById("masthead"),
    		e = $(window);
    	e.unbind("scroll").scroll(function () {
    		a.style.backgroundPosition =  "center "+ -(e.scrollTop()/ 9) + "px";
    	});
    }
    )();
    
  3. The sticky footer or “the curtain reveal effect” is done with
    .footerContainer {
      height:50px;
    }
    .footer {
      position:fixed;
      bottom:0px;
      padding: 10px 0px;
      z-index:0;
      width:100%;
    }
    

    A minimal demonstrator for points one to three can be found here: http://jsfiddle.net/PQS2C/3/

  4. Since there are so many syntax highlighters out there: I prefer the SyntaxHighlighter for WordPress. It does not screw up the indents, it has line numbering and visitors can easily copy the code.
  5. Protecting your WordPress login page (or other sensitive documents) by using .htaccess is a good idea because it reduces the load when your site is attacked and you have an additional protection against security vulnerabilities. But if you want a specific IP address to be excluded from the password query so you don’t have to enter the password every time, add the following to your .htaccess in the WordPress root folder:
    <Files wp-login.php>
      AuthUserFile <path to your .htpasswd>
      AuthName "Admin console"
      AuthType Basic
      require valid-user
      Order allow,deny
      allow from 12.34.567.89
      satisfy any
    </Files>
    # Guard some other sensitive files
    <FilesMatch "(\.htaccess|\.htpasswd|wp-config\.php|readme\.html)">
      order deny,allow
      deny from all
    </FilesMatch>
    

How to connect Google Glass to Windows

I recently got my hands on a Google Glass, the Android-based head-mounted display developed by Google. While connecting to it and installing apps works like a charm on my Linux system, it was quite a hassle to do the same with Windows.

I found a quite nice tutorial which I had to adapt to Windows 8: In a nutshell, we have to convince the Google usb driver that it fits to the Glass device and due to the editing we have to convince Windows 8, that it is okay for the driver’s signature to mismatch. Please proceed at your own responsibility.

  1. Connect the Google Glass to your PC and watch how the driver installation fails. If it does work: congratulations, you are done!
  2. Note the VID and the PID of your connected Glass. You can find them via Device Manager → Portable Devices → Glass 1 → Properties → Details → Hardware Ids.
  3. Open <sdk>\extras\google\usb_driver\android_winusb.inf
  4. Add the following lines using the VID and PID from step 2 to sections [Google.NTx86] and [Google.NTamd64]:
    ;Google Glass
    %SingleAdbInterface% = USB_Install, USB\VID_0000&PID_0000&REV_0216
    %CompositeAdbInterface% = USB_Install, USB\VID_0000&PID_0000&MI_01
    
    %SingleAdbInterface% = USB_Install, USB\VID_0000&PID_0000&REV_0216
    %CompositeAdbInterface% = USB_Install, USB\VID_0000&PID_0000&MI_01
    
  5. Go to the device manager and update the drivers.
  6. If you are not running Windows 8, you are done. If you are, the following error will occur: “The hash for the file is not present in the specified catalog file. The file is likely corrupt or the victim of tampering”. This is because we have altered the .INF-file and now the signature does not match anymore.
  7. Go back to the file android_winusb.inf and search for the lines
    CatalogFile.NTx86   = androidwinusb86.cat
    CatalogFile.NTamd64 = androidwinusba64.cat
    

    and comment them out:

    ;CatalogFile.NTx86   = androidwinusb86.cat
    ;CatalogFile.NTamd64 = androidwinusba64.cat
    
  8. Now, you will get a different error: “The third-party INF does not contain digital signature information”. Well, this security check is great but since we know what we are doing … : Do an “Advanced Startup” (just press the windows key and type it in, then go to Troubleshoot → Advanced options → Start up settings → Restart.
  9. Disable driver signature enforcement in the boot menu.
  10. Update your drivers again in the device manager and this time skip the driver signature enforcement.
  11. Google Glass should now be recognized correctly. Restart your computer if you want to re-enable the driver signature enforcement.