Android: simple color processing, performance issues

Status
Not open for further replies.

Shamyl Zakariya

Ars Praefectus
3,816
Subscriptor++
So first off I have to clarify that I'm writing an Android-specific Java plugin for a cross-platform Javascript-based toolkit for making iOS and Android apps from one codebase. I'm using Appcelerator Titanium, which provides hooks for native plugins.

So: The plugin does a little simple image processing on small images - it drops them to greyscale, bumps the contrast, and then provides two images, the greyscale one and another one with a color screened atop the greyscale.

I wrote an ObjC plugin for the iOS build of the app and it works beautifully. It's fast enough (~100 millis) that the user will never know anything's being done at all.

The Java-based Android plugin, however, takes something like 2 to 3 seconds to run... and that's unacceptable in my opinion.

I'm going to post code below but I'll walk through how it works, and maybe some kind soul here will be able to help me make it faster.

What I do is pre-compute lookup tables for contrast and tinting. I walk through the image's pixels, knock them to greyscale, and output an image using the contrast table. The tinted image uses the output of the contrast table to lookup into a computed tinting table.

I suspect that some of my performance issues come from memory allocation. I also suspect that Java just is slow.

Code:
/**
 * This file was auto-generated by the Titanium Module SDK helper for Android
 * Appcelerator Titanium Mobile
 * Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 *
 */
package org.zakariya.imaging;

import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.annotations.Kroll;

import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiBlob;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiConfig;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;


@Kroll.module(name="Imaging", id="org.zakariya.imaging")
public class ImagingModule extends KrollModule
{

	// Standard Debugging variables
	private static final String LCAT = "ImagingModule";
	private static final boolean DBG = TiConfig.LOGD;

	private TiBlob _sourceBlob;
	private Bitmap _sourceBitmap;
	private int[] _pixelBuffer;
	private String _tintColor;
	private int _tintColorValue;
	private int _contrast;

	private int[] _contrastLUT;
	private int[] _tintLUT;

	// You can define constants with @Kroll.constant, for example:
	// @Kroll.constant public static final String EXTERNAL_NAME = value;

	public ImagingModule()
	{
		super();

		_contrastLUT = new int[256];
		_tintLUT = new int[256];

		setContrast(15);
		setTintColor( "#0cf" );
	}

	@Kroll.onAppCreate
	public static void onAppCreate(TiApplication app)
	{
		Log.d(LCAT, "inside onAppCreate");		
	}

	///////////////////////////////////////////////////////

	@Kroll.setProperty
	public void setImage( Object value ) 
	{
		_sourceBlob = TiConvert.toBlob(value);

		byte[] sourceBytes = _sourceBlob.getBytes();
		_sourceBitmap = BitmapFactory.decodeByteArray(sourceBytes, 0, sourceBytes.length);

		if ( _sourceBitmap != null )
		{
			int 
				width = _sourceBitmap.getWidth(),
				height = _sourceBitmap.getHeight(),
				length = width * height;

			_pixelBuffer = new int[length];
		}
		else
		{
			_pixelBuffer = null;
		}
	}

	@Kroll.getProperty
	public TiBlob getImage()
	{
		return _sourceBlob;
	}

	@Kroll.setProperty
	public void setTintColor( String color )
	{
		_tintColor = color;
		_tintColorValue = TiConvert.toColor( color );

		int 
			red = Color.red(_tintColorValue),
			green = Color.green(_tintColorValue),
			blue = Color.blue(_tintColorValue);

		for ( int i = 0; i <= 255; i++ )
		{
			double factor = (double)i / (double)255.0;

			int 
			rt = _clampColorComponent((int)(red + (factor * (255-red)))),
			gt = _clampColorComponent((int)(green + (factor * (255-green)))),
			bt = _clampColorComponent((int)(blue + (factor * (255-blue))));

			_tintLUT[i] = Color.rgb( rt, gt, bt ); 
		}		
	}

	@Kroll.getProperty
	public String getTintColor()
	{
		return _tintColor;
	}

	@Kroll.setProperty
	public void setContrast( int contrast )
	{
		if ( contrast < -100 ) contrast = -100;
		if ( contrast > 100 ) contrast = 100;
		_contrast = contrast;

		// update contrast LUT
		double c = (100.0 + _contrast) / 100.0;
		c *= c;

		for (int i = 0; i <= 255; i++)
		{
			double v = (double)i;
			v /= 255.0;
			v -= 0.5;
			v *= c;
			v += 0.5;
			v *= 255;

			if (v < 0)
			{
				v = 0;
			}

			if (v > 255)
			{
				v = 255;
			}

			_contrastLUT[i] = _clampColorComponent((int)v);
		}
	}

	@Kroll.getProperty
	public int getContrast()
	{
		return _contrast;
	}

