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

Revision 7625, 56.3 KB checked in by anthony, 13 months ago (diff)

Fix Gaussian Filter which was causing problems with Variable Blur

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