<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Patrick&#039;s playground &#187; JAVA</title>
	<atom:link href="http://www.vankouteren.eu/blog/category/programming/programming-java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.vankouteren.eu/blog</link>
	<description>Random thoughts, problems and solutions</description>
	<lastBuildDate>Sun, 29 Jan 2012 07:53:06 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Using SimpleAdapter for populating simple_list_item_2 with Strings</title>
		<link>http://www.vankouteren.eu/blog/2011/09/using-simpleadapter-for-populating-simple_list_item_2-with-strings/</link>
		<comments>http://www.vankouteren.eu/blog/2011/09/using-simpleadapter-for-populating-simple_list_item_2-with-strings/#comments</comments>
		<pubDate>Tue, 27 Sep 2011 06:29:00 +0000</pubDate>
		<dc:creator>Patrick van Kouteren</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[JAVA]]></category>
		<category><![CDATA[ListView]]></category>
		<category><![CDATA[simpe_list_item_row_2]]></category>
		<category><![CDATA[SimpleAdapter]]></category>

		<guid isPermaLink="false">http://www.vankouteren.eu/blog/?p=264</guid>
		<description><![CDATA[I don't know it it's my searching skills which are fading or the lack of examples, but I wasn't able to find a simple example on how to use the simple_list_item_2 which is built into Android. I've used some custom layouts to establish the same result, and sometimes some extras (display an icon on the [...]]]></description>
			<content:encoded><![CDATA[            <script type="text/javascript" src="http://www.vankouteren.eu/blog/wp-content/plugins/wordpress-code-snippet/scripts/shBrushXml.js"></script>
            <script type="text/javascript" src="http://www.vankouteren.eu/blog/wp-content/plugins/wordpress-code-snippet/scripts/shBrushJava.js"></script>
<p>I don't know it it's my searching skills which are fading or the lack of examples, but I wasn't able to find a simple example on how to use the simple_list_item_2 which is built into Android. I've used some custom layouts to establish the same result, and sometimes some extras (display an icon on the right for example). However, now I wanted to use the built-in feature, but had to search quite some time. If you experience the same, hopefully this post will save you time.</p>
<p><span id="more-264"></span>I know: it's basic, but I'm still learning Android, so I think I may behave like a n00b at the moment <img src='http://www.vankouteren.eu/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>So, what do we need for setting up the list:</p>
<ul>
<li>screen layout</li>
<li>activity</li>
<li>list content</li>
</ul>
<p>Let's go! First create a layout:</p>
<p><pre class="brush: xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout
	android:id=&quot;@+id/screen_about_layout&quot;
	android:layout_width=&quot;fill_parent&quot;
	android:layout_height=&quot;fill_parent&quot;
	android:orientation=&quot;vertical&quot;
	xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
&gt;
	&lt;RelativeLayout
		android:id=&quot;@+id/screen_title_bar&quot;
		android:layout_width=&quot;fill_parent&quot;
		android:layout_height=&quot;60px&quot;
		android:layout_alignParentTop=&quot;true&quot;
		android:layout_alignParentLeft=&quot;true&quot;
		android:background=&quot;@drawable/title_bar&quot;
	&gt;
		&lt;TextView
			android:id=&quot;@+id/screen_top_title&quot;
			android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot;
			android:text=&quot;@string/screen_more_title&quot;
			android:layout_centerVertical=&quot;true&quot;
			android:layout_alignParentLeft=&quot;true&quot;
			android:textSize=&quot;18sp&quot; 
			android:textColor=&quot;@color/white&quot;
			android:paddingLeft=&quot;10px&quot;
		&gt;
		&lt;/TextView&gt;
		&lt;ImageButton
			android:id=&quot;@+id/screen_top_info&quot;
			android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot;
			android:src=&quot;@drawable/icon_info&quot;
			android:layout_centerVertical=&quot;true&quot;
			android:layout_alignParentRight=&quot;true&quot;
			android:paddingRight=&quot;10px&quot;
			android:background=&quot;@null&quot;
		&gt;
		&lt;/ImageButton&gt;	
	&lt;/RelativeLayout&gt; 

&lt;!-- Set height to 0, and let the weight param expand it --&gt;
    &lt;!-- Note the use of the default ID! This lets us use a 
         ListActivity still! --&gt;
    &lt;ListView android:id=&quot;@android:id/list&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;0dip&quot;
        android:layout_weight=&quot;1&quot; 
         /&gt; 

&lt;/LinearLayout&gt;</pre></p>
<p>Note that the list has an id called '@android:id/list'. This enables us to directly use the list in the Activity as it's going to extend ListActivity.</p>
<p>In the Activity itself we define an ArrayList containing HashMaps from String to String. Basically this means that we create a list which will contain key, value pairs which we are going to control (This is similar to associative arrays in PHP). We will use the key 'line1' for the upper line and 'line2' for the lower line. With the variables from and to we map the values of the keys we supply (this is the from variable) to the TextViews of the simple_list_item_row_2 (the to variable). These are called text1 and text2.</p>
<p><pre class="brush: java">package com.example.sampleapp;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.SimpleAdapter;

public class MoreScreen extends ListActivity {

	ArrayList&lt;HashMap&lt;String, String&gt;&gt; list = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(
			2);

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_more);

		HashMap&lt;String, String&gt; map;

		map = new HashMap&lt;String, String&gt;();
		map.put(&quot;line1&quot;, &quot;Foo&quot;);
		map.put(&quot;line2&quot;, &quot;Bar&quot;);
		list.add(map);

		map = new HashMap&lt;String, String&gt;();
		map.put(&quot;line1&quot;, &quot;Hi&quot;);
		map.put(&quot;line2&quot;, &quot;Bye&quot;);
		list.add(map);

		// the from array specifies which keys from the map
		// we want to view in our ListView
		String[] from = { &quot;line1&quot;, &quot;line2&quot; };

		// the to array specifies the TextViews from the xml layout
		// on which we want to display the values defined in the from array
		int[] to = { android.R.id.text1, android.R.id.text2 };

		// create the adapter and assign it to the listview
		SimpleAdapter adapter = new SimpleAdapter(this, list,
				android.R.layout.simple_list_item_2, from, to);
		setListAdapter(adapter);

	}

}</pre></p>
]]></content:encoded>
			<wfw:commentRss>http://www.vankouteren.eu/blog/2011/09/using-simpleadapter-for-populating-simple_list_item_2-with-strings/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Custom checkboxes for CheckBoxPreferences on Android</title>
		<link>http://www.vankouteren.eu/blog/2011/09/custom-checkboxes-for-checkboxpreferences-on-android/</link>
		<comments>http://www.vankouteren.eu/blog/2011/09/custom-checkboxes-for-checkboxpreferences-on-android/#comments</comments>
		<pubDate>Thu, 01 Sep 2011 22:10:39 +0000</pubDate>
		<dc:creator>Patrick van Kouteren</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[JAVA]]></category>

		<guid isPermaLink="false">http://www.vankouteren.eu/blog/?p=261</guid>
		<description><![CDATA[For an App I'm writing I need to use custom checkboxes in a PreferenceScreen. I want to use the CheckboxPreferences as it's designed for that. Many searches lead to StackOverflow, but caused me a stack overflow as well as they didn't work. In this (short) post I outline my findings and provide a working solution [...]]]></description>
			<content:encoded><![CDATA[            <script type="text/javascript" src="http://www.vankouteren.eu/blog/wp-content/plugins/wordpress-code-snippet/scripts/shBrushXml.js"></script>
            <script type="text/javascript" src="http://www.vankouteren.eu/blog/wp-content/plugins/wordpress-code-snippet/scripts/shBrushJava.js"></script>
<p>For an App I'm writing I need to use custom checkboxes in a PreferenceScreen. I want to use the CheckboxPreferences as it's designed for that. Many searches lead to StackOverflow, but caused me a stack overflow as well as they didn't work. In this (short) post I outline my findings and provide a working solution step by step.<span id="more-261"></span></p>
<p><strong>Step 1</strong></p>
<p>You need a custom checkbox. This can be defined in a drawable. In this case I've called the file checkbox.xml and placed it in the drawable folder. The code defines the images for two states: if the checkbox is enabled and when it's disabled. For this file looks like this:</p>
<p><pre class="brush: xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;selector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
    &lt;item android:state_checked=&quot;true&quot;
          android:drawable=&quot;@drawable/checkbox_checked&quot; /&gt; &lt;!-- checked --&gt;
    &lt;item android:state_checked=&quot;false&quot; 
    	android:drawable=&quot;@drawable/checkbox_unchecked&quot; /&gt; &lt;!-- default --&gt;
&lt;/selector&gt;</pre></p>
<p><strong>Step 2</strong></p>
<p>We need a layout for customized preferences. This layout defines the same stuff as the ' regular'  preference does (text, summary etc.). Note the last part in the following file (called checkbox_preference.xml and placed in the layout folder). It loads our custom checkbox!</p>
<p><pre class="brush: xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;!-- Copyright (C) 2006 The Android Open Source Project Licensed under the 
    Apache License, Version 2.0 (the &quot;License&quot;); you may not use this file except 
    in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
    Unless required by applicable law or agreed to in writing, software distributed 
    under the License is distributed on an &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES 
    OR CONDITIONS OF ANY KIND, either express or implied. See the License for 
    the specific language governing permissions and limitations under the License. --&gt;

&lt;!-- Layout for a Preference in a PreferenceActivity. The Preference is able 
    to place a specific widget for its particular type in the &quot;widget_frame&quot; 
    layout. --&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;wrap_content&quot;
    android:minHeight=&quot;?android:attr/listPreferredItemHeight&quot;
    android:gravity=&quot;center_vertical&quot; android:paddingRight=&quot;?android:attr/scrollbarSize&quot;&gt;

    &lt;RelativeLayout android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot; android:layout_marginLeft=&quot;15dip&quot;
        android:layout_marginRight=&quot;6dip&quot; android:layout_marginTop=&quot;6dip&quot;
        android:layout_marginBottom=&quot;6dip&quot; android:layout_weight=&quot;1&quot;&gt;

        &lt;TextView android:id=&quot;@+android:id/title&quot;
            android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot;
            android:singleLine=&quot;true&quot; android:textAppearance=&quot;?android:attr/textAppearanceLarge&quot;
            android:ellipsize=&quot;marquee&quot; android:fadingEdge=&quot;horizontal&quot; /&gt;

        &lt;TextView android:id=&quot;@+android:id/summary&quot;
            android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot;
            android:layout_below=&quot;@android:id/title&quot; android:layout_alignLeft=&quot;@android:id/title&quot;
            android:textAppearance=&quot;?android:attr/textAppearanceSmall&quot;
            android:maxLines=&quot;4&quot; /&gt;

    &lt;/RelativeLayout&gt;

&lt;CheckBox android:id=&quot;@+android:id/checkbox&quot;
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:button=&quot;@drawable/checkbox&quot; /&gt;

&lt;/LinearLayout&gt;</pre></p>
<p><strong>Step 3</strong></p>
<p>Now the code below is the actual layout which you inflate with your SharedPreferences in your Activity. The layout attribute is used to put the custom layout with the custom checkbox as an item in there.</p>
<p><pre class="brush: xml"> &lt;PreferenceScreen xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;

	&lt;PreferenceCategory
		android:title=&quot;@string/category_title&quot;&gt;
		
	&lt;CheckBoxPreference
	android:key=&quot;preferenceKey&quot;
	android:title=&quot;@string/preferenceTitle&quot;
	android:defaultValue=&quot;false&quot;
	android:layout=&quot;@layout/checkbox_preference&quot;
	/&gt;
	&lt;/PreferenceCategory&gt;
&lt;/PreferenceScreen&gt;</pre></p>
<p><strong>Step 4</strong></p>
<p>There is no step 4. You're done! It shouldn't be that hard to find and use these things. Unfortunately many same questions, but more different (and often not / not completely working replies / solutions) are posed on sites like StackOverflow which makes it harder to find the real solution. Hopefully this post is a worthy addition to the interwebs and a valuable resource for Android designers facing the same problem.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.vankouteren.eu/blog/2011/09/custom-checkboxes-for-checkboxpreferences-on-android/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>K Means clustering and Histogram equalization source code</title>
		<link>http://www.vankouteren.eu/blog/2010/03/k-means-clustering-and-histogram-equalization-source-code/</link>
		<comments>http://www.vankouteren.eu/blog/2010/03/k-means-clustering-and-histogram-equalization-source-code/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 06:41:54 +0000</pubDate>
		<dc:creator>Patrick van Kouteren</dc:creator>
				<category><![CDATA[JAVA]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Histogram equalization]]></category>
		<category><![CDATA[k-means]]></category>
		<category><![CDATA[K-means clustering]]></category>
		<category><![CDATA[source code]]></category>

		<guid isPermaLink="false">http://www.vankouteren.eu/blog/?p=195</guid>
		<description><![CDATA[As there was some interest in source code in two earlier posts (post 1, post 2) I've posted the source code here. It's also available through the download page. Please note that the code itself is at least 4 years old and there are far better ways to solve some things. I therefore suggest that [...]]]></description>
			<content:encoded><![CDATA[            <script type="text/javascript" src="http://www.vankouteren.eu/blog/wp-content/plugins/wordpress-code-snippet/scripts/shBrushXml.js"></script>
            <script type="text/javascript" src="http://www.vankouteren.eu/blog/wp-content/plugins/wordpress-code-snippet/scripts/shBrushJava.js"></script>
<p>As there was some interest in source code in two earlier posts (<a href="http://www.vankouteren.eu/blog/2009/09/k-means-clustering-in-java-code-found/" target="_blank">post 1</a>, <a href="http://www.vankouteren.eu/blog/2007/10/k-means-clustering-implementation-in-java/" target="_blank">post 2</a>) I've posted the source code <a href="http://www.vankouteren.eu/downloads/Ispe-dev.zip" target="_blank">here</a>.</p>
<p>It's also available through the <a href="http://www.vankouteren.eu/blog/downloads/" target="_blank">download page</a>.</p>
<p>Please note that the code itself is at least 4 years old and there are far better ways to solve some things. I therefore suggest that it is used for studying purposes only. Comments and improvments are very much appreciated.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.vankouteren.eu/blog/2010/03/k-means-clustering-and-histogram-equalization-source-code/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>K-means clustering in Java code found!</title>
		<link>http://www.vankouteren.eu/blog/2009/09/k-means-clustering-in-java-code-found/</link>
		<comments>http://www.vankouteren.eu/blog/2009/09/k-means-clustering-in-java-code-found/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 13:36:45 +0000</pubDate>
		<dc:creator>Patrick van Kouteren</dc:creator>
				<category><![CDATA[JAVA]]></category>
		<category><![CDATA[clustering]]></category>
		<category><![CDATA[k-means]]></category>
		<category><![CDATA[K-means clustering]]></category>

		<guid isPermaLink="false">http://www.vankouteren.eu/blog/?p=144</guid>
		<description><![CDATA[My blogpost on K-means clustering has the highest number of views, so people are probably interested in it. Sadly enough I lost the source code of the K-means action a while ago. Last week I needed an external harddisk to make a back-up of some files. There was already some content on the disk. I [...]]]></description>
			<content:encoded><![CDATA[            <script type="text/javascript" src="http://www.vankouteren.eu/blog/wp-content/plugins/wordpress-code-snippet/scripts/shBrushXml.js"></script>
            <script type="text/javascript" src="http://www.vankouteren.eu/blog/wp-content/plugins/wordpress-code-snippet/scripts/shBrushJava.js"></script>
<p>My <a title="K-means clustering implementation in JAVA" href="http://www.vankouteren.eu/blog/2007/10/k-means-clustering-implementation-in-java/">blogpost on K-means clustering</a> has the highest number of views, so people are probably interested in it. Sadly enough I lost the source code of the K-means action a while ago. Last week I needed an external harddisk to make a back-up of some files. There was already some content on the disk. I found quite some pieces of code including the K-means code. Although it is quite simple code operating on (if I remember correctly 8-bit) greyscale images, it might give some insights in how to do this.</p>
<p><span id="more-144"></span>The whole code file is presented below. For more information you can view <a title="K-means clustering implementation in JAVA" href="http://www.vankouteren.eu/blog/2007/10/k-means-clustering-implementation-in-java/">my earlier blogpost</a> on K-means clustering.</p>
<p><pre class="brush: java">package actions;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

/**
 * This KMeansAction performs a K-means clustering action on a BufferedImage
 * @author Patrick van Kouteren
 *
 */

public class KMeansAction {

		BufferedImage image_temp;
		boolean not_terminated;
		int loops, changedPixels;
		int[] histogram;
		ArrayList classes;
		int [] lowerbounds;
		public final static int MEAN_BY_MOD = 1;
		public final static int MEAN_BY_SPACE = 2;
		public final static int MEAN_AT_RANDOM = 3;

		/**
		 * Controls the actual work:
		 * - Initialization
		 * - Loop until termination condition is met
		 *  + for each pixel: assign pixel to a class such that the distance from the pixel to the mean of that class is minimized
		 *  + for each class: recalculate the means of the class based on pixels belonging to that class
		 * - End loop
		 * @param image
		 * @param bins (k)
		 * @param histogram
		 */
		public KMeansAction(BufferedImage image, int bins, int[]histogram, int initway) {
			this.histogram = histogram;
			lowerbounds = new int[bins];
			initialize(image, bins, initway);
			calculateBounds();
			while (not_terminated) {
				recalculateMeans();
				loops++;
				checkTermination();
				}
			processImage(image, bins);
		}

		/**
		 * Set the new color values for the image
		 * @param image
		 */
		private void processImage(BufferedImage image, int bins) {
			int delta = 255 / (bins-1);
			for (int h = 0; h &amp;lt; image.getHeight(); h++){
				for (int w = 0; w &amp;lt; image.getWidth(); w++){
					Color rgb = new Color(image.getRGB(w, h));
					int grey = rgb.getRed();
					for (int i = 0; i classes.get(i).lowerbound &amp;amp;&amp;amp; grey &amp;lt; classes.get(i).upperbound) {
							int g = i*delta;
							image_temp.setRGB(w,h,(new Color(g, g, g)).getRGB());
						}
					}
				}
			}
		}

		/**
		 * Returns the image created by the processImage method
		 * @return the result image
		 */
		public BufferedImage getResultImage() {
			return image_temp;
		}

		/**
		 * Just for fun: returns the number of loops which were needed for getting a stable result
		 * @return number of loops for stable result
		 */
		public int getLoops(){
			return loops;
		}

		/**
		 * Initializes the algorithm. Creates k ClusterClasses and puts them into a LinkedList
		 * @param image
		 * @param bins
		 */
		@SuppressWarnings(&quot;unchecked&quot;)
		private void initialize(BufferedImage image, int bins, int initway){
			image_temp = image;
			loops = 0;
			changedPixels = 0;
			not_terminated = true;
			classes = new ArrayList();
			for (int i = 0; i &amp;lt; bins; i++) {
				ClusterClass cc = new ClusterClass(createMean(initway, bins, i, image));
				classes.add(cc);
			}

		}

		/**
		 * Controls the calculations of the upper- and lowerbounds of ClusterClasses and sets them
		 *
		 */
		private void calculateBounds() {
			for (int i = 0; i &amp;lt; classes.size(); i++){
				int lb = calculateLowerBound(classes.get(i));
				lowerbounds[i] = lb;
				classes.get(i).setBounds(lb,calculateUpperBound(classes.get(i)) );
				}
		}

		/**
		 * Does the actual calculation of the lowerbound
		 * @param ClusterClass
		 * @return Lowerbound
		 */
		private int calculateLowerBound(ClusterClass cc) {
			int cMean = cc.getMean();
			int currentBound = 0;
			for (int i = 0; i&amp;lt; classes.size(); i++) { 					if (cMean &amp;gt; classes.get(i).getMean()) {
						currentBound = Math.max((cMean + classes.get(i).getMean())/2, currentBound);
					}
					else {
					}
				}
			return currentBound;
			}

		/**
		 * Does the actual calculation of the upperbound
		 * @param ClusterClass
		 * @return Upperbound
		 */
		private int calculateUpperBound(ClusterClass cc) {
				int cMean = cc.getMean();
				int currentBound = 255;
				for (int i = 0; i&amp;lt; classes.size(); i++) {
						if (cMean &amp;lt; classes.get(i).getMean()) {
							currentBound = Math.min((cMean + classes.get(i).getMean())/2, currentBound);
						}
						else {}
					}
				return currentBound;
				}

		/**
		 * Takes care of the recalculation of the means of the ClusterClasses
		 *
		 */
		private void recalculateMeans() {
			for (int i = 0; i= 50) {
				not_terminated = false;
			}
			if (changedPixels &amp;lt;= 300) {
				not_terminated = false;
			}
		}

		private void calculateChangedPixels() {
			int changed = 0;
			for (int i = 0; i&amp;lt; lowerbounds[i]) {
					for (int j = c; j lowerbounds[i]) {
					for (int j = lowerbounds[i]; j&amp;lt; image.getHeight(); h++){
					for (int w = 0; w &amp;lt; image.getWidth(); w++){
						pixelindex+=1;
						if (pixelindex % bins == index) {
							Color rgb = new Color(image.getRGB(w, h));
							sum+= rgb.getRed();
							value+=1;
						}
					}}
				return sum/value;

			case MEAN_BY_SPACE:
				return (int)(255 / (bins-1) * index);
			case MEAN_AT_RANDOM:
				Double dmean = Math.random() * 255;
				return (int) Math.floor(dmean);
			default:
				return 0;
			}
		}
}&lt;/pre&gt;
In addition to this, the custom class ClusterClass is defined as:
&lt;pre lang=&quot;java&quot;&gt;package actions;

/**
 * The ClusterClass is just a class holding the important cluster properties.
 * @author Patrick van Kouteren
 *
 */

public class ClusterClass {
	int mean, upperbound, lowerbound;

	public ClusterClass(int m) {
		mean = m;
	}

	public void setBounds(int lb, int ub) {
		lowerbound = lb;
		upperbound = ub;
	}

	public void setMean(int i) {
		mean = i;
	}

	public int getMean() {
		return mean;
	}

	public int getLowerBound() {
		return lowerbound;
	}

	public int getUpperBound() {
		return upperbound;
	}

	public void calculateMean(int [] histogram) {
		int tempMean = 0;
		int counter = 0;
		for (int i = lowerbound; i&amp;lt;= upperbound; i++) {
			counter += histogram[i];
			tempMean += histogram[i] * i;
		}
		mean = tempMean / counter;
	}

}</pre></p>
<p>The source code might not be completely visible. It can be viewed in a blank screen <a title="View code in blank screen" href="http://www.vankouteren.eu/downloads/KMeansAction.java">here</a>. As mentioned in the replies to this post, I forgot to add the ClusterClass. It can be viewed in a blank screen <a title="ClusterClass" href="http://www.vankouteren.eu/downloads/ClusterClass.java" target="_blank">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.vankouteren.eu/blog/2009/09/k-means-clustering-in-java-code-found/feed/</wfw:commentRss>
		<slash:comments>69</slash:comments>
		</item>
		<item>
		<title>Frequent Itemset Mining implementation in JAVA</title>
		<link>http://www.vankouteren.eu/blog/2008/01/fr/</link>
		<comments>http://www.vankouteren.eu/blog/2008/01/fr/#comments</comments>
		<pubDate>Tue, 15 Jan 2008 15:38:07 +0000</pubDate>
		<dc:creator>Patrick van Kouteren</dc:creator>
				<category><![CDATA[JAVA]]></category>
		<category><![CDATA[frequent]]></category>
		<category><![CDATA[itemset]]></category>
		<category><![CDATA[mining]]></category>

		<guid isPermaLink="false">http://www.vankouteren.eu/blog/?p=8</guid>
		<description><![CDATA[Huge datasets, often containing important operational knowledge, defy standard data analysis methods. Traditional data analysis methods do not easily scale from analyzing megabytes of data to analyzing terra- or peta-bytes of data, nor from analyzing low dimensional data to analyzing very high dimensional data. Furthermore, results may become difficult or almost impossible to interpret by [...]]]></description>
			<content:encoded><![CDATA[            <script type="text/javascript" src="http://www.vankouteren.eu/blog/wp-content/plugins/wordpress-code-snippet/scripts/shBrushXml.js"></script>
            <script type="text/javascript" src="http://www.vankouteren.eu/blog/wp-content/plugins/wordpress-code-snippet/scripts/shBrushJava.js"></script>
<p>Huge datasets, often containing important operational knowledge, defy standard data analysis methods. Traditional data analysis methods do not easily scale from analyzing megabytes of data to analyzing terra- or peta-bytes of data, nor from analyzing low dimensional data to analyzing very high dimensional data. Furthermore, results may become difficult or almost impossible to interpret by the end-user because of their size and complexity. These are several of the problems that novel data mining methods try to solve. Frequent Itemset Mining focuses on deriving association rules which can then be used to classify new incoming data. The classic example is the shopping cart example with the ‘myth’: people who buy diapers also buy beer. If there is a large confidence of the rule D(iapers) =&gt; B(eer), it will actually be there in the ouput of the algorithm. For a concern this is perhaps nice to know, so that they can adjust their shop to it (like putting the diapers close to the beer or something) and their sales (if you buy an extra pack of diapers, you get a 50% discount on beer).<br />
There is a large variety of Frequent Itemset Mining algorithms available on the internet. Because none of them was of direct use, I’ve made an implementation itself. It has its known downsides (see below), but it hopefully provides a start for people who want to do more with FIM.<br />
With this Frequent Itemset Mining implementation I’ve implemented 2 algorithms which are capable of doing this: The Apriori algorithm and the FP-Tree algorithm. Note that these packages are not created by me.</p>
<p><strong>Input of the program / code:</strong><br />
A “.data” comma separated file.</p>
<p><strong>Known downsides of the program / code:</strong><br />
&gt; The user is asked for two classes when performing the scanning algorithm.<br />
There are a lot of cases where there are more than two classes in a data file.<br />
For making it possible to handle these files, the code just has to be adjusted<br />
slightly: the algorithm must look itself for the number of different classes<br />
and perform the partitionscans on all these different classes.<br />
&gt; File rewriting is necessary at this point for the algorithm to work. The<br />
speed could be much improved if this isn't necessary any more. For that the<br />
code for these algorithms needs to be rewritten to handle lists directly.<br />
&gt; The hash function which is present in the program is pretty basic and<br />
probably not sufficient for large datasets. This could be solved by<br />
implementing a stronger hash function (or using JAVA's hash function).<br />
In overall, I've tried to keep all functions as generic as possible so that<br />
further extension is actually possible, so in that point of view, the code that<br />
I've written is pretty scalable and by adjusting some functions (hashfunction<br />
and scanning parameters) slightly, it can be even more scalable. All CSV files<br />
can be read and the program reacts apropriate on the incoming data. If the data<br />
is correct and it can be handled, the algorithm can start working with this<br />
input and it produces a result file.<br />
I was also surprised to see how many warnings my Eclipse environment generated<br />
for the used source codes. Most of them can be solved directly, but some need<br />
more time.</p>
<p><strong>Download</strong><br />
The JAR file, source and test input file can be found in the <a href="http://www.vankouteren.eu/blog/?page_id=6" title="download section">download section</a>.</p>
<p>Find more on Frequent Itemset Mining: <a href="http://www.google.nl/search?source=ig&amp;hl=nl&amp;rlz=&amp;q=Frequent+Itemset+Mining&amp;btnG=Google+zoeken" target="_blank" title="More on Frequent Itemset Mining">http://www.google.nl/search?source=ig&amp;hl=nl&amp;rlz=&amp;q=Frequent+Itemset+Mining&amp;btnG=Google+zoeken</a><br />
More on Association Rule learning:<br />
<a href="http://www.google.nl/search?hl=nl&amp;q=Association+Rule+Learning&amp;btnG=Zoeken" target="_blank" title="More on Association Rule learning"> http://www.google.nl/search?hl=nl&amp;q=Association+Rule+Learning&amp;btnG=Zoeken</a></p>
<p>Library references:<br />
CSVReader: OpenCSV (<a href="http://opencsv.sourceforge.net" title="OpenCSV" target="_blank">http://opencsv.sourceforge.net</a>)<br />
Hash function: <a href="http://www.cs.usfca.edu/galles/cs245/hash.java.html" title="Hash function" target="_blank">http://www.cs.usfca.edu/galles/cs245/hash.java.html</a><br />
Apriori algorithm: <a href="http://www2.cs.uregina.ca/~dbd/cs831/notes/itemsets/itemset_prog1.html" title="Apriori algorithm" target="_blank">http://www2.cs.uregina.ca/~dbd/cs831/notes/itemsets/itemset_prog1.html</a><br />
FPGrowth algorithm: <a href="http://www.csc.liv.ac.uk/~frans/KDD/Software/FPGrowth/fpGrowth.html" title="FPGrowth algorithm" target="_blank">http://www.csc.liv.ac.uk/~frans/KDD/Software/FPGrowth/fpGrowth.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.vankouteren.eu/blog/2008/01/fr/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>K-means clustering implementation in JAVA</title>
		<link>http://www.vankouteren.eu/blog/2007/10/k-means-clustering-implementation-in-java/</link>
		<comments>http://www.vankouteren.eu/blog/2007/10/k-means-clustering-implementation-in-java/#comments</comments>
		<pubDate>Thu, 18 Oct 2007 18:29:44 +0000</pubDate>
		<dc:creator>Patrick van Kouteren</dc:creator>
				<category><![CDATA[JAVA]]></category>
		<category><![CDATA[clustering]]></category>
		<category><![CDATA[k-means]]></category>

		<guid isPermaLink="false">http://www.vankouteren.eu/blog/?p=5</guid>
		<description><![CDATA[Details about K-Means Clustering on images: Before the algorithm starts, the user needs to set a number of greyvalues (bins). The resulting image will contain that number of greyvalues. With that number of bins (called ‘k’) the algorithm clusters the greyvalues of the image into k clusters and once the algorithm is terminated, every cluster [...]]]></description>
			<content:encoded><![CDATA[            <script type="text/javascript" src="http://www.vankouteren.eu/blog/wp-content/plugins/wordpress-code-snippet/scripts/shBrushXml.js"></script>
            <script type="text/javascript" src="http://www.vankouteren.eu/blog/wp-content/plugins/wordpress-code-snippet/scripts/shBrushJava.js"></script>
<p class="MsoNormal"><strong><span lang="EN-GB">Details about K-Means Clustering on images:</span></strong><span lang="EN-GB"></span></p>
<p class="MsoNormal"><span lang="EN-GB">Before the algorithm starts, the user needs to set a number of greyvalues (bins). The resulting image will contain that number of greyvalues.<br />
With that number of bins (called ‘k’) the algorithm clusters the greyvalues of the image into k clusters and once the algorithm is terminated, every cluster will have its own greyvalue.<br />
With starting the algorithm, you should set:</span></p>
<ul type="disc">
<li class="MsoNormal"><span lang="EN-GB">How to define the ‘startingmeans’ of the      clusters before the first iteration.</span></li>
<li class="MsoNormal"><span lang="EN-GB">What the stopping criteria are.</span></li>
</ul>
<p class="MsoNormal"><span lang="EN-GB"> </span></p>
<p class="MsoNormal"><strong><span lang="EN-GB">The Algorithm:</span></strong><span lang="EN-GB"></span></p>
<p class="MsoNormal"><span lang="EN-GB">In short this is what the algorithm is supposed to do:<br />
Initialize (so set k, set ‘startingmeans’, set stopping criteria)<br />
Loop while termination condition isn’t met (</span></p>
<ul type="disc">
<li class="MsoNormal"><span lang="EN-GB">For each pixel: assign the pixel to a      class such that the distance from the pixel to the center (the mean) of a      class is minimalized.</span></li>
<li class="MsoNormal"><span lang="EN-GB">For each class: recalculate the means of      the class based on the pixels belonging to that class.</span></li>
</ul>
<p><span lang="EN-GB">)</span></p>
<p class="MsoNormal"><strong><span lang="EN-GB">My implementation:</span></strong><span lang="EN-GB"></span></p>
<p class="MsoNormal"><span lang="EN-GB">The user can set his k (which is fairly easy).<br />
I’ve implemented 3 ways to choose the ‘startingmeans’ this far:</span></p>
<ol type="1">
<li class="MsoNormal"><span lang="EN-GB">i mod k class: The pixel at index i is      assigned to the class i modulo k</span></li>
<li class="MsoNormal"><span lang="EN-GB">Distribute mean table over color space:      According to the k that’s chosen the means are chosen so that the are      spreaded equally over the complete color space of the image.</span></li>
<li class="MsoNormal"><span lang="EN-GB">Random: Just as it says. Given a k, there      will be chosen k random mean values.</span></li>
</ol>
<p class="MsoNormal"><span lang="EN-GB">The termination constraints are currently not visible for users and are set to:<br />
Terminate after fewer than n pixels change classes after a recalculation of the means.<br />
I’ve set my n to 300 which is pretty small if you are using images bigger than 512 by 512 pixels. Next to that, the algorithm will be terminated if there are more than j iterations needed to get a stable result (in the meanings of that there are not more than n pixels changing classes after a recalculation of the means). My j is currently set to 50. Most of the times the algorithm terminates because of less than 300 pixels have changed classes.</span></p>
<p class="MsoNormal"><span lang="EN-GB">Now that we’ve seen how the parameters of the algorithm are set, let’s have a look how I’ve implemented the algorithm in terms of code and decisions I’ve made.</span></p>
<p class="MsoNormal"><span lang="EN-GB">I’ve devided the code over 3 classes:</span></p>
<p class="MsoNormal"><span lang="EN-GB">1 to build the JDialog which is needed to ask for the input of the user concerning the way the algorithm needs to be initiated.<br />
One with the actual algorithm and the last class is a clusterclass.</span></p>
<p class="MsoNormal"><span lang="EN-GB">Because the class with the JDialog is not that interesting, we’ll focus on the other two classes.</span></p>
<p class="MsoNormal"><span lang="EN-GB">The ClusterClass is pretty simple: it only holds a mean, an upperbound and a lowerbound.<br />
I’ve chosen for the fact that this class holds the bounds because at the initialization of the algorithm, there are k classes which are created (and put into an ArrayList). You can let each class hold it’s own pixels which are belonging to that class, but if your k grows and the image is big, the complete image will be twice in the memory: as the original image and all pixels will be part of one of the clusterclasses as well. Instead of that I’ve chosen to hold the bounds of that class so that if I’m checking pixelvalues, it can also check to which class it belongs in the same for-loop.</span></p>
<p class="MsoNormal"><span lang="EN-GB">As mentioned earlier: a pixel belongs to a class if the distance from that pixelvalue to the mean of a class is minimized. Because my ClusterClasses hold their upper- and lowerbound, a pixelvalue has to lay between the bounds to be part of that class. The bounds are simply calculated by checking which mean is the nearest (but have a lower value for the lowerbound and a higher bound for the upperbound). The bound can simply be calculated by taking the mean of these two means.<br />
After every pixel is assigned to a class (In my case: it can check to which class it belongs). The means of the classes can be recalculated by taking the sum of all the pixelvalues belonging to that clusterclass and divide this sum by the number of pixels in the clusterclass.<br />
After the recalculations of the means, the upper- and lowerbounds need to be recalculated as well.<br />
After this iteration, the termination condition has to be checked. If the condition isn’t met, another iteration follows. If the condition is met, the clusters are set and the colors of the image can be recalculated.</span></p>
<p class="MsoNormal"><strong><span lang="EN-GB">And now shortly in JAVA:</span></strong><span lang="EN-GB"></span></p>
<p class="MsoNormal"><span lang="EN-GB">public KMeansAction:</span></p>
<p class="MsoNormal"><span lang="EN-GB">initialize<br />
calculateBounds<br />
while (not_terminated) do:</span></p>
<ul type="disc">
<li class="MsoNormal"><span lang="EN-GB">recalculateMeans</span></li>
<li class="MsoNormal"><span lang="EN-GB">recalculateBounds</span></li>
<li class="MsoNormal"><span lang="EN-GB">checkTermination</span></li>
</ul>
<p class="MsoNormal"><span lang="EN-GB">processImage</span></p>
<p class="MsoNormal"><span lang="EN-GB">private void processImage:</span></p>
<p class="MsoNormal"><span lang="EN-GB">// This works for 8-bit greyscale images<br />
// It calculates the greyvalues that will occur in the resulting image<br />
delta = 255 / ( k – 1)<br />
for every pixel do:<br />
for every class do:<br />
if a pixel belongs to that class then</span></p>
<p class="MsoNormal">// set the greyvalue of that pixel to the index of the class in the list times delta</p>
<p class="MsoNormal"><span lang="EN-GB"> greyvalue = classindex * delta<br />
// then set the rgbvalue of that pixel to the greyvalue<br />
newImage.setRGB(pixel location, greyvalue)</span></p>
<p class="MsoNormal">
<p class="MsoNormal"><span lang="EN-GB">NOTE (August 7, 2009): I've found the source code and put it in <a title="K-means clustering source code blogpost" href="http://www.vankouteren.eu/blog/2009/09/k-means-clustering-in-java-code-found/">this blogpost.</a></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.vankouteren.eu/blog/2007/10/k-means-clustering-implementation-in-java/feed/</wfw:commentRss>
		<slash:comments>60</slash:comments>
		</item>
	</channel>
</rss>