	@Kroll.getProperty
	public TiBlob imageAsGreyscale()
	{
		return _render_1( false );
	}

	@Kroll.getProperty
	public TiBlob imageAsTinted()
	{
		return _render_1( true );
	}
	
	private TiBlob _render_1( boolean tinted )
	{
		Log.i(LCAT, "ImagingModule::_render_1 - pixel buffer swizzling");

		final double 
			LuminanceRed = 0.299/255.0,
			LuminanceGreen = 0.587/255.0,
			LuminanceBlue = 0.114/255.0;

		if ( _sourceBitmap != null && _pixelBuffer != null )
		{
			int 
				width = _sourceBitmap.getWidth(),
				height = _sourceBitmap.getHeight(),
				length = width * height;
			
			// local aliasing -- does this benefit Java?
			int [] pixels = _pixelBuffer;
			int [] tintLUT = _tintLUT;
			int [] contrastLUT = _contrastLUT;
					

			_sourceBitmap.getPixels( pixels, 0, width, 0, 0, width, height);

			if ( tinted )
			{
				for ( int i = 0; i < length; i++ )
				{
					int 
						color = pixels[i],
						red = (color >> 16) & 0xFF,
						green = (color >> 8) & 0xFF,
						blue = color & 0xFF,
						luma = (int)(((red * LuminanceRed) + (green * LuminanceGreen) + (blue * LuminanceBlue)) * 255.0);
					
					pixels[i] = tintLUT[contrastLUT[luma]];
				}            		
			}
			else
			{
				for ( int i = 0; i < length; i++ )
				{
					int 
						color = pixels[i],
						red = (color >> 16) & 0xFF,
						green = (color >> 8) & 0xFF,
						blue = color & 0xFF,
						luma = (int)(((red * LuminanceRed) + (green * LuminanceGreen) + (blue * LuminanceBlue)) * 255.0);
					
					luma = contrastLUT[luma];
					pixels[i] = 0xFF000000 | luma << 16 | luma << 8 | luma;
				}
			}

			Bitmap result = Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888 );   
			if ( result != null )
			{
				return TiBlob.blobFromImage( result );
			}
		}

		return null;
	}	
	
	private TiBlob _render_2( boolean tinted )
	{
		Log.i(LCAT, "ImagingModule::_render_2 - in-place swizzling");
		
		final double 
			LuminanceRed = 0.299/255.0,
			LuminanceGreen = 0.587/255.0,
			LuminanceBlue = 0.114/255;
		
		if ( _sourceBitmap != null )
		{
			int 
				width = _sourceBitmap.getWidth(),
				height = _sourceBitmap.getHeight();

			Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

			if ( tinted )
			{
				for ( int y = 0; y < height; y++ )
				{
					for ( int x = 0; x < width; x++ )
					{
						int 
							color = _sourceBitmap.getPixel(x, y),
							red = (color >> 16) & 0xFF,
							green = (color >> 8) & 0xFF,
							blue = color & 0xFF,
							luma = (int)(((red * LuminanceRed) + (green * LuminanceGreen) + (blue * LuminanceBlue)) * 255.0);

						result.setPixel(x, y, _tintLUT[_contrastLUT[luma]]);
					}
				}
			}
			else
			{
				for ( int y = 0; y < height; y++ )
				{
					for ( int x = 0; x < width; x++ )
					{
						int 
							color = _sourceBitmap.getPixel(x, y),
							red = (color >> 16) & 0xFF,
							green = (color >> 8) & 0xFF,
							blue = color & 0xFF,
							luma = (int)(((red * LuminanceRed) + (green * LuminanceGreen) + (blue * LuminanceBlue)) * 255.0);

						luma = _contrastLUT[luma];
						result.setPixel(x, y, 0xFF000000 | luma << 16 | luma << 8 | luma);
					}
				}
			}

			return TiBlob.blobFromImage( result );
		}

		return null;
	}		

	private static final int _clampColorComponent( int v )
	{
		if ( v < 0 ) return 0;
		else if ( v > 255 ) return 255;
		return v;
	}
}

In _render_2 I tried eliminating the need for the interim _pixelBuffer allocation, but performance was much worse -- most likely since calling getPixel() and setPixel() probably sanity check/clamp the inputs.

