Monday 28 January 2013

Color Sampling and Conversion


Color Sampling and Conversion

Here’s an example that demonstrates how you work with
colors in a expression. The idea here is that you want to
vary the opacity of an animated small layer based on the
lightness (or luminosity) of the pixels of a background
layer that currently happen to be under the moving layer.
The smaller layer will become more transparent as it passes
over dark areas of the background and more opaque as it
passes over lighter areas. Fortunately, the expression language
supplies a couple of useful tools to help out.
Before examining the expression, we need to talk about
the way color data is represented in expressions. An individual
color channel (red, blue, green, hue, saturation,
lightness, or alpha) is represented as a number between
0.0 (fully off) and 1.0 (fully on). A complete color space
representation consists of an array of four such channels.
Most of the time you’ll be working in red, blue, green,
and alpha (RGBA) color space, but you can convert to
and from hue, saturation, lightness, and alpha (HSLA)
color space. This example uses sampleImage() to extract
RGBA data from a target layer called background. Then
rgbToHsl() converts the RGBA data to HSLA color space
so that you can extract the lightness channel, which will
then be used to drive the Opacity parameter of the small
animated layer. Here’s the expression:

sampleSize = [width, height]/2;
target = thisComp.layer("background");
rgba = target.sampleImage(transform.position,
sampleSize, true, time);
hsla = rgbToHsl(rgba);
hsla[2]*100
First you create the variable sampleSize and set its value as
an array consisting of half the width and height of the layer
whose opacity will be controlled with the expression. Essentially
this means that you’ll be sampling all of the pixels of
the background layer that are under smaller layers at any
given time.
The second line just creates the variable target, which will
be a shorthand way to refer to the background layer. Then
sampleImage() retrieves the RGBA data for the area of the
background under the smaller layer and stores the resulting
array in the variable rgba. See the sidebar “More About
sampleImage()” earlier in the chapter for details on all the
parameters of sampleImage().
Next rgbToHsl() converts the RGBA data to HSLA color
space and stores the result in variable hsla. Finally, because
the lightness channel is the third value in the HSLA array
you use the array index of [2] to extract it (see the “Arrays”
section of the JavaScript guide if this doesn’t make sense
to you). Because it will be a value between 0.0 and 1.0, you
just need to multiply it by 100 to get it into a range suitable
to control the Opacity parameter.

No comments:

Post a Comment