source: ImageMagick/branches/ImageMagick-6/magick/resample.c @ 7579

Revision 7579, 55.9 KB checked in by cristy, 13 months ago (diff)
Line 
1/*
2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3%                                                                             %
4%                                                                             %
5%                                                                             %
6%           RRRR    EEEEE   SSSSS   AAA   M   M  PPPP   L      EEEEE          %
7%           R   R   E       SS     A   A  MM MM  P   P  L      E              %
8%           RRRR    EEE      SSS   AAAAA  M M M  PPPP   L      EEE            %
9%           R R     E          SS  A   A  M   M  P      L      E              %
10%           R  R    EEEEE   SSSSS  A   A  M   M  P      LLLLL  EEEEE          %
11%                                                                             %
12%                                                                             %
13%                      MagickCore Pixel Resampling Methods                    %
14%                                                                             %
15%                              Software Design                                %
16%                                John Cristy                                  %
17%                              Anthony Thyssen                                %
18%                                August 2007                                  %
19%                                                                             %
20%                                                                             %
21%  Copyright 1999-2012 ImageMagick Studio LLC, a non-profit organization      %
22%  dedicated to making software imaging solutions freely available.           %
23%                                                                             %
24%  You may not use this file except in compliance with the License.  You may  %
25%  obtain a copy of the License at                                            %
26%                                                                             %
27%    http://www.imagemagick.org/script/license.php                            %
28%                                                                             %
29%  Unless required by applicable law or agreed to in writing, software        %
30%  distributed under the License is distributed on an "AS IS" BASIS,          %
31%  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
32%  See the License for the specific language governing permissions and        %
33%  limitations under the License.                                             %
34%                                                                             %
35%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36%
37%
38*/
39
40/*
41  Include declarations.
42*/
43#include "magick/studio.h"
44#include "magick/artifact.h"
45#include "magick/color-private.h"
46#include "magick/cache.h"
47#include "magick/draw.h"
48#include "magick/exception-private.h"
49#include "magick/gem.h"
50#include "magick/image.h"
51#include "magick/image-private.h"
52#include "magick/log.h"
53#include "magick/magick.h"
54#include "magick/memory_.h"
55#include "magick/pixel.h"
56#include "magick/pixel-private.h"
57#include "magick/quantum.h"
58#include "magick/random_.h"
59#include "magick/resample.h"
60#include "magick/resize.h"
61#include "magick/resize-private.h"
62#include "magick/transform.h"
63#include "magick/signature-private.h"
64#include "magick/token.h"
65#include "magick/utility.h"
66/*
67  EWA Resampling Options
68*/
69
70/* select ONE resampling method */
71#define EWA 1                 /* Normal EWA handling - raw or clamped */
72                              /* if 0 then use "High Quality EWA" */
73#define EWA_CLAMP 1           /* EWA Clamping from Nicolas Robidoux */
74
75#define FILTER_LUT 1          /* Use a LUT rather then direct filter calls */
76
77/* output debugging information */
78#define DEBUG_ELLIPSE 0       /* output ellipse info for debug */
79#define DEBUG_HIT_MISS 0      /* output hit/miss pixels (as gnuplot commands) */
80#define DEBUG_NO_PIXEL_HIT 0  /* Make pixels that fail to hit anything - RED */
81
82#if ! FILTER_DIRECT
83#define WLUT_WIDTH 1024       /* size of the filter cache */
84#endif
85
86/*
87  Typedef declarations.
88*/
89struct _ResampleFilter
90{
91  CacheView
92    *view;
93
94  Image
95    *image;
96
97  ExceptionInfo
98    *exception;
99
100  MagickBooleanType
101    debug;
102
103  /* Information about image being resampled */
104  ssize_t
105    image_area;
106
107  InterpolatePixelMethod
108    interpolate;
109
110  VirtualPixelMethod
111    virtual_pixel;
112
113  FilterTypes
114    filter;
115
116  /* processing settings needed */
117  MagickBooleanType
118    limit_reached,
119    do_interpolate,
120    average_defined;
121
122  MagickPixelPacket
123    average_pixel;
124
125  /* current ellipitical area being resampled around center point */
126  double
127    A, B, C,
128    Vlimit, Ulimit, Uwidth, slope;
129
130#if FILTER_LUT
131  /* LUT of weights for filtered average in elliptical area */
132  double
133    filter_lut[WLUT_WIDTH];
134#else
135  /* Use a Direct call to the filter functions */
136  ResizeFilter
137    *filter_def;
138
139  double
140    F;
141#endif
142
143  /* the practical working support of the filter */
144  double
145    support;
146
147  size_t
148    signature;
149};
150
151/*
152%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
153%                                                                             %
154%                                                                             %
155%                                                                             %
156%   A c q u i r e R e s a m p l e I n f o                                     %
157%                                                                             %
158%                                                                             %
159%                                                                             %
160%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
161%
162%  AcquireResampleFilter() initializes the information resample needs do to a
163%  scaled lookup of a color from an image, using area sampling.
164%
165%  The algorithm is based on a Elliptical Weighted Average, where the pixels
166%  found in a large elliptical area is averaged together according to a
167%  weighting (filter) function.  For more details see "Fundamentals of Texture
168%  Mapping and Image Warping" a master's thesis by Paul.S.Heckbert, June 17,
169%  1989.  Available for free from, http://www.cs.cmu.edu/~ph/
170%
171%  As EWA resampling (or any sort of resampling) can require a lot of
172%  calculations to produce a distorted scaling of the source image for each
173%  output pixel, the ResampleFilter structure generated holds that information
174%  between individual image resampling.
175%
176%  This function will make the appropriate AcquireVirtualCacheView() calls
177%  to view the image, calling functions do not need to open a cache view.
178%
179%  Usage Example...
180%      resample_filter=AcquireResampleFilter(image,exception);
181%      SetResampleFilter(resample_filter, GaussianFilter, 1.0);
182%      for (y=0; y < (ssize_t) image->rows; y++) {
183%        for (x=0; x < (ssize_t) image->columns; x++) {
184%          u= ....;   v= ....;
185%          ScaleResampleFilter(resample_filter, ... scaling vectors ...);
186%          (void) ResamplePixelColor(resample_filter,u,v,&pixel);
187%          ... assign resampled pixel value ...
188%        }
189%      }
190%      DestroyResampleFilter(resample_filter);
191%
192%  The format of the AcquireResampleFilter method is:
193%
194%     ResampleFilter *AcquireResampleFilter(const Image *image,
195%       ExceptionInfo *exception)
196%
197%  A description of each parameter follows:
198%
199%    o image: the image.
200%
201%    o exception: return any errors or warnings in this structure.
202%
203*/
204MagickExport ResampleFilter *AcquireResampleFilter(const Image *image,
205  ExceptionInfo *exception)
206{
207  register ResampleFilter
208    *resample_filter;
209
210  assert(image != (Image *) NULL);
211  assert(image->signature == MagickSignature);
212  if (image->debug != MagickFalse)
213    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
214  assert(exception != (ExceptionInfo *) NULL);
215  assert(exception->signature == MagickSignature);
216
217  resample_filter=(ResampleFilter *) AcquireMagickMemory(
218    sizeof(*resample_filter));
219  if (resample_filter == (ResampleFilter *) NULL)
220    ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
221  (void) ResetMagickMemory(resample_filter,0,sizeof(*resample_filter));
222
223  resample_filter->exception=exception;
224  resample_filter->image=ReferenceImage((Image *) image);
225  resample_filter->view=AcquireVirtualCacheView(resample_filter->image,exception);
226
227  resample_filter->debug=IsEventLogging();
228  resample_filter->signature=MagickSignature;
229
230  resample_filter->image_area=(ssize_t) (image->columns*image->rows);
231  resample_filter->average_defined = MagickFalse;
232
233  /* initialise the resampling filter settings */
234  SetResampleFilter(resample_filter, image->filter, image->blur);
235  (void) SetResampleFilterInterpolateMethod(resample_filter,
236    image->interpolate);
237  (void) SetResampleFilterVirtualPixelMethod(resample_filter,
238    GetImageVirtualPixelMethod(image));
239
240  return(resample_filter);
241}
242
243/*
244%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
245%                                                                             %
246%                                                                             %
247%                                                                             %
248%   D e s t r o y R e s a m p l e I n f o                                     %
249%                                                                             %
250%                                                                             %
251%                                                                             %
252%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
253%
254%  DestroyResampleFilter() finalizes and cleans up the resampling
255%  resample_filter as returned by AcquireResampleFilter(), freeing any memory
256%  or other information as needed.
257%
258%  The format of the DestroyResampleFilter method is:
259%
260%      ResampleFilter *DestroyResampleFilter(ResampleFilter *resample_filter)
261%
262%  A description of each parameter follows:
263%
264%    o resample_filter: resampling information structure
265%
266*/
267MagickExport ResampleFilter *DestroyResampleFilter(
268  ResampleFilter *resample_filter)
269{
270  assert(resample_filter != (ResampleFilter *) NULL);
271  assert(resample_filter->signature == MagickSignature);
272  assert(resample_filter->image != (Image *) NULL);
273  if (resample_filter->debug != MagickFalse)
274    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
275      resample_filter->image->filename);
276  resample_filter->view=DestroyCacheView(resample_filter->view);
277  resample_filter->image=DestroyImage(resample_filter->image);
278#if ! FILTER_LUT
279  resample_filter->filter_def=DestroyResizeFilter(resample_filter->filter_def);
280#endif
281  resample_filter->signature=(~MagickSignature);
282  resample_filter=(ResampleFilter *) RelinquishMagickMemory(resample_filter);
283  return(resample_filter);
284}
285
286/*
287%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
288%                                                                             %
289%                                                                             %
290%                                                                             %
291%   R e s a m p l e P i x e l C o l o r                                       %
292%                                                                             %
293%                                                                             %
294%                                                                             %
295%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
296%
297%  ResamplePixelColor() samples the pixel values surrounding the location
298%  given using an elliptical weighted average, at the scale previously
299%  calculated, and in the most efficent manner possible for the
300%  VirtualPixelMethod setting.
301%
302%  The format of the ResamplePixelColor method is:
303%
304%     MagickBooleanType ResamplePixelColor(ResampleFilter *resample_filter,
305%       const double u0,const double v0,MagickPixelPacket *pixel)
306%
307%  A description of each parameter follows:
308%
309%    o resample_filter: the resample filter.
310%
311%    o u0,v0: A double representing the center of the area to resample,
312%        The distortion transformed transformed x,y coordinate.
313%
314%    o pixel: the resampled pixel is returned here.
315%
316*/
317MagickExport MagickBooleanType ResamplePixelColor(
318  ResampleFilter *resample_filter,const double u0,const double v0,
319  MagickPixelPacket *pixel)
320{
321  MagickBooleanType
322    status;
323
324  ssize_t u,v, v1, v2, uw, hit;
325  double u1;
326  double U,V,Q,DQ,DDQ;
327  double divisor_c,divisor_m;
328  register double weight;
329  register const PixelPacket *pixels;
330  register const IndexPacket *indexes;
331  assert(resample_filter != (ResampleFilter *) NULL);
332  assert(resample_filter->signature == MagickSignature);
333
334  status=MagickTrue;
335  /* GetMagickPixelPacket(resample_filter->image,pixel); */
336  if ( resample_filter->do_interpolate ) {
337    status=InterpolateMagickPixelPacket(resample_filter->image,
338      resample_filter->view,resample_filter->interpolate,u0,v0,pixel,
339      resample_filter->exception);
340    return(status);
341  }
342
343#if DEBUG_ELLIPSE
344  (void) FormatLocaleFile(stderr, "u0=%lf; v0=%lf;\n", u0, v0);
345#endif
346
347  /*
348    Does resample area Miss the image?
349    And is that area a simple solid color - then return that color
350  */
351  hit = 0;
352  switch ( resample_filter->virtual_pixel ) {
353    case BackgroundVirtualPixelMethod:
354    case ConstantVirtualPixelMethod:
355    case TransparentVirtualPixelMethod:
356    case BlackVirtualPixelMethod:
357    case GrayVirtualPixelMethod:
358    case WhiteVirtualPixelMethod:
359    case MaskVirtualPixelMethod:
360      if ( resample_filter->limit_reached
361           || u0 + resample_filter->Ulimit < 0.0
362           || u0 - resample_filter->Ulimit > (double) resample_filter->image->columns
363           || v0 + resample_filter->Vlimit < 0.0
364           || v0 - resample_filter->Vlimit > (double) resample_filter->image->rows
365           )
366        hit++;
367      break;
368
369    case UndefinedVirtualPixelMethod:
370    case EdgeVirtualPixelMethod:
371      if (    ( u0 + resample_filter->Ulimit < 0.0 && v0 + resample_filter->Vlimit < 0.0 )
372           || ( u0 + resample_filter->Ulimit < 0.0
373                && v0 - resample_filter->Vlimit > (double) resample_filter->image->rows )
374           || ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns
375                && v0 + resample_filter->Vlimit < 0.0 )
376           || ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns
377                && v0 - resample_filter->Vlimit > (double) resample_filter->image->rows )
378           )
379        hit++;
380      break;
381    case HorizontalTileVirtualPixelMethod:
382      if (    v0 + resample_filter->Vlimit < 0.0
383           || v0 - resample_filter->Vlimit > (double) resample_filter->image->rows
384           )
385        hit++;  /* outside the horizontally tiled images. */
386      break;
387    case VerticalTileVirtualPixelMethod:
388      if (    u0 + resample_filter->Ulimit < 0.0
389           || u0 - resample_filter->Ulimit > (double) resample_filter->image->columns
390           )
391        hit++;  /* outside the vertically tiled images. */
392      break;
393    case DitherVirtualPixelMethod:
394      if (    ( u0 + resample_filter->Ulimit < -32.0 && v0 + resample_filter->Vlimit < -32.0 )
395           || ( u0 + resample_filter->Ulimit < -32.0
396                && v0 - resample_filter->Vlimit > (double) resample_filter->image->rows+32.0 )
397           || ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns+32.0
398                && v0 + resample_filter->Vlimit < -32.0 )
399           || ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns+32.0
400                && v0 - resample_filter->Vlimit > (double) resample_filter->image->rows+32.0 )
401           )
402        hit++;
403      break;
404    case TileVirtualPixelMethod:
405    case MirrorVirtualPixelMethod:
406    case RandomVirtualPixelMethod:
407    case HorizontalTileEdgeVirtualPixelMethod:
408    case VerticalTileEdgeVirtualPixelMethod:
409    case CheckerTileVirtualPixelMethod:
410      /* resampling of area is always needed - no VP limits */
411      break;
412  }
413  if ( hit ) {
414    /* whole area is a solid color -- just return that color */
415    status=InterpolateMagickPixelPacket(resample_filter->image,
416      resample_filter->view,IntegerInterpolatePixel,u0,v0,pixel,
417      resample_filter->exception);
418    return(status);
419  }
420
421  /*
422    Scaling limits reached, return an 'averaged' result.
423  */
424  if ( resample_filter->limit_reached ) {
425    switch ( resample_filter->virtual_pixel ) {
426      /*  This is always handled by the above, so no need.
427        case BackgroundVirtualPixelMethod:
428        case ConstantVirtualPixelMethod:
429        case TransparentVirtualPixelMethod:
430        case GrayVirtualPixelMethod,
431        case WhiteVirtualPixelMethod
432        case MaskVirtualPixelMethod:
433      */
434      case UndefinedVirtualPixelMethod:
435      case EdgeVirtualPixelMethod:
436      case DitherVirtualPixelMethod:
437      case HorizontalTileEdgeVirtualPixelMethod:
438      case VerticalTileEdgeVirtualPixelMethod:
439        /* We need an average edge pixel, from the correct edge!
440           How should I calculate an average edge color?
441           Just returning an averaged neighbourhood,
442           works well in general, but falls down for TileEdge methods.
443           This needs to be done properly!!!!!!
444        */
445        status=InterpolateMagickPixelPacket(resample_filter->image,
446          resample_filter->view,AverageInterpolatePixel,u0,v0,pixel,
447          resample_filter->exception);
448        break;
449      case HorizontalTileVirtualPixelMethod:
450      case VerticalTileVirtualPixelMethod:
451        /* just return the background pixel - Is there more direct way? */
452        status=InterpolateMagickPixelPacket(resample_filter->image,
453          resample_filter->view,IntegerInterpolatePixel,-1.0,-1.0,pixel,
454          resample_filter->exception);
455        break;
456      case TileVirtualPixelMethod:
457      case MirrorVirtualPixelMethod:
458      case RandomVirtualPixelMethod:
459      case CheckerTileVirtualPixelMethod:
460      default:
461        /* generate a average color of the WHOLE image */
462        if ( resample_filter->average_defined == MagickFalse ) {
463          Image
464            *average_image;
465
466          CacheView
467            *average_view;
468
469          GetMagickPixelPacket(resample_filter->image,(MagickPixelPacket *)
470            &resample_filter->average_pixel);
471          resample_filter->average_defined=MagickTrue;
472
473          /* Try to get an averaged pixel color of whole image */
474          average_image=ResizeImage(resample_filter->image,1,1,BoxFilter,1.0,
475            resample_filter->exception);
476          if (average_image == (Image *) NULL)
477            {
478              *pixel=resample_filter->average_pixel; /* FAILED */
479              break;
480            }
481          average_view=AcquireVirtualCacheView(average_image,
482            &average_image->exception);
483          pixels=(PixelPacket *)GetCacheViewVirtualPixels(average_view,0,0,1,1,
484            resample_filter->exception);
485          if (pixels == (const PixelPacket *) NULL) {
486            average_view=DestroyCacheView(average_view);
487            average_image=DestroyImage(average_image);
488            *pixel=resample_filter->average_pixel; /* FAILED */
489            break;
490          }
491          indexes=(IndexPacket *) GetCacheViewAuthenticIndexQueue(average_view);
492          SetMagickPixelPacket(resample_filter->image,pixels,indexes,
493            &(resample_filter->average_pixel));
494          average_view=DestroyCacheView(average_view);
495          average_image=DestroyImage(average_image);
496
497          if ( resample_filter->virtual_pixel == CheckerTileVirtualPixelMethod )
498            {
499              /* CheckerTile is avergae of image average half background */
500              /* FUTURE: replace with a 50% blend of both pixels */
501
502              weight = QuantumScale*((MagickRealType)(QuantumRange-
503                          resample_filter->average_pixel.opacity));
504              resample_filter->average_pixel.red *= weight;
505              resample_filter->average_pixel.green *= weight;
506              resample_filter->average_pixel.blue *= weight;
507              divisor_c = weight;
508
509              weight = QuantumScale*((MagickRealType)(QuantumRange-
510                          resample_filter->image->background_color.opacity));
511              resample_filter->average_pixel.red +=
512                      weight*resample_filter->image->background_color.red;
513              resample_filter->average_pixel.green +=
514                      weight*resample_filter->image->background_color.green;
515              resample_filter->average_pixel.blue +=
516                      weight*resample_filter->image->background_color.blue;
517              resample_filter->average_pixel.opacity +=
518                      resample_filter->image->background_color.opacity;
519              divisor_c += weight;
520
521              resample_filter->average_pixel.red /= divisor_c;
522              resample_filter->average_pixel.green /= divisor_c;
523              resample_filter->average_pixel.blue /= divisor_c;
524              resample_filter->average_pixel.opacity /= 2;
525
526            }
527        }
528        *pixel=resample_filter->average_pixel;
529        break;
530    }
531    return(status);
532  }
533
534  /*
535    Initialize weighted average data collection
536  */
537  hit = 0;
538  divisor_c = 0.0;
539  divisor_m = 0.0;
540  pixel->red = pixel->green = pixel->blue = 0.0;
541  if (pixel->matte != MagickFalse) pixel->opacity = 0.0;
542  if (pixel->colorspace == CMYKColorspace) pixel->index = 0.0;
543
544  /*
545    Determine the parellelogram bounding box fitted to the ellipse
546    centered at u0,v0.  This area is bounding by the lines...
547  */
548  v1 = (ssize_t)ceil(v0 - resample_filter->Vlimit);  /* range of scan lines */
549  v2 = (ssize_t)floor(v0 + resample_filter->Vlimit);
550
551  /* scan line start and width accross the parallelogram */
552  u1 = u0 + (v1-v0)*resample_filter->slope - resample_filter->Uwidth;
553  uw = (ssize_t)(2.0*resample_filter->Uwidth)+1;
554
555#if DEBUG_ELLIPSE
556  (void) FormatLocaleFile(stderr, "v1=%ld; v2=%ld\n", (long)v1, (long)v2);
557  (void) FormatLocaleFile(stderr, "u1=%ld; uw=%ld\n", (long)u1, (long)uw);
558#else
559# define DEBUG_HIT_MISS 0 /* only valid if DEBUG_ELLIPSE is enabled */
560#endif
561
562  /*
563    Do weighted resampling of all pixels,  within the scaled ellipse,
564    bound by a Parellelogram fitted to the ellipse.
565  */
566  DDQ = 2*resample_filter->A;
567  for( v=v1; v<=v2;  v++ ) {
568#if DEBUG_HIT_MISS
569    long uu = ceil(u1);   /* actual pixel location (for debug only) */
570    (void) FormatLocaleFile(stderr, "# scan line from pixel %ld, %ld\n", (long)uu, (long)v);
571#endif
572    u = (ssize_t)ceil(u1);        /* first pixel in scanline */
573    u1 += resample_filter->slope; /* start of next scan line */
574
575
576    /* location of this first pixel, relative to u0,v0 */
577    U = (double)u-u0;
578    V = (double)v-v0;
579
580    /* Q = ellipse quotent ( if Q<F then pixel is inside ellipse) */
581    Q = (resample_filter->A*U + resample_filter->B*V)*U + resample_filter->C*V*V;
582    DQ = resample_filter->A*(2.0*U+1) + resample_filter->B*V;
583
584    /* get the scanline of pixels for this v */
585    pixels=GetCacheViewVirtualPixels(resample_filter->view,u,v,(size_t) uw,
586      1,resample_filter->exception);
587    if (pixels == (const PixelPacket *) NULL)
588      return(MagickFalse);
589    indexes=GetCacheViewVirtualIndexQueue(resample_filter->view);
590
591    /* count up the weighted pixel colors */
592    for( u=0; u<uw; u++ ) {
593#if FILTER_LUT
594      /* Note that the ellipse has been pre-scaled so F = WLUT_WIDTH */
595      if ( Q < (double)WLUT_WIDTH ) {
596        weight = resample_filter->filter_lut[(int)Q];
597#else
598      /* Note that the ellipse has been pre-scaled so F = support^2 */
599      if ( Q < (double)resample_filter->F ) {
600        weight = GetResizeFilterWeight(resample_filter->filter_def,
601             sqrt(Q));    /* a SquareRoot!  Arrggghhhhh... */
602#endif
603
604        pixel->opacity  += weight*pixels->opacity;
605        divisor_m += weight;
606
607        if (pixel->matte != MagickFalse)
608          weight *= QuantumScale*((MagickRealType)(QuantumRange-pixels->opacity));
609        pixel->red   += weight*pixels->red;
610        pixel->green += weight*pixels->green;
611        pixel->blue  += weight*pixels->blue;
612        if (pixel->colorspace == CMYKColorspace)
613          pixel->index += weight*(*indexes);
614        divisor_c += weight;
615
616        hit++;
617#if DEBUG_HIT_MISS
618        /* mark the pixel according to hit/miss of the ellipse */
619        (void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 3\n",
620                     (long)uu-.1,(double)v-.1,(long)uu+.1,(long)v+.1);
621        (void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 3\n",
622                     (long)uu+.1,(double)v-.1,(long)uu-.1,(long)v+.1);
623      } else {
624        (void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 1\n",
625                     (long)uu-.1,(double)v-.1,(long)uu+.1,(long)v+.1);
626        (void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 1\n",
627                     (long)uu+.1,(double)v-.1,(long)uu-.1,(long)v+.1);
628      }
629      uu++;
630#else
631      }
632#endif
633      pixels++;
634      indexes++;
635      Q += DQ;
636      DQ += DDQ;
637    }
638  }
639#if DEBUG_ELLIPSE
640  (void) FormatLocaleFile(stderr, "Hit=%ld;  Total=%ld;\n", (long)hit, (long)uw*(v2-v1) );
641#endif
642
643  /*
644    Result sanity check -- this should NOT happen
645  */
646  if ( hit == 0 ) {
647    /* not enough pixels in resampling, resort to direct interpolation */
648#if DEBUG_NO_PIXEL_HIT
649    pixel->opacity = pixel->red = pixel->green = pixel->blue = 0;
650    pixel->red = QuantumRange; /* show pixels for which EWA fails */
651#else
652    status=InterpolateMagickPixelPacket(resample_filter->image,
653      resample_filter->view,resample_filter->interpolate,u0,v0,pixel,
654      resample_filter->exception);
655#endif
656    return status;
657  }
658
659  /*
660    Finialize results of resampling
661  */
662  divisor_m = 1.0/divisor_m;
663  pixel->opacity = (MagickRealType) ClampToQuantum(divisor_m*pixel->opacity);
664  divisor_c = 1.0/divisor_c;
665  pixel->red   = (MagickRealType) ClampToQuantum(divisor_c*pixel->red);
666  pixel->green = (MagickRealType) ClampToQuantum(divisor_c*pixel->green);
667  pixel->blue  = (MagickRealType) ClampToQuantum(divisor_c*pixel->blue);
668  if (pixel->colorspace == CMYKColorspace)
669    pixel->index = (MagickRealType) ClampToQuantum(divisor_c*pixel->index);
670  return(MagickTrue);
671}
672
673#if EWA && EWA_CLAMP
674/*
675%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
676%                                                                             %
677%                                                                             %
678%                                                                             %
679-   C l a m p U p A x e s                                                     %
680%                                                                             %
681%                                                                             %
682%                                                                             %
683%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
684%
685% ClampUpAxes() function converts the input vectors into a major and
686% minor axis unit vectors, and their magnitude.  This allows us to
687% ensure that the ellipse generated is never smaller than the unit
688% circle and thus never too small for use in EWA resampling.
689%
690% This purely mathematical 'magic' was provided by Professor Nicolas
691% Robidoux and his Masters student Chantal Racette.
692%
693% Reference: "We Recommend Singular Value Decomposition", David Austin
694%   http://www.ams.org/samplings/feature-column/fcarc-svd
695%
696% By generating major and minor axis vectors, we can actually use the
697% ellipse in its "canonical form", by remapping the dx,dy of the
698% sampled point into distances along the major and minor axis unit
699% vectors.
700%
701% Reference: http://en.wikipedia.org/wiki/Ellipse#Canonical_form
702*/
703static inline void ClampUpAxes(const double dux,
704                               const double dvx,
705                               const double duy,
706                               const double dvy,
707                               double *major_mag,
708                               double *minor_mag,
709                               double *major_unit_x,
710                               double *major_unit_y,
711                               double *minor_unit_x,
712                               double *minor_unit_y)
713{
714  /*
715   * ClampUpAxes takes an input 2x2 matrix
716   *
717   * [ a b ] = [ dux duy ]
718   * [ c d ] = [ dvx dvy ]
719   *
720   * and computes from it the major and minor axis vectors [major_x,
721   * major_y] and [minor_x,minor_y] of the smallest ellipse containing
722   * both the unit disk and the ellipse which is the image of the unit
723   * disk by the linear transformation
724   *
725   * [ dux duy ] [S] = [s]
726   * [ dvx dvy ] [T] = [t]
727   *
728   * (The vector [S,T] is the difference between a position in output
729   * space and [X,Y]; the vector [s,t] is the difference between a
730   * position in input space and [x,y].)
731   */
732  /*
733   * Output:
734   *
735   * major_mag is the half-length of the major axis of the "new"
736   * ellipse.
737   *
738   * minor_mag is the half-length of the minor axis of the "new"
739   * ellipse.
740   *
741   * major_unit_x is the x-coordinate of the major axis direction vector
742   * of both the "old" and "new" ellipses.
743   *
744   * major_unit_y is the y-coordinate of the major axis direction vector.
745   *
746   * minor_unit_x is the x-coordinate of the minor axis direction vector.
747   *
748   * minor_unit_y is the y-coordinate of the minor axis direction vector.
749   *
750   * Unit vectors are useful for computing projections, in particular,
751   * to compute the distance between a point in output space and the
752   * center of a unit disk in output space, using the position of the
753   * corresponding point [s,t] in input space. Following the clamping,
754   * the square of this distance is
755   *
756   * ( ( s * major_unit_x + t * major_unit_y ) / major_mag )^2
757   * +
758   * ( ( s * minor_unit_x + t * minor_unit_y ) / minor_mag )^2
759   *
760   * If such distances will be computed for many [s,t]'s, it makes
761   * sense to actually compute the reciprocal of major_mag and
762   * minor_mag and multiply them by the above unit lengths.
763   *
764   * Now, if you want to modify the input pair of tangent vectors so
765   * that it defines the modified ellipse, all you have to do is set
766   *
767   * newdux = major_mag * major_unit_x
768   * newdvx = major_mag * major_unit_y
769   * newduy = minor_mag * minor_unit_x = minor_mag * -major_unit_y
770   * newdvy = minor_mag * minor_unit_y = minor_mag *  major_unit_x
771   *
772   * and use these tangent vectors as if they were the original ones.
773   * Usually, this is a drastic change in the tangent vectors even if
774   * the singular values are not clamped; for example, the minor axis
775   * vector always points in a direction which is 90 degrees
776   * counterclockwise from the direction of the major axis vector.
777   */
778  /*
779   * Discussion:
780   *
781   * GOAL: Fix things so that the pullback, in input space, of a disk
782   * of radius r in output space is an ellipse which contains, at
783   * least, a disc of radius r. (Make this hold for any r>0.)
784   *
785   * ESSENCE OF THE METHOD: Compute the product of the first two
786   * factors of an SVD of the linear transformation defining the
787   * ellipse and make sure that both its columns have norm at least 1.
788   * Because rotations and reflexions map disks to themselves, it is
789   * not necessary to compute the third (rightmost) factor of the SVD.
790   *
791   * DETAILS: Find the singular values and (unit) left singular
792   * vectors of Jinv, clampling up the singular values to 1, and
793   * multiply the unit left singular vectors by the new singular
794   * values in order to get the minor and major ellipse axis vectors.
795   *
796   * Image resampling context:
797   *
798   * The Jacobian matrix of the transformation at the output point
799   * under consideration is defined as follows:
800   *
801   * Consider the transformation (x,y) -> (X,Y) from input locations
802   * to output locations. (Anthony Thyssen, elsewhere in resample.c,
803   * uses the notation (u,v) -> (x,y).)
804   *
805   * The Jacobian matrix of the transformation at (x,y) is equal to
806   *
807   *   J = [ A, B ] = [ dX/dx, dX/dy ]
808   *       [ C, D ]   [ dY/dx, dY/dy ]
809   *
810   * that is, the vector [A,C] is the tangent vector corresponding to
811   * input changes in the horizontal direction, and the vector [B,D]
812   * is the tangent vector corresponding to input changes in the
813   * vertical direction.
814   *
815   * In the context of resampling, it is natural to use the inverse
816   * Jacobian matrix Jinv because resampling is generally performed by
817   * pulling pixel locations in the output image back to locations in
818   * the input image. Jinv is
819   *
820   *   Jinv = [ a, b ] = [ dx/dX, dx/dY ]
821   *          [ c, d ]   [ dy/dX, dy/dY ]
822   *
823   * Note: Jinv can be computed from J with the following matrix
824   * formula:
825   *
826   *   Jinv = 1/(A*D-B*C) [  D, -B ]
827   *                      [ -C,  A ]
828   *
829   * What we do is modify Jinv so that it generates an ellipse which
830   * is as close as possible to the original but which contains the
831   * unit disk. This can be accomplished as follows:
832   *
833   * Let
834   *
835   *   Jinv = U Sigma V^T
836   *
837   * be an SVD decomposition of Jinv. (The SVD is not unique, but the
838   * final ellipse does not depend on the particular SVD.)
839   *
840   * We could clamp up the entries of the diagonal matrix Sigma so
841   * that they are at least 1, and then set
842   *
843   *   Jinv = U newSigma V^T.
844   *
845   * However, we do not need to compute V for the following reason:
846   * V^T is an orthogonal matrix (that is, it represents a combination
847   * of rotations and reflexions) so that it maps the unit circle to
848   * itself. For this reason, the exact value of V does not affect the
849   * final ellipse, and we can choose V to be the identity
850   * matrix. This gives
851   *
852   *   Jinv = U newSigma.
853   *
854   * In the end, we return the two diagonal entries of newSigma
855   * together with the two columns of U.
856   */
857  /*
858   * ClampUpAxes was written by Nicolas Robidoux and Chantal Racette
859   * of Laurentian University with insightful suggestions from Anthony
860   * Thyssen and funding from the National Science and Engineering
861   * Research Council of Canada. It is distinguished from its
862   * predecessors by its efficient handling of degenerate cases.
863   *
864   * The idea of clamping up the EWA ellipse's major and minor axes so
865   * that the result contains the reconstruction kernel filter support
866   * is taken from Andreas Gustaffson's Masters thesis "Interactive
867   * Image Warping", Helsinki University of Technology, Faculty of
868   * Information Technology, 59 pages, 1993 (see Section 3.6).
869   *
870   * The use of the SVD to clamp up the singular values of the
871   * Jacobian matrix of the pullback transformation for EWA resampling
872   * is taken from the astrophysicist Craig DeForest.  It is
873   * implemented in his PDL::Transform code (PDL = Perl Data
874   * Language).
875   */
876  const double a = dux;
877  const double b = duy;
878  const double c = dvx;
879  const double d = dvy;
880  /*
881   * n is the matrix Jinv * transpose(Jinv). Eigenvalues of n are the
882   * squares of the singular values of Jinv.
883   */
884  const double aa = a*a;
885  const double bb = b*b;
886  const double cc = c*c;
887  const double dd = d*d;
888  /*
889   * Eigenvectors of n are left singular vectors of Jinv.
890   */
891  const double n11 = aa+bb;
892  const double n12 = a*c+b*d;
893  const double n21 = n12;
894  const double n22 = cc+dd;
895  const double det = a*d-b*c;
896  const double twice_det = det+det;
897  const double frobenius_squared = n11+n22;
898  const double discriminant =
899    (frobenius_squared+twice_det)*(frobenius_squared-twice_det);
900  const double sqrt_discriminant = sqrt(discriminant);
901  /*
902   * s1 is the largest singular value of the inverse Jacobian
903   * matrix. In other words, its reciprocal is the smallest singular
904   * value of the Jacobian matrix itself.
905   * If s1 = 0, both singular values are 0, and any orthogonal pair of
906   * left and right factors produces a singular decomposition of Jinv.
907   */
908  /*
909   * Initially, we only compute the squares of the singular values.
910   */
911  const double s1s1 = 0.5*(frobenius_squared+sqrt_discriminant);
912  /*
913   * s2 the smallest singular value of the inverse Jacobian
914   * matrix. Its reciprocal is the largest singular value of the
915   * Jacobian matrix itself.
916   */
917  const double s2s2 = 0.5*(frobenius_squared-sqrt_discriminant);
918  const double s1s1minusn11 = s1s1-n11;
919  const double s1s1minusn22 = s1s1-n22;
920  /*
921   * u1, the first column of the U factor of a singular decomposition
922   * of Jinv, is a (non-normalized) left singular vector corresponding
923   * to s1. It has entries u11 and u21. We compute u1 from the fact
924   * that it is an eigenvector of n corresponding to the eigenvalue
925   * s1^2.
926   */
927  const double s1s1minusn11_squared = s1s1minusn11*s1s1minusn11;
928  const double s1s1minusn22_squared = s1s1minusn22*s1s1minusn22;
929  /*
930   * The following selects the largest row of n-s1^2 I as the one
931   * which is used to find the eigenvector. If both s1^2-n11 and
932   * s1^2-n22 are zero, n-s1^2 I is the zero matrix.  In that case,
933   * any vector is an eigenvector; in addition, norm below is equal to
934   * zero, and, in exact arithmetic, this is the only case in which
935   * norm = 0. So, setting u1 to the simple but arbitrary vector [1,0]
936   * if norm = 0 safely takes care of all cases.
937   */
938  const double temp_u11 =
939    ( (s1s1minusn11_squared>=s1s1minusn22_squared) ? n12 : s1s1minusn22 );
940  const double temp_u21 =
941    ( (s1s1minusn11_squared>=s1s1minusn22_squared) ? s1s1minusn11 : n21 );
942  const double norm = sqrt(temp_u11*temp_u11+temp_u21*temp_u21);
943  /*
944   * Finalize the entries of first left singular vector (associated
945   * with the largest singular value).
946   */
947  const double u11 = ( (norm>0.0) ? temp_u11/norm : 1.0 );
948  const double u21 = ( (norm>0.0) ? temp_u21/norm : 0.0 );
949  /*
950   * Clamp the singular values up to 1.
951   */
952  *major_mag = ( (s1s1<=1.0) ? 1.0 : sqrt(s1s1) );
953  *minor_mag = ( (s2s2<=1.0) ? 1.0 : sqrt(s2s2) );
954  /*
955   * Return the unit major and minor axis direction vectors.
956   */
957  *major_unit_x = u11;
958  *major_unit_y = u21;
959  *minor_unit_x = -u21;
960  *minor_unit_y = u11;
961}
962
963#endif
964/*
965%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
966%                                                                             %
967%                                                                             %
968%                                                                             %
969%   S c a l e R e s a m p l e F i l t e r                                     %
970%                                                                             %
971%                                                                             %
972%                                                                             %
973%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
974%
975%  ScaleResampleFilter() does all the calculations needed to resample an image
976%  at a specific scale, defined by two scaling vectors.  This not using
977%  a orthogonal scaling, but two distorted scaling vectors, to allow the
978%  generation of a angled ellipse.
979%
980%  As only two deritive scaling vectors are used the center of the ellipse
981%  must be the center of the lookup.  That is any curvature that the
982%  distortion may produce is discounted.
983%
984%  The input vectors are produced by either finding the derivitives of the
985%  distortion function, or the partial derivitives from a distortion mapping.
986%  They do not need to be the orthogonal dx,dy scaling vectors, but can be
987%  calculated from other derivatives.  For example you could use  dr,da/r
988%  polar coordinate vector scaling vectors
989%
990%  If   u,v =  DistortEquation(x,y)   OR   u = Fu(x,y); v = Fv(x,y)
991%  Then the scaling vectors are determined from the deritives...
992%      du/dx, dv/dx     and    du/dy, dv/dy
993%  If the resulting scaling vectors is othogonally aligned then...
994%      dv/dx = 0   and   du/dy  =  0
995%  Producing an othogonally alligned ellipse in source space for the area to
996%  be resampled.
997%
998%  Note that scaling vectors are different to argument order.  Argument order
999%  is the general order the deritives are extracted from the distortion
1000%  equations, and not the scaling vectors. As such the middle two vaules
1001%  may be swapped from what you expect.  Caution is advised.
1002%
1003%  WARNING: It is assumed that any SetResampleFilter() method call will
1004%  always be performed before the ScaleResampleFilter() method, so that the
1005%  size of the ellipse will match the support for the resampling filter being
1006%  used.
1007%
1008%  The format of the ScaleResampleFilter method is:
1009%
1010%     void ScaleResampleFilter(const ResampleFilter *resample_filter,
1011%       const double dux,const double duy,const double dvx,const double dvy)
1012%
1013%  A description of each parameter follows:
1014%
1015%    o resample_filter: the resampling resample_filterrmation defining the
1016%      image being resampled
1017%
1018%    o dux,duy,dvx,dvy:
1019%         The deritives or scaling vectors defining the EWA ellipse.
1020%         NOTE: watch the order, which is based on the order deritives
1021%         are usally determined from distortion equations (see above).
1022%         The middle two values may need to be swapped if you are thinking
1023%         in terms of scaling vectors.
1024%
1025*/
1026MagickExport void ScaleResampleFilter(ResampleFilter *resample_filter,
1027  const double dux,const double duy,const double dvx,const double dvy)
1028{
1029  double A,B,C,F;
1030
1031  assert(resample_filter != (ResampleFilter *) NULL);
1032  assert(resample_filter->signature == MagickSignature);
1033
1034  resample_filter->limit_reached = MagickFalse;
1035
1036  /* A 'point' filter forces use of interpolation instead of area sampling */
1037  if ( resample_filter->filter == PointFilter )
1038    return; /* EWA turned off - nothing to do */
1039
1040#if DEBUG_ELLIPSE
1041  (void) FormatLocaleFile(stderr, "# -----\n" );
1042  (void) FormatLocaleFile(stderr, "dux=%lf; dvx=%lf;   duy=%lf; dvy=%lf;\n",
1043       dux, dvx, duy, dvy);
1044#endif
1045
1046  /* Find Ellipse Coefficents such that
1047        A*u^2 + B*u*v + C*v^2 = F
1048     With u,v relative to point around which we are resampling.
1049     And the given scaling dx,dy vectors in u,v space
1050         du/dx,dv/dx   and  du/dy,dv/dy
1051  */
1052#if EWA
1053  /* Direct conversion of derivatives into elliptical coefficients
1054     However when magnifying images, the scaling vectors will be small
1055     resulting in a ellipse that is too small to sample properly.
1056     As such we need to clamp the major/minor axis to a minumum of 1.0
1057     to prevent it getting too small.
1058  */
1059#if EWA_CLAMP
1060  { double major_mag,
1061           minor_mag,
1062           major_x,
1063           major_y,
1064           minor_x,
1065           minor_y;
1066
1067  ClampUpAxes(dux,dvx,duy,dvy, &major_mag, &minor_mag,
1068                &major_x, &major_y, &minor_x, &minor_y);
1069  major_x *= major_mag;  major_y *= major_mag;
1070  minor_x *= minor_mag;  minor_y *= minor_mag;
1071#if DEBUG_ELLIPSE
1072  (void) FormatLocaleFile(stderr, "major_x=%lf; major_y=%lf;  minor_x=%lf; minor_y=%lf;\n",
1073        major_x, major_y, minor_x, minor_y);
1074#endif
1075  A = major_y*major_y+minor_y*minor_y;
1076  B = -2.0*(major_x*major_y+minor_x*minor_y);
1077  C = major_x*major_x+minor_x*minor_x;
1078  F = major_mag*minor_mag;
1079  F *= F; /* square it */
1080  }
1081#else /* raw unclamped EWA */
1082  A = dvx*dvx+dvy*dvy;
1083  B = -2.0*(dux*dvx+duy*dvy);
1084  C = dux*dux+duy*duy;
1085  F = dux*dvy-duy*dvx;
1086  F *= F; /* square it */
1087#endif /* EWA_CLAMP */
1088
1089#else /* HQ_EWA */
1090  /*
1091    This Paul Heckbert's "Higher Quality EWA" formula, from page 60 in his
1092    thesis, which adds a unit circle to the elliptical area so as to do both
1093    Reconstruction and Prefiltering of the pixels in the resampling.  It also
1094    means it is always likely to have at least 4 pixels within the area of the
1095    ellipse, for weighted averaging.  No scaling will result with F == 4.0 and
1096    a circle of radius 2.0, and F smaller than this means magnification is
1097    being used.
1098
1099    NOTE: This method produces a very blury result at near unity scale while
1100    producing perfect results for strong minitification and magnifications.
1101
1102    However filter support is fixed to 2.0 (no good for Windowed Sinc filters)
1103  */
1104  A = dvx*dvx+dvy*dvy+1;
1105  B = -2.0*(dux*dvx+duy*dvy);
1106  C = dux*dux+duy*duy+1;
1107  F = A*C - B*B/4;
1108#endif
1109
1110#if DEBUG_ELLIPSE
1111  (void) FormatLocaleFile(stderr, "A=%lf; B=%lf; C=%lf; F=%lf\n", A,B,C,F);
1112
1113  /* Figure out the various information directly about the ellipse.
1114     This information currently not needed at this time, but may be
1115     needed later for better limit determination.
1116
1117     It is also good to have as a record for future debugging
1118  */
1119  { double alpha, beta, gamma, Major, Minor;
1120    double Eccentricity, Ellipse_Area, Ellipse_Angle;
1121
1122    alpha = A+C;
1123    beta  = A-C;
1124    gamma = sqrt(beta*beta + B*B );
1125
1126    if ( alpha - gamma <= MagickEpsilon )
1127      Major = MagickHuge;
1128    else
1129      Major = sqrt(2*F/(alpha - gamma));
1130    Minor = sqrt(2*F/(alpha + gamma));
1131
1132    (void) FormatLocaleFile(stderr, "# Major=%lf; Minor=%lf\n", Major, Minor );
1133
1134    /* other information about ellipse include... */
1135    Eccentricity = Major/Minor;
1136    Ellipse_Area = MagickPI*Major*Minor;
1137    Ellipse_Angle = atan2(B, A-C);
1138
1139    (void) FormatLocaleFile(stderr, "# Angle=%lf   Area=%lf\n",
1140         RadiansToDegrees(Ellipse_Angle), Ellipse_Area);
1141  }
1142#endif
1143
1144  /* If one or both of the scaling vectors is impossibly large
1145     (producing a very large raw F value), we may as well not bother
1146     doing any form of resampling since resampled area is very large.
1147     In this case some alternative means of pixel sampling, such as
1148     the average of the whole image is needed to get a reasonable
1149     result. Calculate only as needed.
1150  */
1151  if ( (4*A*C - B*B) > MagickHuge ) {
1152    resample_filter->limit_reached = MagickTrue;
1153    return;
1154  }
1155
1156  /* Scale ellipse to match the filters support
1157     (that is, multiply F by the square of the support).
1158  */
1159  F *= resample_filter->support;
1160  F *= resample_filter->support;
1161
1162  /* Orthogonal bounds of the ellipse */
1163  resample_filter->Ulimit = sqrt(C*F/(A*C-0.25*B*B));
1164  resample_filter->Vlimit = sqrt(A*F/(A*C-0.25*B*B));
1165
1166  /* Horizontally aligned parallelogram fitted to Ellipse */
1167  resample_filter->Uwidth = sqrt(F/A); /* Half of the parallelogram width */
1168  resample_filter->slope = -B/(2.0*A); /* Reciprocal slope of the parallelogram */
1169
1170#if DEBUG_ELLIPSE
1171  (void) FormatLocaleFile(stderr, "Ulimit=%lf; Vlimit=%lf; UWidth=%lf; Slope=%lf;\n",
1172           resample_filter->Ulimit, resample_filter->Vlimit,
1173           resample_filter->Uwidth, resample_filter->slope );
1174#endif
1175
1176  /* Check the absolute area of the parallelogram involved.
1177   * This limit needs more work, as it is too slow for larger images
1178   * with tiled views of the horizon.
1179  */
1180  if ( (resample_filter->Uwidth * resample_filter->Vlimit)
1181         > (4.0*resample_filter->image_area)) {
1182    resample_filter->limit_reached = MagickTrue;
1183    return;
1184  }
1185
1186  /* Scale ellipse formula to directly index the Filter Lookup Table */
1187  { register double scale;
1188#if FILTER_LUT
1189    /* scale so that F = WLUT_WIDTH; -- hardcoded */
1190    scale = (double)WLUT_WIDTH/F;
1191#else
1192    /* scale so that F = resample_filter->F (support^2) */
1193    scale = resample_filter->F/F;
1194#endif
1195    resample_filter->A = A*scale;
1196    resample_filter->B = B*scale;
1197    resample_filter->C = C*scale;
1198  }
1199}
1200
1201/*
1202%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1203%                                                                             %
1204%                                                                             %
1205%                                                                             %
1206%   S e t R e s a m p l e F i l t e r                                         %
1207%                                                                             %
1208%                                                                             %
1209%                                                                             %
1210%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1211%
1212%  SetResampleFilter() set the resampling filter lookup table based on a
1213%  specific filter.  Note that the filter is used as a radial filter not as a
1214%  two pass othogonally aligned resampling filter.
1215%
1216%  The default Filter, is Gaussian, which is the standard filter used by the
1217%  original paper on the Elliptical Weighted Everage Algorithm. However other
1218%  filters can also be used.
1219%
1220%  The format of the SetResampleFilter method is:
1221%
1222%    void SetResampleFilter(ResampleFilter *resample_filter,
1223%      const FilterTypes filter,const double blur)
1224%
1225%  A description of each parameter follows:
1226%
1227%    o resample_filter: resampling resample_filterrmation structure
1228%
1229%    o filter: the resize filter for elliptical weighting LUT
1230%
1231%    o blur: filter blur factor (radial scaling) for elliptical weighting LUT
1232%
1233*/
1234MagickExport void SetResampleFilter(ResampleFilter *resample_filter,
1235  const FilterTypes filter,const double blur)
1236{
1237  ResizeFilter
1238     *resize_filter;
1239
1240  assert(resample_filter != (ResampleFilter *) NULL);
1241  assert(resample_filter->signature == MagickSignature);
1242
1243  resample_filter->do_interpolate = MagickFalse;
1244  resample_filter->filter = filter;
1245
1246  if ( filter == PointFilter )
1247    {
1248      resample_filter->do_interpolate = MagickTrue;
1249      return;  /* EWA turned off - nothing more to do */
1250    }
1251
1252  /* Set a default cylindrical filter of a 'low blur' Jinc windowed Jinc */
1253  if ( filter == UndefinedFilter )
1254    resample_filter->filter = RobidouxFilter;
1255
1256  resize_filter = AcquireResizeFilter(resample_filter->image,
1257       resample_filter->filter,blur,MagickTrue,resample_filter->exception);
1258  if (resize_filter == (ResizeFilter *) NULL)
1259    {
1260      (void) ThrowMagickException(resample_filter->exception,GetMagickModule(),
1261           ModuleError, "UnableToSetFilteringValue",
1262           "Fall back to default EWA gaussian filter");
1263      resample_filter->filter = PointFilter;
1264    }
1265
1266  /* Get the practical working support for the filter,
1267   * after any API call blur factors have been accoded for.
1268   */
1269#if EWA
1270  resample_filter->support = GetResizeFilterSupport(resize_filter);
1271#else
1272  resample_filter->support = 2.0;  /* fixed support size for HQ-EWA */
1273#endif
1274
1275#if FILTER_LUT
1276  /* Fill the LUT with the weights from the selected filter function */
1277  { register int
1278       Q;
1279    double
1280       r_scale;
1281    /* Scale radius so the filter LUT covers the full support range */
1282    r_scale = resample_filter->support*sqrt(1.0/(double)WLUT_WIDTH);
1283    for(Q=0; Q<WLUT_WIDTH; Q++)
1284      resample_filter->filter_lut[Q] = (double)
1285           GetResizeFilterWeight(resize_filter,sqrt((double)Q)*r_scale);
1286
1287    /* finished with the resize filter */
1288    resize_filter = DestroyResizeFilter(resize_filter);
1289  }
1290#else
1291  /* save the filter and the scaled ellipse bounds needed for filter */
1292  resample_filter->filter_def = resize_filter;
1293  resample_filter->F = resample_filter->support*resample_filter->support;
1294#endif
1295
1296  /*
1297    Adjust the scaling of the default unit circle
1298    This assumes that any real scaling changes will always
1299    take place AFTER the filter method has been initialized.
1300  */
1301  ScaleResampleFilter(resample_filter, 1.0, 0.0, 0.0, 1.0);
1302
1303#if 0
1304  /* This is old code kept as a reference only.  It is very wrong,
1305     and I don't understand exactly what it was attempting to do.
1306  */
1307  /*
1308    Create Normal Gaussian 2D Filter Weighted Lookup Table.
1309    A normal EWA guassual lookup would use   exp(Q*ALPHA)
1310    where  Q = distance squared from 0.0 (center) to 1.0 (edge)
1311    and    ALPHA = -4.0*ln(2.0)  ==>  -2.77258872223978123767
1312    The table is of length 1024, and equates to support radius of 2.0
1313    thus needs to be scaled by  ALPHA*4/1024 and any blur factor squared
1314
1315    The above came from some reference code provided by Fred Weinhaus
1316    and seems to have been a guess that was appropriate for its use
1317    in a 3d perspective landscape mapping program.
1318  */
1319  r_scale = -2.77258872223978123767/(WLUT_WIDTH*blur*blur);
1320  for(Q=0; Q<WLUT_WIDTH; Q++)
1321    resample_filter->filter_lut[Q] = exp((double)Q*r_scale);
1322  resample_filter->support = WLUT_WIDTH;
1323  break;
1324#endif
1325
1326#if FILTER_LUT
1327#if defined(MAGICKCORE_OPENMP_SUPPORT)
1328  #pragma omp single
1329#endif
1330  { register int
1331       Q;
1332    double
1333       r_scale;
1334
1335    /* Scale radius so the filter LUT covers the full support range */
1336    r_scale = resample_filter->support*sqrt(1.0/(double)WLUT_WIDTH);
1337    if (IsMagickTrue(GetImageArtifact(resample_filter->image,"resample:verbose")) )
1338      {
1339        /* Debug output of the filter weighting LUT
1340          Gnuplot the LUT with hoizontal adjusted to 'r' using...
1341            plot [0:2][-.2:1] "lut.dat" using (sqrt($0/1024)*2):1 with lines
1342          The filter values is normalized for comparision
1343        */
1344        printf("#\n");
1345        printf("# Resampling Filter LUT (%d values)\n", WLUT_WIDTH);
1346        printf("#\n");
1347        printf("# Note: values in table are using a squared radius lookup.\n");
1348        printf("# And the whole table represents the filters support.\n");
1349        printf("\n"); /* generates a 'break' in gnuplot if multiple outputs */
1350        for(Q=0; Q<WLUT_WIDTH; Q++)
1351          printf("%8.*g %.*g\n",
1352               GetMagickPrecision(),sqrt((double)Q)*r_scale,
1353               GetMagickPrecision(),resample_filter->filter_lut[Q] );
1354      }
1355    /* output the above once only for each image, and each setting */
1356    (void) DeleteImageArtifact(resample_filter->image,"resample:verbose");
1357  }
1358#endif /* FILTER_LUT */
1359  return;
1360}
1361
1362/*
1363%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1364%                                                                             %
1365%                                                                             %
1366%                                                                             %
1367%   S e t R e s a m p l e F i l t e r I n t e r p o l a t e M e t h o d       %
1368%                                                                             %
1369%                                                                             %
1370%                                                                             %
1371%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1372%
1373%  SetResampleFilterInterpolateMethod() sets the resample filter interpolation
1374%  method.
1375%
1376%  The format of the SetResampleFilterInterpolateMethod method is:
1377%
1378%      MagickBooleanType SetResampleFilterInterpolateMethod(
1379%        ResampleFilter *resample_filter,const InterpolateMethod method)
1380%
1381%  A description of each parameter follows:
1382%
1383%    o resample_filter: the resample filter.
1384%
1385%    o method: the interpolation method.
1386%
1387*/
1388MagickExport MagickBooleanType SetResampleFilterInterpolateMethod(
1389  ResampleFilter *resample_filter,const InterpolatePixelMethod method)
1390{
1391  assert(resample_filter != (ResampleFilter *) NULL);
1392  assert(resample_filter->signature == MagickSignature);
1393  assert(resample_filter->image != (Image *) NULL);
1394  if (resample_filter->debug != MagickFalse)
1395    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
1396      resample_filter->image->filename);
1397  resample_filter->interpolate=method;
1398  return(MagickTrue);
1399}
1400
1401/*
1402%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1403%                                                                             %
1404%                                                                             %
1405%                                                                             %
1406%   S e t R e s a m p l e F i l t e r V i r t u a l P i x e l M e t h o d     %
1407%                                                                             %
1408%                                                                             %
1409%                                                                             %
1410%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1411%
1412%  SetResampleFilterVirtualPixelMethod() changes the virtual pixel method
1413%  associated with the specified resample filter.
1414%
1415%  The format of the SetResampleFilterVirtualPixelMethod method is:
1416%
1417%      MagickBooleanType SetResampleFilterVirtualPixelMethod(
1418%        ResampleFilter *resample_filter,const VirtualPixelMethod method)
1419%
1420%  A description of each parameter follows:
1421%
1422%    o resample_filter: the resample filter.
1423%
1424%    o method: the virtual pixel method.
1425%
1426*/
1427MagickExport MagickBooleanType SetResampleFilterVirtualPixelMethod(
1428  ResampleFilter *resample_filter,const VirtualPixelMethod method)
1429{
1430  assert(resample_filter != (ResampleFilter *) NULL);
1431  assert(resample_filter->signature == MagickSignature);
1432  assert(resample_filter->image != (Image *) NULL);
1433  if (resample_filter->debug != MagickFalse)
1434    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
1435      resample_filter->image->filename);
1436  resample_filter->virtual_pixel=method;
1437  if (method != UndefinedVirtualPixelMethod)
1438    (void) SetCacheViewVirtualPixelMethod(resample_filter->view,method);
1439  return(MagickTrue);
1440}
Note: See TracBrowser for help on using the repository browser.