]> git.imager.perl.org - imager.git/blob - lib/Imager/Filters.pod
Update metadata to meta-spec 2, include web view of repository, correct EUMM version...
[imager.git] / lib / Imager / Filters.pod
1 =head1 NAME
2
3 Imager::Filters - Entire Image Filtering Operations
4
5 =head1 SYNOPSIS
6
7   use Imager;
8
9   $img = ...;
10
11   $img->filter(type=>'autolevels');
12   $img->filter(type=>'autolevels', lsat=>0.2);
13   $img->filter(type=>'turbnoise')
14
15   # and lots of others
16
17   load_plugin("dynfilt/dyntest.so")
18     or die "unable to load plugin\n";
19
20   $img->filter(type=>'lin_stretch', a=>35, b=>200);
21
22   unload_plugin("dynfilt/dyntest.so")
23     or die "unable to load plugin\n";
24
25   $out = $img->difference(other=>$other_img);
26
27 =head1 DESCRIPTION
28
29 Filters are operations that have similar calling interface.
30
31 =over
32
33 =item filter()
34
35 Parameters:
36
37 =over
38
39 =item *
40
41 type - the type of filter, see L</Types of Filters>.
42
43 =item *
44
45 many other possible parameters, see L</Types of Filters> below.
46
47 =back
48
49 Returns the invocant (C<$self>) on success, returns a false value on
50 failure.  You can call C<< $self->errstr >> to determine the cause of
51 the failure.
52
53   $self->filter(type => $type, ...)
54     or die $self->errstr;
55
56 =back
57
58 =head2 Types of Filters
59
60 Here is a list of the filters that are always available in Imager.
61 This list can be obtained by running the C<filterlist.perl> script
62 that comes with the module source.
63
64   Filter          Arguments   Default value
65   autolevels      lsat        0.1
66                   usat        0.1
67
68   autolevels_skew lsat        0.1
69                   usat        0.1
70                   skew        0
71
72   bumpmap         bump lightx lighty
73                   elevation   0
74                   st          2
75
76   bumpmap_complex bump
77                   channel     0
78                   tx          0
79                   ty          0
80                   Lx          0.2
81                   Ly          0.4
82                   Lz          -1 
83                   cd          1.0 
84                   cs          40.0
85                   n           1.3
86                   Ia          (0 0 0)
87                   Il          (255 255 255)
88                   Is          (255 255 255)
89
90   contrast        intensity
91
92   conv            coef
93
94   fountain        xa ya xb yb
95                   ftype        linear
96                   repeat       none
97                   combine      none
98                   super_sample none
99                   ssample_param 4
100                   segments(see below)
101
102   gaussian        stddev
103
104   gradgen         xo yo colors 
105                   dist         0
106
107   hardinvert
108
109   hardinvertall
110
111   mosaic          size         20
112
113   noise           amount       3
114                   subtype      0
115
116   postlevels      levels       10
117
118   radnoise        xo           100
119                   yo           100
120                   ascale       17.0
121                   rscale       0.02
122
123   turbnoise       xo           0.0
124                   yo           0.0
125                   scale        10.0
126
127   unsharpmask     stddev       2.0
128                   scale        1.0
129
130   watermark       wmark
131                   pixdiff      10
132                   tx           0
133                   ty           0
134
135 All parameters must have some value but if a parameter has a default
136 value it may be omitted when calling the filter function.
137
138 Every one of these filters modifies the image in place.
139
140 If none of the filters here do what you need, the
141 L<Imager::Engines/transform()> or L<Imager::Engines/transform2()>
142 function may be useful.
143
144 =for stopwords
145 autolevels bumpmap bumpmap_complex conv gaussian hardinvert hardinvertall
146 radnoise turbnoise unsharpmask gradgen postlevels
147
148 A reference of the filters follows:
149
150 =over
151
152 =item autolevels
153
154 Scales the luminosity of the image so that the luminosity will cover
155 the possible range for the image.  C<lsat> and C<usat> truncate the
156 range by the specified fraction at the top and bottom of the range
157 respectively.
158
159   # increase contrast, losing little detail
160   $img->filter(type=>"autolevels")
161     or die $img->errstr;
162
163 The method used here is typically called L<Histogram
164 Equalization|http://en.wikipedia.org/wiki/Histogram_equalization>.
165
166 =item autolevels_skew
167
168 Scales the value of each channel so that the values in the image will
169 cover the whole possible range for the channel.  C<lsat> and C<usat>
170 truncate the range by the specified fraction at the top and bottom of
171 the range respectively.
172
173   # increase contrast per channel, losing little detail
174   $img->filter(type=>"autolevels_skew")
175     or die $img->errstr;
176
177   # increase contrast, losing 20% of highlight at top and bottom range
178   $img->filter(type=>"autolevels", lsat=>0.2, usat=>0.2)
179     or die $img->errstr;
180
181 This filter was the original C<autolevels> filter, but it's typically
182 useless due to the significant color skew it can produce.
183
184 =item bumpmap
185
186 uses the channel C<elevation> image C<bump> as a bump map on your
187 image, with the light at (C<lightx>, C<lightty>), with a shadow length
188 of C<st>.
189
190   $img->filter(type=>"bumpmap", bump=>$bumpmap_img,
191                lightx=>10, lighty=>10, st=>5)
192     or die $img->errstr;
193
194 =item bumpmap_complex
195
196 uses the channel C<channel> image C<bump> as a bump map on your image.
197 If C<< Lz < 0 >> the three L parameters are considered to be the
198 direction of the light.  If C<< Lz > 0 >> the L parameters are
199 considered to be the light position.  C<Ia> is the ambient color,
200 C<Il> is the light color, C<Is> is the color of specular highlights.
201 C<cd> is the diffuse coefficient and C<cs> is the specular
202 coefficient.  C<n> is the shininess of the surface.
203
204   $img->filter(type=>"bumpmap_complex", bump=>$bumpmap_img)
205     or die $img->errstr;
206
207 =item contrast
208
209 scales each channel by C<intensity>.  Values of C<intensity> < 1.0
210 will reduce the contrast.
211
212   # higher contrast
213   $img->filter(type=>"contrast", intensity=>1.3)
214     or die $img->errstr;
215
216   # lower contrast
217   $img->filter(type=>"contrast", intensity=>0.8)
218     or die $img->errstr;
219
220 =item conv
221
222 performs 2 1-dimensional convolutions on the image using the values
223 from C<coef>.  C<coef> should be have an odd length and the sum of the
224 coefficients must be non-zero.
225
226   # sharper
227   $img->filter(type=>"conv", coef=>[-0.5, 2, -0.5 ])
228     or die $img->errstr;
229
230   # blur
231   $img->filter(type=>"conv", coef=>[ 1, 2, 1 ])
232     or die $img->errstr;
233
234   # error
235   $img->filter(type=>"conv", coef=>[ -0.5, 1, -0.5 ])
236     or die $img->errstr;
237
238 =item fountain
239
240 renders a fountain fill, similar to the gradient tool in most paint
241 software.  The default fill is a linear fill from opaque black to
242 opaque white.  The points C<A(Cxa, ya)> and C<B(xb, yb)> control the
243 way the fill is performed, depending on the C<ftype> parameter:
244
245 =for stopwords ramping
246
247 =over
248
249 =item C<linear>
250
251 the fill ramps from A through to B.
252
253 =item C<bilinear>
254
255 the fill ramps in both directions from A, where AB defines the length
256 of the gradient.
257
258 =item C<radial>
259
260 A is the center of a circle, and B is a point on it's circumference.
261 The fill ramps from the center out to the circumference.
262
263 =item C<radial_square>
264
265 A is the center of a square and B is the center of one of it's sides.
266 This can be used to rotate the square.  The fill ramps out to the
267 edges of the square.
268
269 =item C<revolution>
270
271 A is the center of a circle and B is a point on its circumference.  B
272 marks the 0 and 360 point on the circle, with the fill ramping
273 clockwise.
274
275 =item C<conical>
276
277 A is the center of a circle and B is a point on it's circumference.  B
278 marks the 0 and point on the circle, with the fill ramping in both
279 directions to meet opposite.
280
281 =back
282
283 The C<repeat> option controls how the fill is repeated for some
284 C<ftype>s after it leaves the AB range:
285
286 =over
287
288 =item C<none>
289
290 no repeats, points outside of each range are treated as if they were
291 on the extreme end of that range.
292
293 =item C<sawtooth>
294
295 the fill simply repeats in the positive direction
296
297 =item C<triangle>
298
299 the fill repeats in reverse and then forward and so on, in the
300 positive direction
301
302 =item C<saw_both>
303
304 the fill repeats in both the positive and negative directions (only
305 meaningful for a linear fill).
306
307 =item C<tri_both>
308
309 as for triangle, but in the negative direction too (only meaningful
310 for a linear fill).
311
312 =back
313
314 By default the fill simply overwrites the whole image (unless you have
315 parts of the range 0 through 1 that aren't covered by a segment), if
316 any segments of your fill have any transparency, you can set the
317 I<combine> option to 'normal' to have the fill combined with the
318 existing pixels.  See the description of I<combine> in L<Imager::Fill>.
319
320 If your fill has sharp edges, for example between steps if you use
321 repeat set to 'triangle', you may see some aliased or ragged edges.
322 You can enable super-sampling which will take extra samples within the
323 pixel in an attempt anti-alias the fill.
324
325 The possible values for the super_sample option are:
326
327 =over
328
329 =item none
330
331 no super-sampling is done
332
333 =item grid
334
335 a square grid of points are sampled.  The number of points sampled is
336 the square of ceil(0.5 + sqrt(ssample_param)).
337
338 =item random
339
340 a random set of points within the pixel are sampled.  This looks
341 pretty bad for low ssample_param values.
342
343 =item circle
344
345 the points on the radius of a circle within the pixel are sampled.
346 This seems to produce the best results, but is fairly slow (for now).
347
348 =back
349
350 You can control the level of sampling by setting the ssample_param
351 option.  This is roughly the number of points sampled, but depends on
352 the type of sampling.
353
354 The segments option is an arrayref of segments.  You really should use
355 the L<Imager::Fountain> class to build your fountain fill.  Each
356 segment is an array ref containing:
357
358 =over
359
360 =item start
361
362 a floating point number between 0 and 1, the start of the range of
363 fill parameters covered by this segment.
364
365 =item middle
366
367 a floating point number between start and end which can be used to
368 push the color range towards one end of the segment.
369
370 =item end
371
372 a floating point number between 0 and 1, the end of the range of fill
373 parameters covered by this segment.  This should be greater than
374 start.
375
376 =item c0
377
378 =item c1
379
380 The colors at each end of the segment.  These can be either
381 Imager::Color or Imager::Color::Float objects.
382
383 =item segment type
384
385 The type of segment, this controls the way the fill parameter varies
386 over the segment. 0 for linear, 1 for curved (unimplemented), 2 for
387 sine, 3 for sphere increasing, 4 for sphere decreasing.
388
389 =item color type
390
391 The way the color varies within the segment, 0 for simple RGB, 1 for
392 hue increasing and 2 for hue decreasing.
393
394 =back
395
396 Don't forget to use Imager::Fountain instead of building your own.
397 Really.  It even loads GIMP gradient files.
398
399   # build the gradient the hard way - linear from black to white,
400   # then back again
401   my @simple =
402    (
403      [   0, 0.25, 0.5, 'black', 'white', 0, 0 ],
404      [ 0.5. 0.75, 1.0, 'white', 'black', 0, 0 ],
405    );
406   # across
407   my $linear = $img->copy;
408   $linear->filter(type     => "fountain",
409                   ftype    => 'linear',
410                   repeat   => 'sawtooth',
411                   segments => \@simple,
412                   xa       => 0,
413                   ya       => $linear->getheight / 2,
414                   xb       => $linear->getwidth - 1,
415                   yb       => $linear->getheight / 2)
416     or die $linear->errstr;
417   # around
418   my $revolution = $img->copy;
419   $revolution->filter(type     => "fountain",
420                       ftype    => 'revolution',
421                       segments => \@simple,
422                       xa       => $revolution->getwidth / 2,
423                       ya       => $revolution->getheight / 2,
424                       xb       => $revolution->getwidth / 2,
425                       yb       => 0)
426     or die $revolution->errstr;
427   # out from the middle
428   my $radial = $img->copy;
429   $radial->filter(type     => "fountain",
430                   ftype    => 'radial',
431                   segments => \@simple,
432                   xa       => $im->getwidth / 2,
433                   ya       => $im->getheight / 2,
434                   xb       => $im->getwidth / 2,
435                   yb       => 0)
436     or die $radial->errstr;
437
438 =for stopwords Gaussian
439                            
440 =item gaussian
441
442 performs a Gaussian blur of the image, using C<stddev> as the standard
443 deviation of the curve used to combine pixels, larger values give
444 bigger blurs.  For a definition of Gaussian Blur, see:
445
446   http://www.maths.abdn.ac.uk/~igc/tch/mx4002/notes/node99.html
447
448 Values of C<stddev> around 0.5 provide a barely noticeable blur,
449 values around 5 provide a very strong blur.
450
451   # only slightly blurred
452   $img->filter(type=>"gaussian", stddev=>0.5)
453     or die $img->errstr;
454
455   # more strongly blurred
456   $img->filter(type=>"gaussian", stddev=>5)
457     or die $img->errstr;
458
459 =item gradgen
460
461 renders a gradient, with the given I<colors> at the corresponding
462 points (x,y) in C<xo> and C<yo>.  You can specify the way distance is
463 measured for color blending by setting C<dist> to 0 for Euclidean, 1
464 for Euclidean squared, and 2 for Manhattan distance.
465
466   $img->filter(type="gradgen", 
467                xo=>[ 10, 50, 10 ], 
468                yo=>[ 10, 50, 50 ],
469                colors=>[ qw(red blue green) ]);
470
471 =item hardinvert
472 X<filters, hardinvert>X<hardinvert>
473
474 inverts the image, black to white, white to black.  All color channels
475 are inverted, excluding the alpha channel if any.
476
477   $img->filter(type=>"hardinvert")
478     or die $img->errstr;
479
480 =item hardinvertall
481 X<filters, hardinvertall>X<hardinvertall>
482
483 inverts the image, black to white, white to black.  All channels are
484 inverted, including the alpha channel if any.
485
486   $img->filter(type=>"hardinvertall")
487     or die $img->errstr;
488
489 =item mosaic
490
491 produces averaged tiles of the given C<size>.
492
493   $img->filter(type=>"mosaic", size=>5)
494     or die $img->errstr;
495
496 =item noise
497
498 adds noise of the given C<amount> to the image.  If C<subtype> is
499 zero, the noise is even to each channel, otherwise noise is added to
500 each channel independently.
501
502   # monochrome noise
503   $img->filter(type=>"noise", amount=>20, subtype=>0)
504     or die $img->errstr;
505
506   # color noise
507   $img->filter(type=>"noise", amount=>20, subtype=>1)
508     or die $img->errstr;
509
510 =for stopwords Perlin
511
512 =item radnoise
513
514 renders radiant Perlin turbulent noise.  The center of the noise is at
515 (C<xo>, C<yo>), C<ascale> controls the angular scale of the noise ,
516 and C<rscale> the radial scale, higher numbers give more detail.
517
518   $img->filter(type=>"radnoise", xo=>50, yo=>50,
519                ascale=>1, rscale=>0.02)
520     or die $img->errstr;
521
522 =item postlevels
523
524 alters the image to have only C<levels> distinct level in each
525 channel.
526
527   $img->filter(type=>"postlevels", levels=>10)
528     or die $img->errstr;
529
530 =item turbnoise
531
532 renders Perlin turbulent noise.  (C<xo>, C<yo>) controls the origin of
533 the noise, and C<scale> the scale of the noise, with lower numbers
534 giving more detail.
535
536   $img->filter(type=>"turbnoise", xo=>10, yo=>10, scale=>10)
537     or die $img->errstr;
538
539 =for stopwords unsharp
540
541 =item unsharpmask
542
543 performs an unsharp mask on the image.  This increases the contrast of
544 edges in the image.
545
546 This is the result of subtracting a Gaussian blurred version of the
547 image from the original.  C<stddev> controls the C<stddev> parameter
548 of the Gaussian blur.  Each output pixel is:
549
550   in + scale * (in - blurred)
551
552 eg.
553
554   $img->filter(type=>"unsharpmask", stddev=>1, scale=>0.5)
555     or die $img->errstr;
556
557 C<unsharpmark> has the following parameters:
558
559 =for stopwords GIMP GIMP's
560
561 =over
562
563 =item *
564
565 C<stddev> - this is equivalent to the C<Radius> value in the GIMP's
566 unsharp mask filter.  This controls the size of the contrast increase
567 around edges, larger values will remove fine detail. You should
568 probably experiment on the types of images you plan to work with.
569 Default: 2.0.
570
571 =item *
572
573 C<scale> - controls the strength of the edge enhancement, equivalent
574 to I<Amount> in the GIMP's unsharp mask filter.  Default: 1.0.
575
576 =back
577
578 =item watermark
579
580 applies C<wmark> as a watermark on the image with strength C<pixdiff>,
581 with an origin at (C<tx>, C<ty>)
582
583   $img->filter(type=>"watermark", tx=>10, ty=>50, 
584                wmark=>$wmark_image, pixdiff=>50)
585     or die $img->errstr;
586
587 =back
588
589 A demonstration of most of the filters can be found at:
590
591   http://www.develop-help.com/imager/filters.html
592
593 =head2 External Filters
594
595 As of Imager 0.48 you can create perl or XS based filters and hook
596 them into Imager's filter() method:
597
598 =over
599
600 =item register_filter()
601
602 Registers a filter so it is visible via Imager's filter() method.
603
604   Imager->register_filter(type => 'your_filter',
605                           defaults => { parm1 => 'default1' },
606                           callseq => [ qw/image parm1/ ],
607                           callsub => \&your_filter);
608   $img->filter(type=>'your_filter', parm1 => 'something');
609
610 The following parameters are needed:
611
612 =over
613
614 =item *
615
616 C<type> - the type value that will be supplied to filter() to use your
617 filter.
618
619 =item *
620
621 C<defaults> - a hash of defaults for the filter's parameters
622
623 =item *
624
625 C<callseq> - a reference to an array of required parameter names.
626
627 =item *
628
629 C<callsub> - a code reference called to execute your filter.  The
630 parameters passed to filter() are supplied as a list of parameter
631 name, value ... which can be assigned to a hash.
632
633 The special parameters C<image> and C<imager> are supplied as the low
634 level image object from $self and $self itself respectively.
635
636 The function you supply must modify the image in place.
637
638 To indicate an error, die with an error message followed by a
639 newline. C<filter()> will store the error message as the C<errstr()>
640 for the invocant and return false to indicate failure.
641
642   sub my_filter {
643     my %opts = @_;
644     _is_valid($opts{myparam})
645       or die "myparam invalid!\n";
646
647     # actually do the filtering...
648   }
649
650 =back
651
652 See L<Imager::Filter::Mandelbrot> for an example.
653
654 =back
655
656 =for stopwords DSOs
657
658 =head2 Plug-ins
659
660 The plug in interface is deprecated.  Please use the Imager API, see
661 L<Imager::API> and L</External Filters> for details
662
663 It is possible to add filters to the module without recompiling Imager
664 itself.  This is done by using DSOs (Dynamic shared object) available
665 on most systems.  This way you can maintain your own filters and not
666 have to have it added to Imager, or worse patch every new version of
667 Imager.  Modules can be loaded AND UNLOADED at run time.  This means
668 that you can have a server/daemon thingy that can do something like:
669
670   load_plugin("dynfilt/dyntest.so")
671     or die "unable to load plugin\n";
672
673   $img->filter(type=>'lin_stretch', a=>35, b=>200);
674
675   unload_plugin("dynfilt/dyntest.so")
676     or die "unable to load plugin\n";
677
678 Someone decides that the filter is not working as it should -
679 F<dyntest.c> can be modified and recompiled, and then reloaded:
680
681   load_plugin("dynfilt/dyntest.so")
682     or die "unable to load plugin\n";
683
684   $img->filter(%hsh);
685
686 =for stopwords Linux Solaris HPUX OpenBSD FreeBSD TRU64 OSF1 AIX Win32 OS X
687
688 Note: This has been tested successfully on the following systems:
689 Linux, Solaris, HPUX, OpenBSD, FreeBSD, TRU64/OSF1, AIX, Win32, OS X.
690
691 =over
692
693 =item load_plugin()
694
695 This is a function, not a method, exported by default.  You should
696 import this function explicitly for future compatibility if you need
697 it.
698
699 Accepts a single parameter, the name of a shared library file to load.
700
701 Returns true on success.  Check Imager->errstr on failure.
702
703 =item unload_plugin()
704
705 This is a function, not a method, which is exported by default.  You
706 should import this function explicitly for future compatibility if you
707 need it.
708
709 Accepts a single parameter, the name of a shared library to unload.
710 This library must have been previously loaded by load_plugin().
711
712 Returns true on success.  Check Imager->errstr on failure.
713
714 =back
715
716 A few example plug-ins are included and built (but not installed):
717
718 =over
719
720 =item *
721
722 F<plugins/dyntest.c> - provides the C<null> (no action) filter, and
723 C<lin_stretch> filters.  C<lin_stretch> stretches sample values
724 between C<a> and C<b> out to the full sample range.
725
726 =item *
727
728 F<plugins/dt2.c> - provides the C<html_art> filter that writes the
729 image to the HTML fragment file supplied in C<fname> as a HTML table.
730
731 =item *
732
733 F<plugins/flines.c> - provides the C<flines> filter that dims
734 alternate lines to emulate an old CRT display.
735 L<Imager::Filter::Flines> provides the same functionality.
736
737 =item *
738
739 F<plugins/mandelbrot.c> - provides the C<mandelbrot> filter that
740 renders the Mandelbrot set within the given range of x [-2, 0.5) and y
741 [-1.25, 1,25).  L<Imager::Filter::Mandelbrot> provides a more flexible
742 Mandelbrot set renderer.
743
744 =back
745
746 =head2 Image Difference
747
748 =over
749
750 =item difference()
751
752 You can create a new image that is the difference between 2 other images.
753
754   my $diff = $img->difference(other=>$other_img);
755
756 For each pixel in $img that is different to the pixel in $other_img,
757 the pixel from $other_img is given, otherwise the pixel is transparent
758 black.
759
760 This can be used for debugging image differences ("Where are they
761 different?"), and for optimizing animated GIFs.
762
763 Note that $img and $other_img must have the same number of channels.
764 The width and height of $diff will be the minimum of each of the width
765 and height of $img and $other_img.
766
767 Parameters:
768
769 =over
770
771 =item *
772
773 C<other> - the other image object to compare against
774
775 =item *
776
777 C<mindist> - the difference between corresponding samples must be
778 greater than C<mindist> for the pixel to be considered different.  So
779 a value of zero returns all different pixels, not all pixels.  Range:
780 0 to 255 inclusive.  Default: 0.
781
782 For large sample images this is scaled down to the range 0 .. 1.
783
784 =back
785
786 =back
787
788 =head1 AUTHOR
789
790 Arnar M. Hrafnkelsson, Tony Cook <tonyc@cpan.org>.
791
792 =head1 SEE ALSO
793
794 Imager, Imager::Filter::Flines, Imager::Filter::Mandelbrot
795
796 =head1 REVISION
797
798 $Revision$
799
800 =cut