Thursday, May 24, 2012

Quartz : Getting the diff image of two images

Suppose there are following two images the background may be totally different image, e.g. not just plain color.

Image number one
Image number two











So basically I want to get the diff image of these two images i.e.

Diffed image
The diff image of two images is the image with the same size but the pixels are set to be transparent that haven't been changed. The difference image is constructed from the diff pixels with the color from the second image

Using difference blending mode Actually if we use the difference blending mode it doesn't solve the problem as it doesn't keep right colors of the pixels. If we apply difference blend mode to above 2 images we'll get following

Difference blended image








Which seems to have inverted color but, so after inverted the colors we will get  

Inverted diff blended image
So basically this method doesn't solve the issue, so what we need is to use mask the second image where there are differences. Please find below the Objective-C code implementation of the initially setup problem.


Download link




Solution implementation with Objective-C, tested on iPhone/iPad
- (CGContextRef)createCGContextFromCGImage:(CGImageRef)img
{
    size_t width = CGImageGetWidth(img);
    size_t height = CGImageGetHeight(img);
    size_t bitsPerComponent = CGImageGetBitsPerComponent(img);
    size_t bytesPerRow = CGImageGetBytesPerRow(img);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); //CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(NULL, // Let CG allocate it for us
                                             width,
                                             height,
                                             bitsPerComponent,
                                             bytesPerRow,
                                             colorSpace,
                                             kCGImageAlphaNone); // RGBA
    CGColorSpaceRelease(colorSpace);
    NSAssert(ctx, @"CGContext creation fail");
    return ctx;
}

- (UIImage*) computeDifferenceOfImage:(CGImageRef)oldImage withImage:(CGImageRef)newImage
{
    // Return the old image if the newImage is nil
    if (newImage == nil) {
        return [UIImage imageWithCGImage:oldImage];
    }
    
    // We assume both images are the same size, but it's just a matter of finding the biggest
    // CGRect that contains both image sizes and create the CGContext with that size
    CGRect imageRect = CGRectMake(0, 0,
                                  CGImageGetWidth(oldImage),
                                  CGImageGetHeight(oldImage));
    // Create our context based on the old image
    CGContextRef ctx = [self createCGContextFromCGImage:oldImage];
    
    // Draw the old image with the default (normal) blendmode 
    CGContextDrawImage(ctx, imageRect, oldImage);
    // Change the blendmode for the remaining drawing operations
    CGContextSetBlendMode(ctx, kCGBlendModeDifference);
    // Draw the new image "on top" of the old one
    CGContextDrawImage(ctx, imageRect, newImage);
    // Grab the composed CGImage
    CGImageRef diffed = CGBitmapContextCreateImage(ctx);

    // Make the gray color based image black and white based
    const CGFloat myMaskingColors[6] = { 1, 255, 1, 255, 1, 255 };
    // Get the masked image consisting of black and transparent pixels
    CGImageRef myColorMaskedImage = CGImageCreateWithMaskingColors(diffed, myMaskingColors);
    // Clean the context
    CGContextClearRect(ctx, imageRect);
    // Fill the context with white color 
    CGContextSetFillColorWithColor(ctx, [[UIColor whiteColor] CGColor]);
    CGContextFillRect(ctx, imageRect);
    CGContextDrawImage(ctx, imageRect, myColorMaskedImage);
    
    // Memory cleanup 
    CGImageRelease(diffed);
    CGImageRelease(myColorMaskedImage);
    // Grab the composed CGImage
    diffed = CGBitmapContextCreateImage(ctx);
    // Close the context 
    CGContextRelease(ctx);
    
    // Apply the constructed diff mask to newImage
    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(diffed),
                                        CGImageGetHeight(diffed), 
                                        CGImageGetBitsPerComponent(diffed),
                                        CGImageGetBitsPerPixel(diffed),
                                        CGImageGetBytesPerRow(diffed),
                                        CGImageGetDataProvider(diffed), NULL, false);
    CGImageRef masked = CGImageCreateWithMask(newImage, mask);
    UIImage *finalDiffedImage = [UIImage imageWithCGImage:masked];

    CGImageRelease(mask);
    CGImageRelease(masked);
    CGImageRelease(diffed);
    
    return finalDiffedImage;
}

Tuesday, September 6, 2011

GNU Gettext library

gettext is a l10n and i18n library

1. The texts inside source code should be wrapped by gettext function

So the text "My Name is..." becomes _("My Name is...")

2. Then xgettext runs on source code to generate .pot file, which contains the a list of all translatable strings. Translator edits .po files.

msginit --locale=fr --input=name.pot 

3. The .po files are compile into binary .mo file with msgfmt


4. The user, on Unix-type systems, sets the enviroment variable LC_MESSAGES, and the program will display strings in the selected language, if there is an .mo file for it.Then using msginit program translator derives .po file for example for french it will be

