Sg2.9
Average Color
Recent RSS
Average Color
Date:  24. March 2010, 14:32

Hi,

I'm trying to make a script that will read the average color value of a set of pixels in an image. The user will be able to set the square amout of pixels to be read.
Kind of like the mosaic filter but I want to be able to just get the color values.
So far I have just made 4 for-loops as following:

for py = 0; py < picturesizeY; increase py by square value

for px = 0; px < picturesizeX; increase px by square value

for y = py; y < py + square Value;

for x = px; x < px + square Value;

getPixel(x, y);

}
}
}
}

This is increadably slow. I saw in the reference that there is a function that will read the average color in a rectangle. How would I go about using that instead (and is it faster)?
I want to read the pixel values of the image but not draw on the actual image.

Hope this makes any sense to you all.

Grateful for help!

Re: Average Color
Date:  24. March 2010, 15:43

raster.getAverageColor(rect) tends to be very fast.

Read more about how to make rectangles in the Point, Size and Rectangle tutorial.

The following code should help you on your way:

var rectSize = new Size(30, 20);

var rasters = document.getItems({
	selected: true,
	type: Raster
});

if(rasters.length) {
	var raster = rasters[0];
	var rasterSize = raster.bounds.size;

	var columns = Math.round(rasterSize.width / rectSize.width);
	var rows = Math.round(rasterSize.height / rectSize.height);

	var offset = raster.bounds.bottomLeft;
	
	// loop through rows and columns
	for(var row = 0; row < rows; row++) {
		for(var column = 0; column < columns; column++) {
			var bottomLeft = offset + new Point(column, row) * rectSize;
			var rectangle = new Rectangle(bottomLeft, rectSize);
			var color = raster.getAverageColor(rectangle);
			var path = new Path.Rectangle(rectangle);
			path.fillColor = color;
		}
	}
}
Re: Average Color
Date:  24. March 2010, 16:44

Gr8!!

Thanks a bunch, Jonathan, now it's working like a charm!
Perhaps now I will dare post this script here...

Scripts
08.08.14, 15:24
15.05.14, 14:23
02.03.14, 19:16
18.11.13, 14:48
22.03.13, 03:05
22.02.13, 15:45
Posts
10.01.17, 16:37
19.02.16, 06:03
19.02.16, 06:00
17.01.16, 11:00
12.01.16, 13:10
25.11.15, 08:19
Script of the Moment
Variator 08.01.12