]> granicus.if.org Git - imagemagick/blob - MagickCore/shear.c
(no commit message)
[imagemagick] / MagickCore / shear.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                      SSSSS  H   H  EEEEE   AAA    RRRR                      %
7 %                      SS     H   H  E      A   A   R   R                     %
8 %                       SSS   HHHHH  EEE    AAAAA   RRRR                      %
9 %                         SS  H   H  E      A   A   R R                       %
10 %                      SSSSS  H   H  EEEEE  A   A   R  R                      %
11 %                                                                             %
12 %                                                                             %
13 %    MagickCore Methods to Shear or Rotate an Image by an Arbitrary Angle     %
14 %                                                                             %
15 %                               Software Design                               %
16 %                                 John Cristy                                 %
17 %                                  July 1992                                  %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2012 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    http://www.imagemagick.org/script/license.php                            %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %  The XShearImage() and YShearImage() methods are based on the paper "A Fast
37 %  Algorithm for General Raster Rotatation" by Alan W. Paeth, Graphics
38 %  Interface '86 (Vancouver).  ShearRotateImage() is adapted from a similar
39 %  method based on the Paeth paper written by Michael Halle of the Spatial
40 %  Imaging Group, MIT Media Lab.
41 %
42 */
43 \f
44 /*
45   Include declarations.
46 */
47 #include "MagickCore/studio.h"
48 #include "MagickCore/artifact.h"
49 #include "MagickCore/attribute.h"
50 #include "MagickCore/blob-private.h"
51 #include "MagickCore/cache-private.h"
52 #include "MagickCore/color-private.h"
53 #include "MagickCore/colorspace-private.h"
54 #include "MagickCore/composite.h"
55 #include "MagickCore/composite-private.h"
56 #include "MagickCore/decorate.h"
57 #include "MagickCore/distort.h"
58 #include "MagickCore/draw.h"
59 #include "MagickCore/exception.h"
60 #include "MagickCore/exception-private.h"
61 #include "MagickCore/gem.h"
62 #include "MagickCore/geometry.h"
63 #include "MagickCore/image.h"
64 #include "MagickCore/image-private.h"
65 #include "MagickCore/memory_.h"
66 #include "MagickCore/list.h"
67 #include "MagickCore/monitor.h"
68 #include "MagickCore/monitor-private.h"
69 #include "MagickCore/nt-base-private.h"
70 #include "MagickCore/pixel-accessor.h"
71 #include "MagickCore/quantum.h"
72 #include "MagickCore/resource_.h"
73 #include "MagickCore/shear.h"
74 #include "MagickCore/statistic.h"
75 #include "MagickCore/string_.h"
76 #include "MagickCore/string-private.h"
77 #include "MagickCore/thread-private.h"
78 #include "MagickCore/threshold.h"
79 #include "MagickCore/transform.h"
80 \f
81 /*
82 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
83 %                                                                             %
84 %                                                                             %
85 %                                                                             %
86 +   C r o p T o F i t I m a g e                                               %
87 %                                                                             %
88 %                                                                             %
89 %                                                                             %
90 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
91 %
92 %  CropToFitImage() crops the sheared image as determined by the bounding box
93 %  as defined by width and height and shearing angles.
94 %
95 %  The format of the CropToFitImage method is:
96 %
97 %      MagickBooleanType CropToFitImage(Image **image,
98 %        const double x_shear,const double x_shear,
99 %        const double width,const double height,
100 %        const MagickBooleanType rotate,ExceptionInfo *exception)
101 %
102 %  A description of each parameter follows.
103 %
104 %    o image: the image.
105 %
106 %    o x_shear, y_shear, width, height: Defines a region of the image to crop.
107 %
108 %    o exception: return any errors or warnings in this structure.
109 %
110 */
111 static MagickBooleanType CropToFitImage(Image **image,
112   const double x_shear,const double y_shear,
113   const double width,const double height,
114   const MagickBooleanType rotate,ExceptionInfo *exception)
115 {
116   Image
117     *crop_image;
118
119   PointInfo
120     extent[4],
121     min,
122     max;
123
124   RectangleInfo
125     geometry,
126     page;
127
128   register ssize_t
129     i;
130
131   /*
132     Calculate the rotated image size.
133   */
134   extent[0].x=(double) (-width/2.0);
135   extent[0].y=(double) (-height/2.0);
136   extent[1].x=(double) width/2.0;
137   extent[1].y=(double) (-height/2.0);
138   extent[2].x=(double) (-width/2.0);
139   extent[2].y=(double) height/2.0;
140   extent[3].x=(double) width/2.0;
141   extent[3].y=(double) height/2.0;
142   for (i=0; i < 4; i++)
143   {
144     extent[i].x+=x_shear*extent[i].y;
145     extent[i].y+=y_shear*extent[i].x;
146     if (rotate != MagickFalse)
147       extent[i].x+=x_shear*extent[i].y;
148     extent[i].x+=(double) (*image)->columns/2.0;
149     extent[i].y+=(double) (*image)->rows/2.0;
150   }
151   min=extent[0];
152   max=extent[0];
153   for (i=1; i < 4; i++)
154   {
155     if (min.x > extent[i].x)
156       min.x=extent[i].x;
157     if (min.y > extent[i].y)
158       min.y=extent[i].y;
159     if (max.x < extent[i].x)
160       max.x=extent[i].x;
161     if (max.y < extent[i].y)
162       max.y=extent[i].y;
163   }
164   geometry.x=(ssize_t) ceil(min.x-0.5);
165   geometry.y=(ssize_t) ceil(min.y-0.5);
166   geometry.width=(size_t) floor(max.x-min.x+0.5);
167   geometry.height=(size_t) floor(max.y-min.y+0.5);
168   page=(*image)->page;
169   (void) ParseAbsoluteGeometry("0x0+0+0",&(*image)->page);
170   crop_image=CropImage(*image,&geometry,exception);
171   if (crop_image == (Image *) NULL)
172     return(MagickFalse);
173   crop_image->page=page;
174   *image=DestroyImage(*image);
175   *image=crop_image;
176   return(MagickTrue);
177 }
178 \f
179 /*
180 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
181 %                                                                             %
182 %                                                                             %
183 %                                                                             %
184 %     D e s k e w I m a g e                                                   %
185 %                                                                             %
186 %                                                                             %
187 %                                                                             %
188 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
189 %
190 %  DeskewImage() removes skew from the image.  Skew is an artifact that
191 %  occurs in scanned images because of the camera being misaligned,
192 %  imperfections in the scanning or surface, or simply because the paper was
193 %  not placed completely flat when scanned.
194 %
195 %  The format of the DeskewImage method is:
196 %
197 %      Image *DeskewImage(const Image *image,const double threshold,
198 %        ExceptionInfo *exception)
199 %
200 %  A description of each parameter follows:
201 %
202 %    o image: the image.
203 %
204 %    o threshold: separate background from foreground.
205 %
206 %    o exception: return any errors or warnings in this structure.
207 %
208 */
209
210 typedef struct _RadonInfo
211 {
212   CacheType
213     type;
214
215   size_t
216     width,
217     height;
218
219   MagickSizeType
220     length;
221
222   MagickBooleanType
223     mapped;
224
225   char
226     path[MaxTextExtent];
227
228   int
229     file;
230
231   unsigned short
232     *cells;
233 } RadonInfo;
234
235 static RadonInfo *DestroyRadonInfo(RadonInfo *radon_info)
236 {
237   assert(radon_info != (RadonInfo *) NULL);
238   switch (radon_info->type)
239   {
240     case MemoryCache:
241     {
242       if (radon_info->mapped == MagickFalse)
243         radon_info->cells=(unsigned short *) RelinquishMagickMemory(
244           radon_info->cells);
245       else
246         radon_info->cells=(unsigned short *) UnmapBlob(radon_info->cells,
247           (size_t) radon_info->length);
248       RelinquishMagickResource(MemoryResource,radon_info->length);
249       break;
250     }
251     case MapCache:
252     {
253       radon_info->cells=(unsigned short *) UnmapBlob(radon_info->cells,(size_t)
254         radon_info->length);
255       RelinquishMagickResource(MapResource,radon_info->length);
256     }
257     case DiskCache:
258     {
259       if (radon_info->file != -1)
260         (void) close(radon_info->file);
261       (void) RelinquishUniqueFileResource(radon_info->path);
262       RelinquishMagickResource(DiskResource,radon_info->length);
263       break;
264     }
265     default:
266       break;
267   }
268   return((RadonInfo *) RelinquishMagickMemory(radon_info));
269 }
270
271 static MagickBooleanType ResetRadonCells(RadonInfo *radon_info)
272 {
273   register ssize_t
274     x;
275
276   ssize_t
277     count,
278     y;
279
280   unsigned short
281     value;
282
283   if (radon_info->type != DiskCache)
284     {
285       (void) ResetMagickMemory(radon_info->cells,0,(size_t) radon_info->length);
286       return(MagickTrue);
287     }
288   value=0;
289   (void) lseek(radon_info->file,0,SEEK_SET);
290   for (y=0; y < (ssize_t) radon_info->height; y++)
291   {
292     for (x=0; x < (ssize_t) radon_info->width; x++)
293     {
294       count=write(radon_info->file,&value,sizeof(*radon_info->cells));
295       if (count != (ssize_t) sizeof(*radon_info->cells))
296         break;
297     }
298     if (x < (ssize_t) radon_info->width)
299       break;
300   }
301   return(y < (ssize_t) radon_info->height ? MagickFalse : MagickTrue);
302 }
303
304 static RadonInfo *AcquireRadonInfo(const Image *image,const size_t width,
305   const size_t height,ExceptionInfo *exception)
306 {
307   MagickBooleanType
308     status;
309
310   RadonInfo
311     *radon_info;
312
313   radon_info=(RadonInfo *) AcquireMagickMemory(sizeof(*radon_info));
314   if (radon_info == (RadonInfo *) NULL)
315     return((RadonInfo *) NULL);
316   (void) ResetMagickMemory(radon_info,0,sizeof(*radon_info));
317   radon_info->width=width;
318   radon_info->height=height;
319   radon_info->length=(MagickSizeType) width*height*sizeof(*radon_info->cells);
320   radon_info->type=MemoryCache;
321   status=AcquireMagickResource(AreaResource,radon_info->length);
322   if ((status != MagickFalse) &&
323       (radon_info->length == (MagickSizeType) ((size_t) radon_info->length)))
324     {
325       status=AcquireMagickResource(MemoryResource,radon_info->length);
326       if (status != MagickFalse)
327         {
328           radon_info->mapped=MagickFalse;
329           radon_info->cells=(unsigned short *) AcquireMagickMemory((size_t)
330             radon_info->length);
331           if (radon_info->cells == (unsigned short *) NULL)
332             {
333               radon_info->mapped=MagickTrue;
334               radon_info->cells=(unsigned short *) MapBlob(-1,IOMode,0,(size_t)
335                 radon_info->length);
336             }
337           if (radon_info->cells == (unsigned short *) NULL)
338             RelinquishMagickResource(MemoryResource,radon_info->length);
339         }
340     }
341   radon_info->file=(-1);
342   if (radon_info->cells == (unsigned short *) NULL)
343     {
344       status=AcquireMagickResource(DiskResource,radon_info->length);
345       if (status == MagickFalse)
346         {
347           (void) ThrowMagickException(exception,GetMagickModule(),CacheError,
348             "CacheResourcesExhausted","'%s'",image->filename);
349           return(DestroyRadonInfo(radon_info));
350         }
351       radon_info->type=DiskCache;
352       (void) AcquireMagickResource(MemoryResource,radon_info->length);
353       radon_info->file=AcquireUniqueFileResource(radon_info->path);
354       if (radon_info->file == -1)
355         return(DestroyRadonInfo(radon_info));
356       status=AcquireMagickResource(MapResource,radon_info->length);
357       if (status != MagickFalse)
358         {
359           status=ResetRadonCells(radon_info);
360           if (status != MagickFalse)
361             {
362               radon_info->cells=(unsigned short *) MapBlob(radon_info->file,
363                 IOMode,0,(size_t) radon_info->length);
364               if (radon_info->cells != (unsigned short *) NULL)
365                 radon_info->type=MapCache;
366               else
367                 RelinquishMagickResource(MapResource,radon_info->length);
368             }
369         }
370     }
371   return(radon_info);
372 }
373
374 static inline size_t MagickMin(const size_t x,const size_t y)
375 {
376   if (x < y)
377     return(x);
378   return(y);
379 }
380
381 static inline ssize_t ReadRadonCell(const RadonInfo *radon_info,
382   const MagickOffsetType offset,const size_t length,unsigned char *buffer)
383 {
384   register ssize_t
385     i;
386
387   ssize_t
388     count;
389
390 #if !defined(MAGICKCORE_HAVE_PPREAD)
391 #if defined(MAGICKCORE_OPENMP_SUPPORT)
392   #pragma omp critical (MagickCore_ReadRadonCell)
393 #endif
394   {
395     i=(-1);
396     if (lseek(radon_info->file,offset,SEEK_SET) >= 0)
397       {
398 #endif
399         count=0;
400         for (i=0; i < (ssize_t) length; i+=count)
401         {
402 #if !defined(MAGICKCORE_HAVE_PPREAD)
403           count=read(radon_info->file,buffer+i,MagickMin(length-i,(size_t)
404             SSIZE_MAX));
405 #else
406           count=pread(radon_info->file,buffer+i,MagickMin(length-i,(size_t)
407             SSIZE_MAX),offset+i);
408 #endif
409           if (count > 0)
410             continue;
411           count=0;
412           if (errno != EINTR)
413             {
414               i=(-1);
415               break;
416             }
417         }
418 #if !defined(MAGICKCORE_HAVE_PPREAD)
419       }
420   }
421 #endif
422   return(i);
423 }
424
425 static inline ssize_t WriteRadonCell(const RadonInfo *radon_info,
426   const MagickOffsetType offset,const size_t length,const unsigned char *buffer)
427 {
428   register ssize_t
429     i;
430
431   ssize_t
432     count;
433
434 #if !defined(MAGICKCORE_HAVE_PWRITE)
435 #if defined(MAGICKCORE_OPENMP_SUPPORT)
436   #pragma omp critical (MagickCore_WriteRadonCell)
437 #endif
438   {
439     if (lseek(radon_info->file,offset,SEEK_SET) >= 0)
440       {
441 #endif
442         count=0;
443         for (i=0; i < (ssize_t) length; i+=count)
444         {
445 #if !defined(MAGICKCORE_HAVE_PWRITE)
446           count=write(radon_info->file,buffer+i,MagickMin(length-i,(size_t)
447             SSIZE_MAX));
448 #else
449           count=pwrite(radon_info->file,buffer+i,MagickMin(length-i,(size_t)
450             SSIZE_MAX),offset+i);
451 #endif
452           if (count > 0)
453             continue;
454           count=0;
455           if (errno != EINTR)
456             {
457               i=(-1);
458               break;
459             }
460         }
461 #if !defined(MAGICKCORE_HAVE_PWRITE)
462       }
463   }
464 #endif
465   return(i);
466 }
467
468 static inline unsigned short GetRadonCell(const RadonInfo *radon_info,
469   const ssize_t x,const ssize_t y)
470 {
471   MagickOffsetType
472     i;
473
474   unsigned short
475     value;
476
477   i=(MagickOffsetType) radon_info->height*x+y;
478   if ((i < 0) ||
479       ((MagickSizeType) (i*sizeof(*radon_info->cells)) >= radon_info->length))
480     return(0);
481   if (radon_info->type != DiskCache)
482     return(radon_info->cells[i]);
483   value=0;
484   (void) ReadRadonCell(radon_info,i*sizeof(*radon_info->cells),
485     sizeof(*radon_info->cells),(unsigned char *) &value);
486   return(value);
487 }
488
489 static inline MagickBooleanType SetRadonCell(const RadonInfo *radon_info,
490   const ssize_t x,const ssize_t y,const unsigned short value)
491 {
492   MagickOffsetType
493     i;
494
495   ssize_t
496     count;
497
498   i=(MagickOffsetType) radon_info->height*x+y;
499   if ((i < 0) ||
500       ((MagickSizeType) (i*sizeof(*radon_info->cells)) >= radon_info->length))
501     return(MagickFalse);
502   if (radon_info->type != DiskCache)
503     {
504       radon_info->cells[i]=value;
505       return(MagickTrue);
506     }
507   count=WriteRadonCell(radon_info,i*sizeof(*radon_info->cells),
508     sizeof(*radon_info->cells),(const unsigned char *) &value);
509   if (count != (ssize_t) sizeof(*radon_info->cells))
510     return(MagickFalse);
511   return(MagickTrue);
512 }
513
514 static void RadonProjection(const Image *image,RadonInfo *source_cells,
515   RadonInfo *destination_cells,const ssize_t sign,size_t *projection)
516 {
517   RadonInfo
518     *swap;
519
520   register ssize_t
521     x;
522
523   register RadonInfo
524     *p,
525     *q;
526
527   size_t
528     step;
529
530   p=source_cells;
531   q=destination_cells;
532   for (step=1; step < p->width; step*=2)
533   {
534     for (x=0; x < (ssize_t) p->width; x+=2*(ssize_t) step)
535     {
536       register ssize_t
537         i;
538
539       ssize_t
540         y;
541
542       unsigned short
543         cell;
544
545       for (i=0; i < (ssize_t) step; i++)
546       {
547         for (y=0; y < (ssize_t) (p->height-i-1); y++)
548         {
549           cell=GetRadonCell(p,x+i,y);
550           (void) SetRadonCell(q,x+2*i,y,cell+GetRadonCell(p,x+i+(ssize_t)
551             step,y+i));
552           (void) SetRadonCell(q,x+2*i+1,y,cell+GetRadonCell(p,x+i+(ssize_t)
553             step,y+i+1));
554         }
555         for ( ; y < (ssize_t) (p->height-i); y++)
556         {
557           cell=GetRadonCell(p,x+i,y);
558           (void) SetRadonCell(q,x+2*i,y,cell+GetRadonCell(p,x+i+(ssize_t) step,
559             y+i));
560           (void) SetRadonCell(q,x+2*i+1,y,cell);
561         }
562         for ( ; y < (ssize_t) p->height; y++)
563         {
564           cell=GetRadonCell(p,x+i,y);
565           (void) SetRadonCell(q,x+2*i,y,cell);
566           (void) SetRadonCell(q,x+2*i+1,y,cell);
567         }
568       }
569     }
570     swap=p;
571     p=q;
572     q=swap;
573   }
574 #if defined(MAGICKCORE_OPENMP_SUPPORT)
575   #pragma omp parallel for schedule(static,4) \
576     dynamic_number_threads(image,p->width,p->height,1)
577 #endif
578   for (x=0; x < (ssize_t) p->width; x++)
579   {
580     register ssize_t
581       y;
582
583     size_t
584       sum;
585
586     sum=0;
587     for (y=0; y < (ssize_t) (p->height-1); y++)
588     {
589       ssize_t
590         delta;
591
592       delta=GetRadonCell(p,x,y)-(ssize_t) GetRadonCell(p,x,y+1);
593       sum+=delta*delta;
594     }
595     projection[p->width+sign*x-1]=sum;
596   }
597 }
598
599 static MagickBooleanType RadonTransform(const Image *image,
600   const double threshold,size_t *projection,ExceptionInfo *exception)
601 {
602   CacheView
603     *image_view;
604
605   MagickBooleanType
606     status;
607
608   RadonInfo
609     *destination_cells,
610     *source_cells;
611
612   register ssize_t
613     i;
614
615   size_t
616     count,
617     width;
618
619   ssize_t
620     y;
621
622   unsigned char
623     byte;
624
625   unsigned short
626     bits[256];
627
628   for (width=1; width < ((image->columns+7)/8); width<<=1) ;
629   source_cells=AcquireRadonInfo(image,width,image->rows,exception);
630   destination_cells=AcquireRadonInfo(image,width,image->rows,exception);
631   if ((source_cells == (RadonInfo *) NULL) ||
632       (destination_cells == (RadonInfo *) NULL))
633     {
634       if (destination_cells != (RadonInfo *) NULL)
635         destination_cells=DestroyRadonInfo(destination_cells);
636       if (source_cells != (RadonInfo *) NULL)
637         source_cells=DestroyRadonInfo(source_cells);
638       return(MagickFalse);
639     }
640   if (ResetRadonCells(source_cells) == MagickFalse)
641     {
642       destination_cells=DestroyRadonInfo(destination_cells);
643       source_cells=DestroyRadonInfo(source_cells);
644       return(MagickFalse);
645     }
646   for (i=0; i < 256; i++)
647   {
648     byte=(unsigned char) i;
649     for (count=0; byte != 0; byte>>=1)
650       count+=byte & 0x01;
651     bits[i]=(unsigned short) count;
652   }
653   status=MagickTrue;
654   image_view=AcquireVirtualCacheView(image,exception);
655 #if defined(MAGICKCORE_OPENMP_SUPPORT)
656   #pragma omp parallel for schedule(static,4) shared(status) \
657     dynamic_number_threads(image,image->columns,image->rows,1)
658 #endif
659   for (y=0; y < (ssize_t) image->rows; y++)
660   {
661     register const Quantum
662       *restrict p;
663
664     register ssize_t
665       i,
666       x;
667
668     size_t
669       bit,
670       byte;
671
672     if (status == MagickFalse)
673       continue;
674     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
675     if (p == (const Quantum *) NULL)
676       {
677         status=MagickFalse;
678         continue;
679       }
680     bit=0;
681     byte=0;
682     i=(ssize_t) (image->columns+7)/8;
683     for (x=0; x < (ssize_t) image->columns; x++)
684     {
685       byte<<=1;
686       if (GetPixelIntensity(image,p) < threshold)
687         byte|=0x01;
688       bit++;
689       if (bit == 8)
690         {
691           (void) SetRadonCell(source_cells,--i,y,bits[byte]);
692           bit=0;
693           byte=0;
694         }
695       p+=GetPixelChannels(image);
696     }
697     if (bit != 0)
698       {
699         byte<<=(8-bit);
700         (void) SetRadonCell(source_cells,--i,y,bits[byte]);
701       }
702   }
703   RadonProjection(image,source_cells,destination_cells,-1,projection);
704   (void) ResetRadonCells(source_cells);
705 #if defined(MAGICKCORE_OPENMP_SUPPORT)
706   #pragma omp parallel for schedule(static,4) shared(status) \
707     dynamic_number_threads(image,image->columns,image->rows,1)
708 #endif
709   for (y=0; y < (ssize_t) image->rows; y++)
710   {
711     register const Quantum
712       *restrict p;
713
714     register ssize_t
715       i,
716       x;
717
718     size_t
719       bit,
720       byte;
721
722     if (status == MagickFalse)
723       continue;
724     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
725     if (p == (const Quantum *) NULL)
726       {
727         status=MagickFalse;
728         continue;
729       }
730     bit=0;
731     byte=0;
732     i=0;
733     for (x=0; x < (ssize_t) image->columns; x++)
734     {
735       byte<<=1;
736       if (GetPixelIntensity(image,p) < threshold)
737         byte|=0x01;
738       bit++;
739       if (bit == 8)
740         {
741           (void) SetRadonCell(source_cells,i++,y,bits[byte]);
742           bit=0;
743           byte=0;
744         }
745       p+=GetPixelChannels(image);
746     }
747     if (bit != 0)
748       {
749         byte<<=(8-bit);
750         (void) SetRadonCell(source_cells,i++,y,bits[byte]);
751       }
752   }
753   RadonProjection(image,source_cells,destination_cells,1,projection);
754   image_view=DestroyCacheView(image_view);
755   destination_cells=DestroyRadonInfo(destination_cells);
756   source_cells=DestroyRadonInfo(source_cells);
757   return(MagickTrue);
758 }
759
760 static void GetImageBackgroundColor(Image *image,const ssize_t offset,
761   ExceptionInfo *exception)
762 {
763   CacheView
764     *image_view;
765
766   PixelInfo
767     background;
768
769   double
770     count;
771
772   ssize_t
773     y;
774
775   /*
776     Compute average background color.
777   */
778   if (offset <= 0)
779     return;
780   GetPixelInfo(image,&background);
781   count=0.0;
782   image_view=AcquireVirtualCacheView(image,exception);
783   for (y=0; y < (ssize_t) image->rows; y++)
784   {
785     register const Quantum
786       *restrict p;
787
788     register ssize_t
789       x;
790
791     if ((y >= offset) && (y < ((ssize_t) image->rows-offset)))
792       continue;
793     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
794     if (p == (const Quantum *) NULL)
795       continue;
796     for (x=0; x < (ssize_t) image->columns; x++)
797     {
798       if ((x >= offset) && (x < ((ssize_t) image->columns-offset)))
799         continue;
800       background.red+=QuantumScale*GetPixelRed(image,p);
801       background.green+=QuantumScale*GetPixelGreen(image,p);
802       background.blue+=QuantumScale*GetPixelBlue(image,p);
803       if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
804         background.alpha+=QuantumScale*GetPixelAlpha(image,p);
805       count++;
806       p+=GetPixelChannels(image);
807     }
808   }
809   image_view=DestroyCacheView(image_view);
810   image->background_color.red=(double) ClampToQuantum(QuantumRange*
811     background.red/count);
812   image->background_color.green=(double) ClampToQuantum(QuantumRange*
813     background.green/count);
814   image->background_color.blue=(double) ClampToQuantum(QuantumRange*
815     background.blue/count);
816   if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
817     image->background_color.alpha=(double) ClampToQuantum(QuantumRange*
818       background.alpha/count);
819 }
820
821 MagickExport Image *DeskewImage(const Image *image,const double threshold,
822   ExceptionInfo *exception)
823 {
824   AffineMatrix
825     affine_matrix;
826
827   const char
828     *artifact;
829
830   double
831     degrees;
832
833   Image
834     *clone_image,
835     *crop_image,
836     *deskew_image,
837     *median_image;
838
839   MagickBooleanType
840     status;
841
842   RectangleInfo
843     geometry;
844
845   register ssize_t
846     i;
847
848   size_t
849     max_projection,
850     *projection,
851     width;
852
853   ssize_t
854     skew;
855
856   /*
857     Compute deskew angle.
858   */
859   for (width=1; width < ((image->columns+7)/8); width<<=1) ;
860   projection=(size_t *) AcquireQuantumMemory((size_t) (2*width-1),
861     sizeof(*projection));
862   if (projection == (size_t *) NULL)
863     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
864   status=RadonTransform(image,threshold,projection,exception);
865   if (status == MagickFalse)
866     {
867       projection=(size_t *) RelinquishMagickMemory(projection);
868       ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
869     }
870   max_projection=0;
871   skew=0;
872   for (i=0; i < (ssize_t) (2*width-1); i++)
873   {
874     if (projection[i] > max_projection)
875       {
876         skew=i-(ssize_t) width+1;
877         max_projection=projection[i];
878       }
879   }
880   projection=(size_t *) RelinquishMagickMemory(projection);
881   /*
882     Deskew image.
883   */
884   clone_image=CloneImage(image,0,0,MagickTrue,exception);
885   if (clone_image == (Image *) NULL)
886     return((Image *) NULL);
887   (void) SetImageVirtualPixelMethod(clone_image,BackgroundVirtualPixelMethod,
888     exception);
889   degrees=RadiansToDegrees(-atan((double) skew/width/8));
890   if (image->debug != MagickFalse)
891     (void) LogMagickEvent(TransformEvent,GetMagickModule(),
892       "  Deskew angle: %g",degrees);
893   affine_matrix.sx=cos(DegreesToRadians(fmod((double) degrees,360.0)));
894   affine_matrix.rx=sin(DegreesToRadians(fmod((double) degrees,360.0)));
895   affine_matrix.ry=(-sin(DegreesToRadians(fmod((double) degrees,360.0))));
896   affine_matrix.sy=cos(DegreesToRadians(fmod((double) degrees,360.0)));
897   affine_matrix.tx=0.0;
898   affine_matrix.ty=0.0;
899   artifact=GetImageArtifact(image,"deskew:auto-crop");
900   if (artifact == (const char *) NULL)
901     {
902       deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception);
903       clone_image=DestroyImage(clone_image);
904       return(deskew_image);
905     }
906   /*
907     Auto-crop image.
908   */
909   GetImageBackgroundColor(clone_image,(ssize_t) StringToLong(artifact),
910     exception);
911   deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception);
912   clone_image=DestroyImage(clone_image);
913   if (deskew_image == (Image *) NULL)
914     return((Image *) NULL);
915   median_image=StatisticImage(deskew_image,MedianStatistic,3,3,exception);
916   if (median_image == (Image *) NULL)
917     {
918       deskew_image=DestroyImage(deskew_image);
919       return((Image *) NULL);
920     }
921   geometry=GetImageBoundingBox(median_image,exception);
922   median_image=DestroyImage(median_image);
923   if (image->debug != MagickFalse)
924     (void) LogMagickEvent(TransformEvent,GetMagickModule(),"  Deskew geometry: "
925       "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double)
926       geometry.height,(double) geometry.x,(double) geometry.y);
927   crop_image=CropImage(deskew_image,&geometry,exception);
928   deskew_image=DestroyImage(deskew_image);
929   return(crop_image);
930 }
931 \f
932 /*
933 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
934 %                                                                             %
935 %                                                                             %
936 %                                                                             %
937 %   I n t e g r a l R o t a t e I m a g e                                     %
938 %                                                                             %
939 %                                                                             %
940 %                                                                             %
941 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
942 %
943 %  IntegralRotateImage() rotates the image an integral of 90 degrees.  It
944 %  allocates the memory necessary for the new Image structure and returns a
945 %  pointer to the rotated image.
946 %
947 %  The format of the IntegralRotateImage method is:
948 %
949 %      Image *IntegralRotateImage(const Image *image,size_t rotations,
950 %        ExceptionInfo *exception)
951 %
952 %  A description of each parameter follows.
953 %
954 %    o image: the image.
955 %
956 %    o rotations: Specifies the number of 90 degree rotations.
957 %
958 */
959 MagickExport Image *IntegralRotateImage(const Image *image,size_t rotations,
960   ExceptionInfo *exception)
961 {
962 #define RotateImageTag  "Rotate/Image"
963
964   CacheView
965     *image_view,
966     *rotate_view;
967
968   Image
969     *rotate_image;
970
971   MagickBooleanType
972     status;
973
974   MagickOffsetType
975     progress;
976
977   RectangleInfo
978     page;
979
980   ssize_t
981     y;
982
983   /*
984     Initialize rotated image attributes.
985   */
986   assert(image != (Image *) NULL);
987   page=image->page;
988   rotations%=4;
989   if (rotations == 0)
990     return(CloneImage(image,0,0,MagickTrue,exception));
991   if ((rotations == 1) || (rotations == 3))
992     rotate_image=CloneImage(image,image->rows,image->columns,MagickTrue,
993       exception);
994   else
995     rotate_image=CloneImage(image,image->columns,image->rows,MagickTrue,
996       exception);
997   if (rotate_image == (Image *) NULL)
998     return((Image *) NULL);
999   /*
1000     Integral rotate the image.
1001   */
1002   status=MagickTrue;
1003   progress=0;
1004   image_view=AcquireVirtualCacheView(image,exception);
1005   rotate_view=AcquireAuthenticCacheView(rotate_image,exception);
1006   switch (rotations)
1007   {
1008     case 0:
1009     {
1010       /*
1011         Rotate 0 degrees.
1012       */
1013       break;
1014     }
1015     case 1:
1016     {
1017       size_t
1018         tile_height,
1019         tile_width;
1020
1021       ssize_t
1022         tile_y;
1023
1024       /*
1025         Rotate 90 degrees.
1026       */
1027       GetPixelCacheTileSize(image,&tile_width,&tile_height);
1028       tile_width=(ssize_t) image->columns;
1029       for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height)
1030       {
1031         register ssize_t
1032           tile_x;
1033
1034         if (status == MagickFalse)
1035           continue;
1036         tile_x=0;
1037         for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width)
1038         {
1039           MagickBooleanType
1040             sync;
1041
1042           register const Quantum
1043             *restrict p;
1044
1045           register Quantum
1046             *restrict q;
1047
1048           register ssize_t
1049             y;
1050
1051           size_t
1052             height,
1053             width;
1054
1055           width=tile_width;
1056           if ((tile_x+(ssize_t) tile_width) > (ssize_t) image->columns)
1057             width=(size_t) (tile_width-(tile_x+tile_width-image->columns));
1058           height=tile_height;
1059           if ((tile_y+(ssize_t) tile_height) > (ssize_t) image->rows)
1060             height=(size_t) (tile_height-(tile_y+tile_height-image->rows));
1061           p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height,
1062             exception);
1063           if (p == (const Quantum *) NULL)
1064             {
1065               status=MagickFalse;
1066               break;
1067             }
1068           for (y=0; y < (ssize_t) width; y++)
1069           {
1070             register const Quantum
1071               *restrict tile_pixels;
1072
1073             register ssize_t
1074               x;
1075
1076             if (status == MagickFalse)
1077               continue;
1078             q=QueueCacheViewAuthenticPixels(rotate_view,(ssize_t)
1079               (rotate_image->columns-(tile_y+height)),y+tile_x,height,1,
1080               exception);
1081             if (q == (Quantum *) NULL)
1082               {
1083                 status=MagickFalse;
1084                 continue;
1085               }
1086             tile_pixels=p+((height-1)*width+y)*GetPixelChannels(image);
1087             for (x=0; x < (ssize_t) height; x++)
1088             {
1089               register ssize_t
1090                 i;
1091
1092               if (GetPixelMask(image,tile_pixels) != 0)
1093                 {
1094                   tile_pixels-=width*GetPixelChannels(image);
1095                   q+=GetPixelChannels(rotate_image);
1096                   continue;
1097                 }
1098               for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1099               {
1100                 PixelChannel
1101                   channel;
1102
1103                 PixelTrait
1104                   rotate_traits,
1105                   traits;
1106
1107                 channel=GetPixelChannelChannel(image,i);
1108                 traits=GetPixelChannelTraits(image,channel);
1109                 rotate_traits=GetPixelChannelTraits(rotate_image,channel);
1110                 if ((traits == UndefinedPixelTrait) ||
1111                     (rotate_traits == UndefinedPixelTrait))
1112                   continue;
1113                 SetPixelChannel(rotate_image,channel,tile_pixels[i],q);
1114               }
1115               tile_pixels-=width*GetPixelChannels(image);
1116               q+=GetPixelChannels(rotate_image);
1117             }
1118             sync=SyncCacheViewAuthenticPixels(rotate_view,exception);
1119             if (sync == MagickFalse)
1120               status=MagickFalse;
1121           }
1122         }
1123         if (image->progress_monitor != (MagickProgressMonitor) NULL)
1124           {
1125             MagickBooleanType
1126               proceed;
1127
1128             proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height,
1129               image->rows);
1130             if (proceed == MagickFalse)
1131               status=MagickFalse;
1132           }
1133       }
1134       (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType)
1135         image->rows-1,image->rows);
1136       Swap(page.width,page.height);
1137       Swap(page.x,page.y);
1138       if (page.width != 0)
1139         page.x=(ssize_t) (page.width-rotate_image->columns-page.x);
1140       break;
1141     }
1142     case 2:
1143     {
1144       /*
1145         Rotate 180 degrees.
1146       */
1147       for (y=0; y < (ssize_t) image->rows; y++)
1148       {
1149         MagickBooleanType
1150           sync;
1151
1152         register const Quantum
1153           *restrict p;
1154
1155         register Quantum
1156           *restrict q;
1157
1158         register ssize_t
1159           x;
1160
1161         if (status == MagickFalse)
1162           continue;
1163         p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
1164         q=QueueCacheViewAuthenticPixels(rotate_view,0,(ssize_t) (image->rows-y-
1165           1),image->columns,1,exception);
1166         if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
1167           {
1168             status=MagickFalse;
1169             continue;
1170           }
1171         q+=GetPixelChannels(rotate_image)*image->columns;
1172         for (x=0; x < (ssize_t) image->columns; x++)
1173         {
1174           register ssize_t
1175             i;
1176
1177           q-=GetPixelChannels(rotate_image);
1178           if (GetPixelMask(image,p) != 0)
1179             {
1180               p+=GetPixelChannels(image);
1181               continue;
1182             }
1183           for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1184           {
1185             PixelChannel
1186               channel;
1187
1188             PixelTrait
1189               rotate_traits,
1190               traits;
1191
1192             channel=GetPixelChannelChannel(image,i);
1193             traits=GetPixelChannelTraits(image,channel);
1194             rotate_traits=GetPixelChannelTraits(rotate_image,channel);
1195             if ((traits == UndefinedPixelTrait) ||
1196                 (rotate_traits == UndefinedPixelTrait))
1197               continue;
1198             SetPixelChannel(rotate_image,channel,p[i],q);
1199           }
1200           p+=GetPixelChannels(image);
1201         }
1202         sync=SyncCacheViewAuthenticPixels(rotate_view,exception);
1203         if (sync == MagickFalse)
1204           status=MagickFalse;
1205         if (image->progress_monitor != (MagickProgressMonitor) NULL)
1206           {
1207             MagickBooleanType
1208               proceed;
1209
1210             proceed=SetImageProgress(image,RotateImageTag,progress++,
1211               image->rows);
1212             if (proceed == MagickFalse)
1213               status=MagickFalse;
1214           }
1215       }
1216       (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType)
1217         image->rows-1,image->rows);
1218       Swap(page.width,page.height);
1219       Swap(page.x,page.y);
1220       if (page.width != 0)
1221         page.x=(ssize_t) (page.width-rotate_image->columns-page.x);
1222       break;
1223     }
1224     case 3:
1225     {
1226       size_t
1227         tile_height,
1228         tile_width;
1229
1230       ssize_t
1231         tile_y;
1232
1233       /*
1234         Rotate 270 degrees.
1235       */
1236       GetPixelCacheTileSize(image,&tile_width,&tile_height);
1237       tile_width=(ssize_t) image->columns;
1238       for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height)
1239       {
1240         register ssize_t
1241           tile_x;
1242
1243         if (status == MagickFalse)
1244           continue;
1245         tile_x=0;
1246         for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width)
1247         {
1248           MagickBooleanType
1249             sync;
1250
1251           register const Quantum
1252             *restrict p;
1253
1254           register Quantum
1255             *restrict q;
1256
1257           register ssize_t
1258             y;
1259
1260           size_t
1261             height,
1262             width;
1263
1264           width=tile_width;
1265           if ((tile_x+(ssize_t) tile_width) > (ssize_t) image->columns)
1266             width=(size_t) (tile_width-(tile_x+tile_width-image->columns));
1267           height=tile_height;
1268           if ((tile_y+(ssize_t) tile_height) > (ssize_t) image->rows)
1269             height=(size_t) (tile_height-(tile_y+tile_height-image->rows));
1270           p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height,
1271             exception);
1272           if (p == (const Quantum *) NULL)
1273             {
1274               status=MagickFalse;
1275               break;
1276             }
1277           for (y=0; y < (ssize_t) width; y++)
1278           {
1279             register const Quantum
1280               *restrict tile_pixels;
1281
1282             register ssize_t
1283               x;
1284
1285             if (status == MagickFalse)
1286               continue;
1287             q=QueueCacheViewAuthenticPixels(rotate_view,tile_y,(ssize_t) (y+
1288               rotate_image->rows-(tile_x+width)),height,1,exception);
1289             if (q == (Quantum *) NULL)
1290               {
1291                 status=MagickFalse;
1292                 continue;
1293               }
1294             tile_pixels=p+((width-1)-y)*GetPixelChannels(image);
1295             for (x=0; x < (ssize_t) height; x++)
1296             {
1297               register ssize_t
1298                 i;
1299
1300               if (GetPixelMask(image,tile_pixels) != 0)
1301                 {
1302                   tile_pixels+=width*GetPixelChannels(image);
1303                   q+=GetPixelChannels(rotate_image);
1304                   continue;
1305                 }
1306               for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1307               {
1308                 PixelChannel
1309                   channel;
1310
1311                 PixelTrait
1312                   rotate_traits,
1313                   traits;
1314
1315                 channel=GetPixelChannelChannel(image,i);
1316                 traits=GetPixelChannelTraits(image,channel);
1317                 rotate_traits=GetPixelChannelTraits(rotate_image,channel);
1318                 if ((traits == UndefinedPixelTrait) ||
1319                     (rotate_traits == UndefinedPixelTrait))
1320                   continue;
1321                 SetPixelChannel(rotate_image,channel,tile_pixels[i],q);
1322               }
1323               tile_pixels+=width*GetPixelChannels(image);
1324               q+=GetPixelChannels(rotate_image);
1325             }
1326             sync=SyncCacheViewAuthenticPixels(rotate_view,exception);
1327             if (sync == MagickFalse)
1328               status=MagickFalse;
1329           }
1330         }
1331         if (image->progress_monitor != (MagickProgressMonitor) NULL)
1332           {
1333             MagickBooleanType
1334               proceed;
1335
1336             proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height,
1337               image->rows);
1338             if (proceed == MagickFalse)
1339               status=MagickFalse;
1340           }
1341       }
1342       (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType)
1343         image->rows-1,image->rows);
1344       Swap(page.width,page.height);
1345       Swap(page.x,page.y);
1346       if (page.width != 0)
1347         page.x=(ssize_t) (page.width-rotate_image->columns-page.x);
1348       break;
1349     }
1350   }
1351   rotate_view=DestroyCacheView(rotate_view);
1352   image_view=DestroyCacheView(image_view);
1353   rotate_image->type=image->type;
1354   rotate_image->page=page;
1355   if (status == MagickFalse)
1356     rotate_image=DestroyImage(rotate_image);
1357   return(rotate_image);
1358 }
1359 \f
1360 /*
1361 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1362 %                                                                             %
1363 %                                                                             %
1364 %                                                                             %
1365 +   X S h e a r I m a g e                                                     %
1366 %                                                                             %
1367 %                                                                             %
1368 %                                                                             %
1369 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1370 %
1371 %  XShearImage() shears the image in the X direction with a shear angle of
1372 %  'degrees'.  Positive angles shear counter-clockwise (right-hand rule), and
1373 %  negative angles shear clockwise.  Angles are measured relative to a vertical
1374 %  Y-axis.  X shears will widen an image creating 'empty' triangles on the left
1375 %  and right sides of the source image.
1376 %
1377 %  The format of the XShearImage method is:
1378 %
1379 %      MagickBooleanType XShearImage(Image *image,const double degrees,
1380 %        const size_t width,const size_t height,
1381 %        const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception)
1382 %
1383 %  A description of each parameter follows.
1384 %
1385 %    o image: the image.
1386 %
1387 %    o degrees: A double representing the shearing angle along the X
1388 %      axis.
1389 %
1390 %    o width, height, x_offset, y_offset: Defines a region of the image
1391 %      to shear.
1392 %
1393 %    o exception: return any errors or warnings in this structure.
1394 %
1395 */
1396 static MagickBooleanType XShearImage(Image *image,const double degrees,
1397   const size_t width,const size_t height,const ssize_t x_offset,
1398   const ssize_t y_offset,ExceptionInfo *exception)
1399 {
1400 #define XShearImageTag  "XShear/Image"
1401
1402   typedef enum
1403   {
1404     LEFT,
1405     RIGHT
1406   } ShearDirection;
1407
1408   CacheView
1409     *image_view;
1410
1411   MagickBooleanType
1412     status;
1413
1414   MagickOffsetType
1415     progress;
1416
1417   PixelInfo
1418     background;
1419
1420   ssize_t
1421     y;
1422
1423   /*
1424     X shear image.
1425   */
1426   assert(image != (Image *) NULL);
1427   assert(image->signature == MagickSignature);
1428   if (image->debug != MagickFalse)
1429     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1430   status=MagickTrue;
1431   background=image->background_color;
1432   progress=0;
1433   image_view=AcquireAuthenticCacheView(image,exception);
1434 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1435   #pragma omp parallel for schedule(static,4) shared(progress,status) \
1436     dynamic_number_threads(image,width,height,1)
1437 #endif
1438   for (y=0; y < (ssize_t) height; y++)
1439   {
1440     PixelInfo
1441       pixel,
1442       source,
1443       destination;
1444
1445     double
1446       area,
1447       displacement;
1448
1449     register Quantum
1450       *restrict p,
1451       *restrict q;
1452
1453     register ssize_t
1454       i;
1455
1456     ShearDirection
1457       direction;
1458
1459     ssize_t
1460       step;
1461
1462     if (status == MagickFalse)
1463       continue;
1464     p=GetCacheViewAuthenticPixels(image_view,0,y_offset+y,image->columns,1,
1465       exception);
1466     if (p == (Quantum *) NULL)
1467       {
1468         status=MagickFalse;
1469         continue;
1470       }
1471     p+=x_offset*GetPixelChannels(image);
1472     displacement=degrees*(double) (y-height/2.0);
1473     if (displacement == 0.0)
1474       continue;
1475     if (displacement > 0.0)
1476       direction=RIGHT;
1477     else
1478       {
1479         displacement*=(-1.0);
1480         direction=LEFT;
1481       }
1482     step=(ssize_t) floor((double) displacement);
1483     area=(double) (displacement-step);
1484     step++;
1485     pixel=background;
1486     GetPixelInfo(image,&source);
1487     GetPixelInfo(image,&destination);
1488     switch (direction)
1489     {
1490       case LEFT:
1491       {
1492         /*
1493           Transfer pixels left-to-right.
1494         */
1495         if (step > x_offset)
1496           break;
1497         q=p-step*GetPixelChannels(image);
1498         for (i=0; i < (ssize_t) width; i++)
1499         {
1500           if ((x_offset+i) < step)
1501             {
1502               p+=GetPixelChannels(image);
1503               GetPixelInfoPixel(image,p,&pixel);
1504               q+=GetPixelChannels(image);
1505               continue;
1506             }
1507           GetPixelInfoPixel(image,p,&source);
1508           CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1509             &source,(double) GetPixelAlpha(image,p),area,&destination);
1510           SetPixelInfoPixel(image,&destination,q);
1511           GetPixelInfoPixel(image,p,&pixel);
1512           p+=GetPixelChannels(image);
1513           q+=GetPixelChannels(image);
1514         }
1515         CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1516           &background,(double) background.alpha,area,&destination);
1517         SetPixelInfoPixel(image,&destination,q);
1518         q+=GetPixelChannels(image);
1519         for (i=0; i < (step-1); i++)
1520         {
1521           SetPixelInfoPixel(image,&background,q);
1522           q+=GetPixelChannels(image);
1523         }
1524         break;
1525       }
1526       case RIGHT:
1527       {
1528         /*
1529           Transfer pixels right-to-left.
1530         */
1531         p+=width*GetPixelChannels(image);
1532         q=p+step*GetPixelChannels(image);
1533         for (i=0; i < (ssize_t) width; i++)
1534         {
1535           p-=GetPixelChannels(image);
1536           q-=GetPixelChannels(image);
1537           if ((size_t) (x_offset+width+step-i) >= image->columns)
1538             continue;
1539           GetPixelInfoPixel(image,p,&source);
1540           CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1541             &source,(double) GetPixelAlpha(image,p),area,&destination);
1542           SetPixelInfoPixel(image,&destination,q);
1543           GetPixelInfoPixel(image,p,&pixel);
1544         }
1545         CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1546           &background,(double) background.alpha,area,&destination);
1547         q-=GetPixelChannels(image);
1548         SetPixelInfoPixel(image,&destination,q);
1549         for (i=0; i < (step-1); i++)
1550         {
1551           q-=GetPixelChannels(image);
1552           SetPixelInfoPixel(image,&background,q);
1553         }
1554         break;
1555       }
1556     }
1557     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1558       status=MagickFalse;
1559     if (image->progress_monitor != (MagickProgressMonitor) NULL)
1560       {
1561         MagickBooleanType
1562           proceed;
1563
1564 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1565         #pragma omp critical (MagickCore_XShearImage)
1566 #endif
1567         proceed=SetImageProgress(image,XShearImageTag,progress++,height);
1568         if (proceed == MagickFalse)
1569           status=MagickFalse;
1570       }
1571   }
1572   image_view=DestroyCacheView(image_view);
1573   return(status);
1574 }
1575 \f
1576 /*
1577 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1578 %                                                                             %
1579 %                                                                             %
1580 %                                                                             %
1581 +   Y S h e a r I m a g e                                                     %
1582 %                                                                             %
1583 %                                                                             %
1584 %                                                                             %
1585 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1586 %
1587 %  YShearImage shears the image in the Y direction with a shear angle of
1588 %  'degrees'.  Positive angles shear counter-clockwise (right-hand rule), and
1589 %  negative angles shear clockwise.  Angles are measured relative to a
1590 %  horizontal X-axis.  Y shears will increase the height of an image creating
1591 %  'empty' triangles on the top and bottom of the source image.
1592 %
1593 %  The format of the YShearImage method is:
1594 %
1595 %      MagickBooleanType YShearImage(Image *image,const double degrees,
1596 %        const size_t width,const size_t height,
1597 %        const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception)
1598 %
1599 %  A description of each parameter follows.
1600 %
1601 %    o image: the image.
1602 %
1603 %    o degrees: A double representing the shearing angle along the Y
1604 %      axis.
1605 %
1606 %    o width, height, x_offset, y_offset: Defines a region of the image
1607 %      to shear.
1608 %
1609 %    o exception: return any errors or warnings in this structure.
1610 %
1611 */
1612 static MagickBooleanType YShearImage(Image *image,const double degrees,
1613   const size_t width,const size_t height,const ssize_t x_offset,
1614   const ssize_t y_offset,ExceptionInfo *exception)
1615 {
1616 #define YShearImageTag  "YShear/Image"
1617
1618   typedef enum
1619   {
1620     UP,
1621     DOWN
1622   } ShearDirection;
1623
1624   CacheView
1625     *image_view;
1626
1627   MagickBooleanType
1628     status;
1629
1630   MagickOffsetType
1631     progress;
1632
1633   PixelInfo
1634     background;
1635
1636   ssize_t
1637     x;
1638
1639   /*
1640     Y Shear image.
1641   */
1642   assert(image != (Image *) NULL);
1643   assert(image->signature == MagickSignature);
1644   if (image->debug != MagickFalse)
1645     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1646   status=MagickTrue;
1647   progress=0;
1648   background=image->background_color;
1649   image_view=AcquireAuthenticCacheView(image,exception);
1650 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1651   #pragma omp parallel for schedule(static,4) shared(progress,status) \
1652     dynamic_number_threads(image,width,height,1)
1653 #endif
1654   for (x=0; x < (ssize_t) width; x++)
1655   {
1656     ssize_t
1657       step;
1658
1659     double
1660       area,
1661       displacement;
1662
1663     PixelInfo
1664       pixel,
1665       source,
1666       destination;
1667
1668     register Quantum
1669       *restrict p,
1670       *restrict q;
1671
1672     register ssize_t
1673       i;
1674
1675     ShearDirection
1676       direction;
1677
1678     if (status == MagickFalse)
1679       continue;
1680     p=GetCacheViewAuthenticPixels(image_view,x_offset+x,0,1,image->rows,
1681       exception);
1682     if (p == (Quantum *) NULL)
1683       {
1684         status=MagickFalse;
1685         continue;
1686       }
1687     p+=y_offset*GetPixelChannels(image);
1688     displacement=degrees*(double) (x-width/2.0);
1689     if (displacement == 0.0)
1690       continue;
1691     if (displacement > 0.0)
1692       direction=DOWN;
1693     else
1694       {
1695         displacement*=(-1.0);
1696         direction=UP;
1697       }
1698     step=(ssize_t) floor((double) displacement);
1699     area=(double) (displacement-step);
1700     step++;
1701     pixel=background;
1702     GetPixelInfo(image,&source);
1703     GetPixelInfo(image,&destination);
1704     switch (direction)
1705     {
1706       case UP:
1707       {
1708         /*
1709           Transfer pixels top-to-bottom.
1710         */
1711         if (step > y_offset)
1712           break;
1713         q=p-step*GetPixelChannels(image);
1714         for (i=0; i < (ssize_t) height; i++)
1715         {
1716           if ((y_offset+i) < step)
1717             {
1718               p+=GetPixelChannels(image);
1719               GetPixelInfoPixel(image,p,&pixel);
1720               q+=GetPixelChannels(image);
1721               continue;
1722             }
1723           GetPixelInfoPixel(image,p,&source);
1724           CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1725             &source,(double) GetPixelAlpha(image,p),area,
1726             &destination);
1727           SetPixelInfoPixel(image,&destination,q);
1728           GetPixelInfoPixel(image,p,&pixel);
1729           p+=GetPixelChannels(image);
1730           q+=GetPixelChannels(image);
1731         }
1732         CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1733           &background,(double) background.alpha,area,&destination);
1734         SetPixelInfoPixel(image,&destination,q);
1735         q+=GetPixelChannels(image);
1736         for (i=0; i < (step-1); i++)
1737         {
1738           SetPixelInfoPixel(image,&background,q);
1739           q+=GetPixelChannels(image);
1740         }
1741         break;
1742       }
1743       case DOWN:
1744       {
1745         /*
1746           Transfer pixels bottom-to-top.
1747         */
1748         p+=height*GetPixelChannels(image);
1749         q=p+step*GetPixelChannels(image);
1750         for (i=0; i < (ssize_t) height; i++)
1751         {
1752           p-=GetPixelChannels(image);
1753           q-=GetPixelChannels(image);
1754           if ((size_t) (y_offset+height+step-i) >= image->rows)
1755             continue;
1756           GetPixelInfoPixel(image,p,&source);
1757           CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1758             &source,(double) GetPixelAlpha(image,p),area,
1759             &destination);
1760           SetPixelInfoPixel(image,&destination,q);
1761           GetPixelInfoPixel(image,p,&pixel);
1762         }
1763         CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1764           &background,(double) background.alpha,area,&destination);
1765         q-=GetPixelChannels(image);
1766         SetPixelInfoPixel(image,&destination,q);
1767         for (i=0; i < (step-1); i++)
1768         {
1769           q-=GetPixelChannels(image);
1770           SetPixelInfoPixel(image,&background,q);
1771         }
1772         break;
1773       }
1774     }
1775     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1776       status=MagickFalse;
1777     if (image->progress_monitor != (MagickProgressMonitor) NULL)
1778       {
1779         MagickBooleanType
1780           proceed;
1781
1782 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1783         #pragma omp critical (MagickCore_YShearImage)
1784 #endif
1785         proceed=SetImageProgress(image,YShearImageTag,progress++,image->rows);
1786         if (proceed == MagickFalse)
1787           status=MagickFalse;
1788       }
1789   }
1790   image_view=DestroyCacheView(image_view);
1791   return(status);
1792 }
1793 \f
1794 /*
1795 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1796 %                                                                             %
1797 %                                                                             %
1798 %                                                                             %
1799 %   S h e a r I m a g e                                                       %
1800 %                                                                             %
1801 %                                                                             %
1802 %                                                                             %
1803 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1804 %
1805 %  ShearImage() creates a new image that is a shear_image copy of an existing
1806 %  one.  Shearing slides one edge of an image along the X or Y axis, creating
1807 %  a parallelogram.  An X direction shear slides an edge along the X axis,
1808 %  while a Y direction shear slides an edge along the Y axis.  The amount of
1809 %  the shear is controlled by a shear angle.  For X direction shears, x_shear
1810 %  is measured relative to the Y axis, and similarly, for Y direction shears
1811 %  y_shear is measured relative to the X axis.  Empty triangles left over from
1812 %  shearing the image are filled with the background color defined by member
1813 %  'background_color' of the image..  ShearImage() allocates the memory
1814 %  necessary for the new Image structure and returns a pointer to the new image.
1815 %
1816 %  ShearImage() is based on the paper "A Fast Algorithm for General Raster
1817 %  Rotatation" by Alan W. Paeth.
1818 %
1819 %  The format of the ShearImage method is:
1820 %
1821 %      Image *ShearImage(const Image *image,const double x_shear,
1822 %        const double y_shear,ExceptionInfo *exception)
1823 %
1824 %  A description of each parameter follows.
1825 %
1826 %    o image: the image.
1827 %
1828 %    o x_shear, y_shear: Specifies the number of degrees to shear the image.
1829 %
1830 %    o exception: return any errors or warnings in this structure.
1831 %
1832 */
1833 MagickExport Image *ShearImage(const Image *image,const double x_shear,
1834   const double y_shear,ExceptionInfo *exception)
1835 {
1836   Image
1837     *integral_image,
1838     *shear_image;
1839
1840   ssize_t
1841     x_offset,
1842     y_offset;
1843
1844   MagickBooleanType
1845     status;
1846
1847   PointInfo
1848     shear;
1849
1850   RectangleInfo
1851     border_info;
1852
1853   size_t
1854     y_width;
1855
1856   assert(image != (Image *) NULL);
1857   assert(image->signature == MagickSignature);
1858   if (image->debug != MagickFalse)
1859     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1860   assert(exception != (ExceptionInfo *) NULL);
1861   assert(exception->signature == MagickSignature);
1862   if ((x_shear != 0.0) && (fmod(x_shear,90.0) == 0.0))
1863     ThrowImageException(ImageError,"AngleIsDiscontinuous");
1864   if ((y_shear != 0.0) && (fmod(y_shear,90.0) == 0.0))
1865     ThrowImageException(ImageError,"AngleIsDiscontinuous");
1866   /*
1867     Initialize shear angle.
1868   */
1869   integral_image=CloneImage(image,0,0,MagickTrue,exception);
1870   if (integral_image == (Image *) NULL)
1871     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
1872   shear.x=(-tan(DegreesToRadians(fmod(x_shear,360.0))));
1873   shear.y=tan(DegreesToRadians(fmod(y_shear,360.0)));
1874   if ((shear.x == 0.0) && (shear.y == 0.0))
1875     return(integral_image);
1876   if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse)
1877     {
1878       integral_image=DestroyImage(integral_image);
1879       return(integral_image);
1880     }
1881   if (integral_image->alpha_trait != BlendPixelTrait)
1882     (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception);
1883   /*
1884     Compute image size.
1885   */
1886   y_width=image->columns+(ssize_t) floor(fabs(shear.x)*image->rows+0.5);
1887   x_offset=(ssize_t) ceil((double) image->columns+((fabs(shear.x)*image->rows)-
1888     image->columns)/2.0-0.5);
1889   y_offset=(ssize_t) ceil((double) image->rows+((fabs(shear.y)*y_width)-
1890     image->rows)/2.0-0.5);
1891   /*
1892     Surround image with border.
1893   */
1894   integral_image->border_color=integral_image->background_color;
1895   integral_image->compose=CopyCompositeOp;
1896   border_info.width=(size_t) x_offset;
1897   border_info.height=(size_t) y_offset;
1898   shear_image=BorderImage(integral_image,&border_info,image->compose,exception);
1899   integral_image=DestroyImage(integral_image);
1900   if (shear_image == (Image *) NULL)
1901     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
1902   /*
1903     Shear the image.
1904   */
1905   if (shear_image->alpha_trait != BlendPixelTrait)
1906     (void) SetImageAlphaChannel(shear_image,OpaqueAlphaChannel,exception);
1907   status=XShearImage(shear_image,shear.x,image->columns,image->rows,x_offset,
1908     (ssize_t) (shear_image->rows-image->rows)/2,exception);
1909   if (status == MagickFalse)
1910     {
1911       shear_image=DestroyImage(shear_image);
1912       return((Image *) NULL);
1913     }
1914   status=YShearImage(shear_image,shear.y,y_width,image->rows,(ssize_t)
1915     (shear_image->columns-y_width)/2,y_offset,exception);
1916   if (status == MagickFalse)
1917     {
1918       shear_image=DestroyImage(shear_image);
1919       return((Image *) NULL);
1920     }
1921   status=CropToFitImage(&shear_image,shear.x,shear.y,(double)
1922     image->columns,(double) image->rows,MagickFalse,exception);
1923   if (status == MagickFalse)
1924     {
1925       shear_image=DestroyImage(shear_image);
1926       return((Image *) NULL);
1927     }
1928   shear_image->compose=image->compose;
1929   shear_image->page.width=0;
1930   shear_image->page.height=0;
1931   return(shear_image);
1932 }
1933 \f
1934 /*
1935 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1936 %                                                                             %
1937 %                                                                             %
1938 %                                                                             %
1939 %   S h e a r R o t a t e I m a g e                                           %
1940 %                                                                             %
1941 %                                                                             %
1942 %                                                                             %
1943 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1944 %
1945 %  ShearRotateImage() creates a new image that is a rotated copy of an existing
1946 %  one.  Positive angles rotate counter-clockwise (right-hand rule), while
1947 %  negative angles rotate clockwise.  Rotated images are usually larger than
1948 %  the originals and have 'empty' triangular corners.  X axis.  Empty
1949 %  triangles left over from shearing the image are filled with the background
1950 %  color defined by member 'background_color' of the image.  ShearRotateImage
1951 %  allocates the memory necessary for the new Image structure and returns a
1952 %  pointer to the new image.
1953 %
1954 %  ShearRotateImage() is based on the paper "A Fast Algorithm for General
1955 %  Raster Rotatation" by Alan W. Paeth.  ShearRotateImage is adapted from a
1956 %  similar method based on the Paeth paper written by Michael Halle of the
1957 %  Spatial Imaging Group, MIT Media Lab.
1958 %
1959 %  The format of the ShearRotateImage method is:
1960 %
1961 %      Image *ShearRotateImage(const Image *image,const double degrees,
1962 %        ExceptionInfo *exception)
1963 %
1964 %  A description of each parameter follows.
1965 %
1966 %    o image: the image.
1967 %
1968 %    o degrees: Specifies the number of degrees to rotate the image.
1969 %
1970 %    o exception: return any errors or warnings in this structure.
1971 %
1972 */
1973 MagickExport Image *ShearRotateImage(const Image *image,const double degrees,
1974   ExceptionInfo *exception)
1975 {
1976   Image
1977     *integral_image,
1978     *rotate_image;
1979
1980   MagickBooleanType
1981     status;
1982
1983   double
1984     angle;
1985
1986   PointInfo
1987     shear;
1988
1989   RectangleInfo
1990     border_info;
1991
1992   size_t
1993     height,
1994     rotations,
1995     width,
1996     y_width;
1997
1998   ssize_t
1999     x_offset,
2000     y_offset;
2001
2002   /*
2003     Adjust rotation angle.
2004   */
2005   assert(image != (Image *) NULL);
2006   assert(image->signature == MagickSignature);
2007   if (image->debug != MagickFalse)
2008     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2009   assert(exception != (ExceptionInfo *) NULL);
2010   assert(exception->signature == MagickSignature);
2011   angle=degrees;
2012   while (angle < -45.0)
2013     angle+=360.0;
2014   for (rotations=0; angle > 45.0; rotations++)
2015     angle-=90.0;
2016   rotations%=4;
2017   /*
2018     Calculate shear equations.
2019   */
2020   integral_image=IntegralRotateImage(image,rotations,exception);
2021   if (integral_image == (Image *) NULL)
2022     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
2023   shear.x=(-tan((double) DegreesToRadians(angle)/2.0));
2024   shear.y=sin((double) DegreesToRadians(angle));
2025   if ((shear.x == 0.0) && (shear.y == 0.0))
2026     return(integral_image);
2027   if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse)
2028     {
2029       integral_image=DestroyImage(integral_image);
2030       return(integral_image);
2031     }
2032   if (integral_image->alpha_trait != BlendPixelTrait)
2033     (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception);
2034   /*
2035     Compute image size.
2036   */
2037   width=image->columns;
2038   height=image->rows;
2039   if ((rotations == 1) || (rotations == 3))
2040     {
2041       width=image->rows;
2042       height=image->columns;
2043     }
2044   y_width=width+(ssize_t) floor(fabs(shear.x)*height+0.5);
2045   x_offset=(ssize_t) ceil((double) width+((fabs(shear.y)*height)-width)/2.0-
2046     0.5);
2047   y_offset=(ssize_t) ceil((double) height+((fabs(shear.y)*y_width)-height)/2.0-
2048     0.5);
2049   /*
2050     Surround image with a border.
2051   */
2052   integral_image->border_color=integral_image->background_color;
2053   integral_image->compose=CopyCompositeOp;
2054   border_info.width=(size_t) x_offset;
2055   border_info.height=(size_t) y_offset;
2056   rotate_image=BorderImage(integral_image,&border_info,image->compose,
2057     exception);
2058   integral_image=DestroyImage(integral_image);
2059   if (rotate_image == (Image *) NULL)
2060     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
2061   /*
2062     Rotate the image.
2063   */
2064   status=XShearImage(rotate_image,shear.x,width,height,x_offset,(ssize_t)
2065     (rotate_image->rows-height)/2,exception);
2066   if (status == MagickFalse)
2067     {
2068       rotate_image=DestroyImage(rotate_image);
2069       return((Image *) NULL);
2070     }
2071   status=YShearImage(rotate_image,shear.y,y_width,height,(ssize_t)
2072     (rotate_image->columns-y_width)/2,y_offset,exception);
2073   if (status == MagickFalse)
2074     {
2075       rotate_image=DestroyImage(rotate_image);
2076       return((Image *) NULL);
2077     }
2078   status=XShearImage(rotate_image,shear.x,y_width,rotate_image->rows,(ssize_t)
2079     (rotate_image->columns-y_width)/2,0,exception);
2080   if (status == MagickFalse)
2081     {
2082       rotate_image=DestroyImage(rotate_image);
2083       return((Image *) NULL);
2084     }
2085   status=CropToFitImage(&rotate_image,shear.x,shear.y,(double) width,
2086     (double) height,MagickTrue,exception);
2087   if (status == MagickFalse)
2088     {
2089       rotate_image=DestroyImage(rotate_image);
2090       return((Image *) NULL);
2091     }
2092   rotate_image->compose=image->compose;
2093   rotate_image->page.width=0;
2094   rotate_image->page.height=0;
2095   return(rotate_image);
2096 }