Wednesday, March 30, 2011

PDF docs with Mixed Rasted Content

Mixed Rasted Content is the way of keeping images in PDF docs. With couple of words the background image or generally the images in PDF docs are kept in pieces (in segments) for improving the contrast resolution of a raster image composed of pixels. More info on MRC can be found here

Now the problem is that lots of PDF viewers including Okular, Evince, and lots of others are showing the PDF docs with complete noisy background image, i.e. the background image of the docs is just random composition of some colors. Even in Ubuntu distribution the thumbnails are shown in that way.

This is especially problematic when viewing scanned documents in MRC PDFs. Even the converted tools like swftool could not solve the problem, so the only reasonable way is to create PDFs without MRC enabled options. In ABBYY Finereader that can be achieved easily from the saving options.

Another options of doing this is using pdf2pdf converter below which will convert PDFs with MRC to ordinary ones.

The code pdf2pdf converter is:


#!/bin/sh
#
# Convert a PDF to another PDF. This effectively strips
# out a lot of stuff from most PDF files.

gs=`which gs 2>/dev/null`
if [ ! -x "$gs" ]; then
    echo "Error: install ghostscript first" >&2
    exit 1
fi

OPTS=""
pdfver="1.2"
while true; do
    case "$1" in
    --pdf-version)
        shift
        pdfver="$1"
        ;;
    -?*) OPTS="$OPTS $1";;
    *) break;;
    esac
    shift
done