Now, I'm targeting Android 2.2, which probably limits some of the built-in graphics APIs I have access to. I'm not a Java guy ( I'm a c++/opengl guy! ) so I don't know what kind of options I have. If Android has some kind of built-in color manipulation for bitmaps, well, I would appreciate some pointers.

My guess is that there's a smarter way to do what I'm going, but since I'm new to android I don't even know what I don't know.

Thanks,
 

Shamyl Zakariya

Ars Praefectus
3,816
Subscriptor++
So, this is one of those classic cases where, after posting a question to a forum, I go and read the documentation more closely and figure it out.

I've rewritten it completely using android's ColorMatrix to desaturate, and solid color compositing with PorterDuff.Mode.SCREEN - and it works like a charm.

I'm still going to need to write a contrast adjustment matrix but the important part is that the code's a lot faster now, maybe 50%. Still slow compared to iOS, but a hell of a lot faster than before.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
Shamyl Zakariya":3g0gil3q said:
So, this is one of those classic cases where, after posting a question to a forum, I go and read the documentation more closely and figure it out.

I've rewritten it completely using android's ColorMatrix to desaturate, and solid color compositing with PorterDuff.Mode.SCREEN - and it works like a charm.

I'm still going to need to write a contrast adjustment matrix but the important part is that the code's a lot faster now, maybe 50%. Still slow compared to iOS, but a hell of a lot faster than before.
I have a theory that posting a question releases the allocated resources in the mind that are invariably holding you back. It allows you to step out of the box and take a different perspective.
 

SoapySmooth

Wise, Aged Ars Veteran
197
topham":a6y4v363 said:
Shamyl Zakariya":a6y4v363 said:
So, this is one of those classic cases where, after posting a question to a forum, I go and read the documentation more closely and figure it out.

I've rewritten it completely using android's ColorMatrix to desaturate, and solid color compositing with PorterDuff.Mode.SCREEN - and it works like a charm.

I'm still going to need to write a contrast adjustment matrix but the important part is that the code's a lot faster now, maybe 50%. Still slow compared to iOS, but a hell of a lot faster than before.
I have a theory that posting a question releases the allocated resources in the mind that are invariably holding you back. It allows you to step out of the box and take a different perspective.

Its just a form of rubber ducking, forcing you to articulate the issue clearly when posting the question.
 

Shamyl Zakariya

Ars Praefectus
3,816
Subscriptor++
topham":14qy0dee said:
I have a theory that posting a question releases the allocated resources in the mind that are invariably holding you back. It allows you to step out of the box and take a different perspective.

:bigdumbgrin:

I can't tell you how many times I've done this. Usually I solve the problem within 2 hours of asking on this board ( or idevgames.com ).
 

topham

Ars Legatus Legionis
13,756
Subscriptor
SoapySmooth":16lsp8yl said:
topham":16lsp8yl said:
Shamyl Zakariya":16lsp8yl said:
So, this is one of those classic cases where, after posting a question to a forum, I go and read the documentation more closely and figure it out.

I've rewritten it completely using android's ColorMatrix to desaturate, and solid color compositing with PorterDuff.Mode.SCREEN - and it works like a charm.

I'm still going to need to write a contrast adjustment matrix but the important part is that the code's a lot faster now, maybe 50%. Still slow compared to iOS, but a hell of a lot faster than before.
I have a theory that posting a question releases the allocated resources in the mind that are invariably holding you back. It allows you to step out of the box and take a different perspective.

Its just a form of rubber ducking, forcing you to articulate the issue clearly when posting the question.

Articulating the issue can definitely help, but for various reasons most people are still held to the path they were originally pursuing; it's only when we can step back and de-invest in our already written code that we can reimagine a solution independent of the current one. We get trapped in a local-maxima.
 

Shamyl Zakariya

Ars Praefectus
3,816
Subscriptor++
#1 Juan Kerr":2kj0f6jz said:
If it's still not performant enough for you, you could dip in to C via the JNI to speed it up.
Quick example: http://ruckus.tumblr.com/post/18055652108/writing-a-basic-image-filter-in-android-using-ndk

Bitmaps + Android = pain

What device are you testing on?

-=JK=-

I'm going to look into that. The performance of my current implementation - using android's Canvas + ColorMatrixFilter + PorterDuff compositing is a lot better than my original pixel swizzling, but still nowhere near as good as my iOS version ( which is just pixel swizzling, but it's fast because I'm good at C ).

I'm testing this on a Droid Incredible (1st gen) running CM7.2. I like the idea of dropping to the NDK to get pointer arithmetic and making it fast... but I really don't know Android well enough to know how many implementations I'll have to build to make the C version portable.
 

#1 Juan Kerr

Ars Scholae Palatinae
607
I like the idea of dropping to the NDK to get pointer arithmetic and making it fast... but I really don't know Android well enough to know how many implementations I'll have to build to make the C version portable.
You should not need multiple implementations to make it portable.
You put "APP_ABI := all" in your application makefile and the NDK will compile your code for all supported architectures. Then when your app is installed on a device, the best library is selected for the architecture of that device.

I've used the NDK and found it to be not as awkward or daunting as I was expecting, and I do not have a strong background in C.

The bitmap-plasma sample app in the NDK is probably a good place to start IMHO.

-=JK=-
 
Status
Not open for further replies.