Extracting Dominant Color: RGB Averaging Doesn’t Work

This makes sense – two colors can have the same R values, but wildly different G and B values. The result of averaging them will bear no relation to the originals.

However just to prove it, it was very easy to tweak my code to average the RGB values instead of counting the hues. The result for the same four photos is as follows. If the color is really prevalent, the result isn’t so different, but in the case where it isn’t, this way doesn’t really work at all.

Source Code

package ui;

import processing.core.PApplet;
import processing.core.PImage;

@SuppressWarnings("serial")
public class RGBImageViewApplet extends PApplet {

	PImage img;
	float r;
	float g;
	float b;

	public void setup() {
		size(640,600);
		background(0);
		img = loadImage("" /* Your image here */);
		colorMode(RGB);
		extractColorFromImage();
	}

	public void draw() {
		image(img, 0, 0, 640, 480);
		fill(r, g, b);
		rect(0, 480, 640, 120);
	}

	private void extractColorFromImage() {
		img.loadPixels();
		int numberOfPixels = img.pixels.length;
		float totalRed = 0f;
		float totalGreen = 0f;
		float totalBlue = 0f;

		for (int i = 0; i < numberOfPixels; i++) {
			int pixel = img.pixels[i];
			totalRed += red(pixel);
			totalGreen += green(pixel);
			totalBlue += blue(pixel);
		}

		// Set the vars for displaying the color.
		r = totalRed / numberOfPixels;
		g = totalGreen / numberOfPixels;
		b = totalBlue / numberOfPixels;	
	}
}

Leave a Reply