if [ $# -eq 2 ]; then
    outfile="$2"
elif [ $# -eq 1 ]; then
    outfile="`basename \"$1\" .pdf`.new.pdf"
else
    cat <&2
Usage: pdf2pdf [--pdf-version (1.2|1.3|1.4)] [gs-options ...]  [output.pdf|-]

Converts a PDF from whatever PDF specification version it currently
exists as to the one specified by \`--pdf-version'. Default: 1.2

One side-effect of this conversion is the resulting document will have
the no-printing and no-copying flags removed in the output document if
they are set in the input document.
EOF
    exit 1
fi

exec "$gs" $OPTIONS -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite \
    -dCompatibilityLevel="$pdfver" -sOutputFile="$outfile" -f "$1"

Friday, January 7, 2011

Where the hackintosh comes from ?

Patched Mac OS X kernel : Life-cycle

The kernel of Mac OS X is an open source product which can be found http://opensource.apple.com/ .
The current kernel version is xnu-1504.9.17

The Russian clever guys "teateam" are patching the mach_kernel upon every update of Mac OS X for running on Intel Atom based CPUs.
Here is their blog . The patched kernels are posted in English speaking community here.
The building process of kernel on Mac OS X Snow Leopard is described here

Based on last resource lots of distributions of hackintoshes are created e.g. SnowyWindOSX .

Are the hackintoshes legal ?

In all apple agreement you can find this passage

“2. Permitted License Uses and Restrictions.
A. This License allows you to install and use one copy of the Apple Software on a single Apple-labeled
computer at a time, and you may not make the Apple Software available over a network where it could be used by multiple computers at the same time. If you use Setup Assistant to transfer
software from one Apple-labeled computer to another Apple-labeled computer, please remember that continued use of the original copy of the software may be prohibited once a copy has been
transferred to another computer, unless you already have a licensed copy of such software on both computers. You should check the relevant software license agreements for applicable terms and
conditions. You may make one copy of the Apple Software (excluding the Boot ROM code) in machine-readable form for backup purposes only; provided that the backup copy must include all
copyright or other proprietary notices contained on the original.
B. Certain components of the Apple Software, and third party open source programs included with the Apple Software, have been or may be made available by Apple on its Open Source web site
(http://www.opensource.apple.com/) (collectively the “Open-Sourced Components”). You may modify or replace only these Open-Sourced Components; provided that: (i) the resultant modified
Apple Software is used, in place of the unmodified Apple Software, on a single Apple-labeled computer; and (ii) you otherwise comply with the terms of this License and any applicable licensing
terms governing use of the Open-Sourced Components. Apple is not obligated to provide any maintenance, technical or other support for the resultant modified Apple Software.
C. Except as and only to the extent permitted in this License, by applicable licensing terms governing use of the Open-Sourced Components, or by applicable law, you may not copy, decompile,
reverse engineer, disassemble, modify, or create derivative works of the Apple Software or any part thereof. THE APPLE SOFTWARE IS NOT INTENDED FOR USE IN THE OPERATION OF NUCLEAR
FACILITIES, AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL SYSTEMS, LIFE SUPPORT MACHINES OR OTHER EQUIPMENT IN WHICH THE FAILURE OF THE APPLE
SOFTWARE COULD LEAD TO DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE.
3. Transfer. You may not rent, lease, lend, redistribute or sublicense the Apple Software. You may, however, make a one-time permanent transfer of all of your license rights to the Apple Software
(in its original form as provided by Apple) to another party, provided that: (a) the transfer must include all of the Apple Software, including all its component parts, original media, printed materials
and this License; (b) you do not retain any copies of the Apple Software, full or partial, including copies stored on a computer or other storage device; and© the party receiving the Apple Software
reads and agrees to accept the terms and conditions of this License. You may not rent, lease, lend, redistribute, sublicense or transfer any Apple Software that has been modified or replaced under
Section 2B above. All components of the Apple Software are provided as part of a bundle and may not be separated from the bundle and distributed as standalone applications.
Updates: If an Apple Software update completely replaces (full install) a previously licensed version of the Apple Software, you may not use both versions of the Apple Software at the same time nor
may you transfer them separately.
NFR (Not for Resale) Copies: Notwithstanding other sections of this License, Apple Software labeled or otherwise provided to you on a promotional basis may only be used for demonstration,
testing and evaluation purposes and may not be resold or transferred.”


were says that Apple software can be installed only on apple labeled computers, so this mean that we stick the apple sticker on netbook, notebook or pc then on corresponding device can be easily installed machintosh.

Wednesday, November 3, 2010

Xserver : black screen delay when rotating using xrandr

When rotating X's display orientation on the fly 
using xrandr -o left|normal|inverted|right
command, following transitions are performed with 
black screen delay effect i.e. the display becomes 
black for a moment then displays rotated screen.

The following transitions are performed with a delay 
a black screen is shown with ~1 second duration, then 
rotated screen appears
normal > right|left 
inverted > normal|left|right
left > normal|inverted
right > normal|inverted

The following transitions are performed smoothly with 
no delays, i.e. "immediately"
normal > inverted
left > right
right > left
Reason of the problem
Most time consuming code while rotating the display orientation
with xrandr is 
ret = crtc->funcs->set_mode_major(crtc, mode, rotation, x, y);  
intel video drivers function call. This call is located in 
hw/xfree86/modes/xf86Crtc.c file in xf86CrtcSetModeTransform 
function.

HW Platforms:
Graphics : Intel GMA 3150 graphics
Graphics : Intel Graphics Media Accelerator (GMA) 950
Corresponding bug is opened in Xservers's intel video drivers 
project
https://bugs.freedesktop.org/show_bug.cgi?id=31313

Thursday, October 14, 2010

How to checkout a tag from git

For the people from subversion's world it may be difficult to switch to understandings of git.

Firstly git clone copies "everything" (i.e. commit history) to local machine.


Secondly in git the tag is simply a label to commit.
For listing tags use
      git tag -l
Then you can switch to tag using following command
      git checkout -b

Saturday, October 2, 2010

How to filter accelerometer data from noise


Problem statement

Suppose we have accelerometer with 3 axis and the raw data is quite noisy. Below is the plots of noisy data (right) and (desired/filtered) data. So we need to write a filter using which we’ll get the required signal.


Left image is filtered from sudden bumps and scaled, so if you notice the left signal is the middle part of right plot from approximately from -240 to 240.

Algorithm
For filtration quite simple algorithm was used. As the accelerometer data on appropriate axes X, Y, Z is the projection of gravity so the square root of their square sum will be the module of gravity vector with some error +/- 100 points.

Code
Below is the bash script which was used for filtration above signal.

#!/bin/bash

function tosigned() {
    if [ $1 -gt 32767 ]; then
            echo  $[$1-65536]
    else
            echo $1
    fi
}

function abs() {
        if [ $1 -lt 0 ] ; then
                echo `expr 0 - $1`
        else
                echo $1
        fi
}

sleep 1 # Wait for a second then send accelerometer data

tx=0
ty=0
tz=0

while :
do
    x= "datax from accel"
    y=
"datay from accel"
    z= "dataz from accel"
    x=$(tosigned $x)
    y=$(tosigned $y)
    z=$(tosigned $z)
    if [ $(abs $x) -lt 1000 -a $(abs $y) -lt 1000 -a $(abs $z) -lt 1000 ]; then
        g=$[$x * $x  + $y * $y + $z * $z]
        if [ $g -gt 40000 -a $g -lt 70000 ]; then
            max=0
            if [ $x -gt $max ]; then
            max=$x
            fi
            if [ $y -gt $max ]; then
            max=$y
            fi
            if [ $z -gt $max ]; then
            max=$z
            fi
            if [ $tx -eq 0 -a $ty -eq 0 -a $tz -eq 0 ]; then
                tx=$x   
                ty=$y   
                tz=$z   
                continue
            fi
            if [ $(abs $[$x - $tx]) -gt 200 -o $(abs $[$y - $ty]) -gt 200 -o $(abs $[$z - $tz]) -gt 200 ]; then
                tx=$x   
                ty=$y   
                tz=$z   
                continue
            fi
            echo "$x $y $z"
            break
            #sleep 0.01
        fi
    fi
done