]> git.imager.perl.org - imager.git/blob - lib/Imager/Engines.pod
6437f83191977a871638ae37f7ed85077720dc4d
[imager.git] / lib / Imager / Engines.pod
1 =head1 NAME
2
3 Imager::Engines - Programmable transformation operations
4
5 =head1 SYNOPSIS
6
7   use Imager;
8
9   my %opts;
10   my @imgs;
11   my $img;
12   ...
13
14   my $newimg = $img->transform(
15       xexpr=>'x',
16       yexpr=>'y+10*sin((x+y)/10)')
17     or die $img->errstr;
18
19   my $newimg = Imager::transform2(\%opts, @imgs)
20     or die "transform2 failed: $Imager::ERRSTR";
21
22   my $newimg = $img->matrix_transform(
23      matrix=>[ -1, 0, $img->getwidth-1,
24                 0,  1, 0,
25                 0,  0, 1 ]);
26
27
28 =head1 DESCRIPTION
29
30 =head2 transform
31
32 The C<transform()> function can be used to generate spatial warps and
33 rotations and such effects.  It only operates on a single image and
34 its only function is to displace pixels.
35
36 It can be given the operations in postfix notation or the module
37 Affix::Infix2Postfix can be used to generate postfix code from infix
38 code.  Look in the test case t/t55trans.t for an example.
39
40 C<transform()> needs expressions (or opcodes) that determine the
41 source pixel for each target pixel.  Source expressions are infix
42 expressions using any of the +, -, *, / or ** binary operators, the -
43 unary operator, ( and ) for grouping and the sin() and cos()
44 functions.  The target pixel is input as the variables x and y.
45
46 You specify the x and y expressions as xexpr and yexpr respectively.
47 You can also specify opcodes directly, but that's magic deep enough
48 that you can look at the source code.
49
50 Note: You can still use the transform() function, but the transform2()
51 function is just as fast and is more likely to be enhanced and
52 maintained.
53
54   $new_img=$img->transform(xexpr=>'x',yexpr=>'y+10*sin((x+y)/10)')
55
56   $new_img=$img->transform(xexpr=>'x+0.1*y+5*sin(y/10.0+1.57)',
57                            yexpr=>'y+10*sin((x+y-0.785)/10)') 
58
59 =head2 transform2
60
61 Imager also supports a C<transform2()> class method which allows you
62 perform a more general set of operations, rather than just specifying
63 a spatial transformation as with the transform() method, you can also
64 perform colour transformations, image synthesis and image
65 combinations from multiple source images.
66
67 C<transform2()> takes an reference to an options hash, and a list of
68 images to operate one (this list may be empty):
69
70   my %opts;
71   my @imgs;
72   ...
73   my $img = Imager::transform2(\%opts, @imgs)
74       or die "transform2 failed: $Imager::ERRSTR";
75
76 The options hash may define a transformation function, and optionally:
77
78 =over
79
80 =item *
81
82 width - the width of the image in pixels.  If this isn't supplied the
83 width of the first input image is used.  If there are no input images
84 an error occurs.
85
86 =item *
87
88 height - the height of the image in pixels.  If this isn't supplied
89 the height of the first input image is used.  If there are no input
90 images an error occurs.
91
92 =item *
93
94 constants - a reference to hash of constants to define for the
95 expression engine.  Some extra constants are defined by Imager
96
97 =item *
98
99 channels - the number of channels in the output image.  If this isn't
100 supplied a 3 channel image will be created.
101
102 =back
103
104 The tranformation function is specified using either the expr or
105 rpnexpr member of the options.
106
107 =head3 Infix expressions
108
109 You can supply infix expressions to transform 2 with the expr keyword.
110
111   $opts{expr} = 'return getp1(w-x, h-y)'
112
113 The 'expression' supplied follows this general grammar:
114
115    ( identifier '=' expr ';' )* 'return' expr
116
117 This allows you to simplify your expressions using variables.
118
119 A more complex example might be:
120
121   $opts{expr} = 'pix = getp1(x,y); return if(value(pix)>0.8,pix*0.8,pix)'
122
123 Currently to use infix expressions you must have the L<Parse::RecDescent>
124 module installed (available from CPAN).  There is also what might be a
125 significant delay the first time you run the infix expression parser
126 due to the compilation of the expression grammar.
127
128 =head3 Postfix expressions
129
130 You can supply postfix or reverse-polish notation expressions to
131 transform2() through the rpnexpr keyword.
132
133 The parser for rpnexpr emulates a stack machine, so operators will
134 expect to see their parameters on top of the stack.  A stack machine
135 isn't actually used during the image transformation itself.
136
137 You can store the value at the top of the stack in a variable called
138 foo using !foo and retrieve that value again using @foo.  The !foo
139 notation will pop the value from the stack.
140
141 An example equivalent to the infix expression above:
142
143  $opts{rpnexpr} = 'x y getp1 !pix @pix value 0.8 gt @pix 0.8 * @pix ifp'
144
145 =head3 Operators
146
147 transform2() has a fairly rich range of operators.
148
149 =over
150
151 =item +, *, -, /, %, **
152
153 multiplication, addition, subtraction, division, remainder and
154 exponentiation.  Multiplication, addition and subtraction can be used
155 on colour values too - though you need to be careful - adding 2 white
156 values together and multiplying by 0.5 will give you grey, not white.
157
158 Division by zero (or a small number) just results in a large number.
159 Modulo zero (or a small number) results in zero.  % is implemented
160 using fmod() so you can use this to take a value mod a floating point
161 value.
162
163 =item sin(N), cos(N), atan2(y,x)
164
165 Some basic trig functions.  They work in radians, so you can't just
166 use the hue values.
167
168 =item distance(x1, y1, x2, y2)
169
170 Find the distance between two points.  This is handy (along with
171 atan2()) for producing circular effects.
172
173 =item sqrt(n)
174
175 Find the square root.  I haven't had much use for this since adding
176 the distance() function.
177
178 =item abs(n)
179
180 Find the absolute value.
181
182 =item getp1(x,y), getp2(x,y), getp3(x, y)
183
184 Get the pixel at position (x,y) from the first, second or third image
185 respectively.  I may add a getpn() function at some point, but this
186 prevents static checking of the instructions against the number of
187 images actually passed in.
188
189 =item value(c), hue(c), sat(c), hsv(h,s,v), hsva(h,s,v,alpha)
190
191 Separates a colour value into it's value (brightness), hue (colour)
192 and saturation elements.  Use hsv() to put them back together (after
193 suitable manipulation), or hsva() to include a tranparency value.
194
195 =item red(c), green(c), blue(c), rgb(r,g,b)
196
197 Separates a colour value into it's red, green and blue colours.  Use
198 rgb(r,g,b) to put it back together, or rgba() to include a
199 transparency value.
200
201 =item alpha(c)
202
203 Retrieve the alpha value from a colour.
204
205 =item int(n)
206
207 Convert a value to an integer.  Uses a C int cast, so it may break on
208 large values.
209
210 =item if(cond,ntrue,nfalse), if(cond,ctrue,cfalse)
211
212 A simple (and inefficient) if function.
213
214 =item <=,<,==,>=,>,!=
215
216 Relational operators (typically used with if()).  Since we're working
217 with floating point values the equalities are 'near equalities' - an
218 epsilon value is used.
219
220 =item &&, ||, not(n)
221
222 Basic logical operators.
223
224 =item log(n), exp(n)
225
226 Natural logarithm and exponential.
227
228 =back
229
230 =head3 Constants
231
232 transform2() defines the following constants:
233
234 =over
235
236 =item pi
237
238 The classical constant.
239
240 =item w
241
242 =item h
243
244 The width and height of the output image.
245
246 =item cx
247
248 =item cy
249
250 The center of the output image.
251
252 =item wI<image number>
253
254 =item hI<image number>
255
256 The width and height of each of the input images, C<w1> is the width
257 of the first input image and so on.
258
259 =item cxI<image number>
260
261 =item cyI<image number>
262
263 The center of each of the input images, (C<cx1>, C<cy1>) is the center
264 of the first input image and so on.
265
266 =back
267
268 A few examples:
269
270 =over
271
272 =item rpnexpr=>'x 25 % 15 * y 35 % 10 * getp1 !pat x y getp1 !pix @pix sat 0.7 gt @pat @pix ifp'
273
274 tiles a smaller version of the input image over itself where the
275 colour has a saturation over 0.7.
276
277 =item rpnexpr=>'x 25 % 15 * y 35 % 10 * getp1 !pat y 360 / !rat x y getp1 1 @rat - pmult @pat @rat pmult padd'
278
279 tiles the input image over itself so that at the top of the image the
280 full-size image is at full strength and at the bottom the tiling is
281 most visible.
282
283 =item rpnexpr=>'x y getp1 !pix @pix value 0.96 gt @pix sat 0.1 lt and 128 128 255 rgb @pix ifp'
284
285 replace pixels that are white or almost white with a palish blue
286
287 =item rpnexpr=>'x 35 % 10 * y 45 % 8 * getp1 !pat x y getp1 !pix @pix sat 0.2 lt @pix value 0.9 gt and @pix @pat @pix value 2 / 0.5 + pmult ifp'
288
289 Tiles the input image overitself where the image isn't white or almost
290 white.
291
292 =item rpnexpr=>'x y 160 180 distance !d y 180 - x 160 - atan2 !a @d 10 / @a + 3.1416 2 * % !a2 @a2 180 * 3.1416 / 1 @a2 sin 1 + 2 / hsv'
293
294 Produces a spiral.
295
296 =item rpnexpr=>'x y 160 180 distance !d y 180 - x 160 - atan2 !a @d 10 / @a + 3.1416 2 * % !a2 @a 180 * 3.1416 / 1 @a2 sin 1 + 2 / hsv'
297
298 A spiral built on top of a colour wheel.
299
300 =back
301
302 For details on expression parsing see L<Imager::Expr>.  For details on
303 the virtual machine used to transform the images, see
304 L<Imager::regmach.pod>.
305
306   # generate a colorful spiral
307   # requires that Parse::RecDescent be installed
308   my $newimg = Imager::transform2({
309                                    width => 160, height=>160,
310                                    expr => <<EOS
311   dist = distance(x, y, w/2, h/2);
312   angle = atan2(y-h/2, x-w/2);
313   angle2 = (dist / 10 + angle) % ( 2 * pi );
314   return hsv(angle*180/pi, 1, (sin(angle2)+1)/2);
315   EOS
316                                   });
317
318   # replace green portions of an image with another image
319   my $newimg = Imager::transform2({
320                                    rpnexpr => <<EOS
321   x y getp2 !pat # used to replace green portions
322   x y getp1 !pix # source with "green screen"
323   @pix red 10 lt @pix blue 10 lt && # low blue and red
324   @pix green 254 gt && # and high green
325   @pat @pix ifp
326   EOS
327                                   }, $source, $background);
328
329 =head2 Matrix Transformations
330
331 Rather than having to write code in a little language, you can use a
332 matrix to perform affine transformations, using the matrix_transform()
333 method:
334
335   my $newimg = $img->matrix_transform(matrix=>[ -1, 0, $img->getwidth-1,
336                                             0,  1, 0,
337                                             0,  0, 1 ]);
338
339 By default the output image will be the same size as the input image,
340 but you can supply the xsize and ysize parameters to change the size.
341
342 Rather than building matrices by hand you can use the Imager::Matrix2d
343 module to build the matrices.  This class has methods to allow you to
344 scale, shear, rotate, translate and reflect, and you can combine these
345 with an overloaded multiplication operator.
346
347 WARNING: the matrix you provide in the matrix operator transforms the
348 co-ordinates within the B<destination> image to the co-ordinates
349 within the I<source> image.  This can be confusing.
350
351 You can also supply a C<back> argument which acts as a background
352 color for the areas of the image with no samples available (outside
353 the rectangle of the source image.)  This can be either an
354 Imager::Color or Imager::Color::Float object.  This is B<not> mixed
355 transparent pixels in the middle of the source image, it is B<only>
356 used for pixels where there is no corresponding pixel in the source
357 image.
358
359 =cut