]> 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 MagickRealType x_shear,const MagickRealType x_shear,
99 %        const MagickRealType width,const MagickRealType 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 MagickRealType x_shear,const MagickRealType y_shear,
113   const MagickRealType width,const MagickRealType 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(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 #endif
577   for (x=0; x < (ssize_t) p->width; x++)
578   {
579     register ssize_t
580       y;
581
582     size_t
583       sum;
584
585     sum=0;
586     for (y=0; y < (ssize_t) (p->height-1); y++)
587     {
588       ssize_t
589         delta;
590
591       delta=GetRadonCell(p,x,y)-(ssize_t) GetRadonCell(p,x,y+1);
592       sum+=delta*delta;
593     }
594     projection[p->width+sign*x-1]=sum;
595   }
596 }
597
598 static MagickBooleanType RadonTransform(const Image *image,
599   const double threshold,size_t *projection,ExceptionInfo *exception)
600 {
601   CacheView
602     *image_view;
603
604   MagickBooleanType
605     status;
606
607   RadonInfo
608     *destination_cells,
609     *source_cells;
610
611   register ssize_t
612     i;
613
614   size_t
615     count,
616     width;
617
618   ssize_t
619     y;
620
621   unsigned char
622     byte;
623
624   unsigned short
625     bits[256];
626
627   for (width=1; width < ((image->columns+7)/8); width<<=1) ;
628   source_cells=AcquireRadonInfo(image,width,image->rows,exception);
629   destination_cells=AcquireRadonInfo(image,width,image->rows,exception);
630   if ((source_cells == (RadonInfo *) NULL) ||
631       (destination_cells == (RadonInfo *) NULL))
632     {
633       if (destination_cells != (RadonInfo *) NULL)
634         destination_cells=DestroyRadonInfo(destination_cells);
635       if (source_cells != (RadonInfo *) NULL)
636         source_cells=DestroyRadonInfo(source_cells);
637       return(MagickFalse);
638     }
639   if (ResetRadonCells(source_cells) == MagickFalse)
640     {
641       destination_cells=DestroyRadonInfo(destination_cells);
642       source_cells=DestroyRadonInfo(source_cells);
643       return(MagickFalse);
644     }
645   for (i=0; i < 256; i++)
646   {
647     byte=(unsigned char) i;
648     for (count=0; byte != 0; byte>>=1)
649       count+=byte & 0x01;
650     bits[i]=(unsigned short) count;
651   }
652   status=MagickTrue;
653   image_view=AcquireCacheView(image);
654 #if defined(MAGICKCORE_OPENMP_SUPPORT)
655   #pragma omp parallel for schedule(static,4) shared(status)
656 #endif
657   for (y=0; y < (ssize_t) image->rows; y++)
658   {
659     register const Quantum
660       *restrict p;
661
662     register ssize_t
663       i,
664       x;
665
666     size_t
667       bit,
668       byte;
669
670     if (status == MagickFalse)
671       continue;
672     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
673     if (p == (const Quantum *) NULL)
674       {
675         status=MagickFalse;
676         continue;
677       }
678     bit=0;
679     byte=0;
680     i=(ssize_t) (image->columns+7)/8;
681     for (x=0; x < (ssize_t) image->columns; x++)
682     {
683       byte<<=1;
684       if ((double) GetPixelIntensity(image,p) < threshold)
685         byte|=0x01;
686       bit++;
687       if (bit == 8)
688         {
689           (void) SetRadonCell(source_cells,--i,y,bits[byte]);
690           bit=0;
691           byte=0;
692         }
693       p+=GetPixelChannels(image);
694     }
695     if (bit != 0)
696       {
697         byte<<=(8-bit);
698         (void) SetRadonCell(source_cells,--i,y,bits[byte]);
699       }
700   }
701   RadonProjection(source_cells,destination_cells,-1,projection);
702   (void) ResetRadonCells(source_cells);
703 #if defined(MAGICKCORE_OPENMP_SUPPORT)
704   #pragma omp parallel for schedule(static,4) shared(status)
705 #endif
706   for (y=0; y < (ssize_t) image->rows; y++)
707   {
708     register const Quantum
709       *restrict p;
710
711     register ssize_t
712       i,
713       x;
714
715     size_t
716       bit,
717       byte;
718
719     if (status == MagickFalse)
720       continue;
721     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
722     if (p == (const Quantum *) NULL)
723       {
724         status=MagickFalse;
725         continue;
726       }
727     bit=0;
728     byte=0;
729     i=0;
730     for (x=0; x < (ssize_t) image->columns; x++)
731     {
732       byte<<=1;
733       if ((double) GetPixelIntensity(image,p) < threshold)
734         byte|=0x01;
735       bit++;
736       if (bit == 8)
737         {
738           (void) SetRadonCell(source_cells,i++,y,bits[byte]);
739           bit=0;
740           byte=0;
741         }
742       p+=GetPixelChannels(image);
743     }
744     if (bit != 0)
745       {
746         byte<<=(8-bit);
747         (void) SetRadonCell(source_cells,i++,y,bits[byte]);
748       }
749   }
750   RadonProjection(source_cells,destination_cells,1,projection);
751   image_view=DestroyCacheView(image_view);
752   destination_cells=DestroyRadonInfo(destination_cells);
753   source_cells=DestroyRadonInfo(source_cells);
754   return(MagickTrue);
755 }
756
757 static void GetImageBackgroundColor(Image *image,const ssize_t offset,
758   ExceptionInfo *exception)
759 {
760   CacheView
761     *image_view;
762
763   PixelInfo
764     background;
765
766   MagickRealType
767     count;
768
769   ssize_t
770     y;
771
772   /*
773     Compute average background color.
774   */
775   if (offset <= 0)
776     return;
777   GetPixelInfo(image,&background);
778   count=0.0;
779   image_view=AcquireCacheView(image);
780   for (y=0; y < (ssize_t) image->rows; y++)
781   {
782     register const Quantum
783       *restrict p;
784
785     register ssize_t
786       x;
787
788     if ((y >= offset) && (y < ((ssize_t) image->rows-offset)))
789       continue;
790     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
791     if (p == (const Quantum *) NULL)
792       continue;
793     for (x=0; x < (ssize_t) image->columns; x++)
794     {
795       if ((x >= offset) && (x < ((ssize_t) image->columns-offset)))
796         continue;
797       background.red+=QuantumScale*GetPixelRed(image,p);
798       background.green+=QuantumScale*GetPixelGreen(image,p);
799       background.blue+=QuantumScale*GetPixelBlue(image,p);
800       if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
801         background.alpha+=QuantumScale*GetPixelAlpha(image,p);
802       count++;
803       p+=GetPixelChannels(image);
804     }
805   }
806   image_view=DestroyCacheView(image_view);
807   image->background_color.red=(double) ClampToQuantum((MagickRealType)
808     QuantumRange*background.red/count);
809   image->background_color.green=(double) ClampToQuantum((MagickRealType)
810     QuantumRange*background.green/count);
811   image->background_color.blue=(double) ClampToQuantum((MagickRealType)
812     QuantumRange*background.blue/count);
813   if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
814     image->background_color.alpha=(double) ClampToQuantum((MagickRealType)
815       QuantumRange*background.alpha/count);
816 }
817
818 MagickExport Image *DeskewImage(const Image *image,const double threshold,
819   ExceptionInfo *exception)
820 {
821   AffineMatrix
822     affine_matrix;
823
824   const char
825     *artifact;
826
827   double
828     degrees;
829
830   Image
831     *clone_image,
832     *crop_image,
833     *deskew_image,
834     *median_image;
835
836   MagickBooleanType
837     status;
838
839   RectangleInfo
840     geometry;
841
842   register ssize_t
843     i;
844
845   size_t
846     max_projection,
847     *projection,
848     width;
849
850   ssize_t
851     skew;
852
853   /*
854     Compute deskew angle.
855   */
856   for (width=1; width < ((image->columns+7)/8); width<<=1) ;
857   projection=(size_t *) AcquireQuantumMemory((size_t) (2*width-1),
858     sizeof(*projection));
859   if (projection == (size_t *) NULL)
860     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
861   status=RadonTransform(image,threshold,projection,exception);
862   if (status == MagickFalse)
863     {
864       projection=(size_t *) RelinquishMagickMemory(projection);
865       ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
866     }
867   max_projection=0;
868   skew=0;
869   for (i=0; i < (ssize_t) (2*width-1); i++)
870   {
871     if (projection[i] > max_projection)
872       {
873         skew=i-(ssize_t) width+1;
874         max_projection=projection[i];
875       }
876   }
877   projection=(size_t *) RelinquishMagickMemory(projection);
878   /*
879     Deskew image.
880   */
881   clone_image=CloneImage(image,0,0,MagickTrue,exception);
882   if (clone_image == (Image *) NULL)
883     return((Image *) NULL);
884   (void) SetImageVirtualPixelMethod(clone_image,BackgroundVirtualPixelMethod);
885   degrees=RadiansToDegrees(-atan((double) skew/width/8));
886   if (image->debug != MagickFalse)
887     (void) LogMagickEvent(TransformEvent,GetMagickModule(),
888       "  Deskew angle: %g",degrees);
889   affine_matrix.sx=cos(DegreesToRadians(fmod((double) degrees,360.0)));
890   affine_matrix.rx=sin(DegreesToRadians(fmod((double) degrees,360.0)));
891   affine_matrix.ry=(-sin(DegreesToRadians(fmod((double) degrees,360.0))));
892   affine_matrix.sy=cos(DegreesToRadians(fmod((double) degrees,360.0)));
893   affine_matrix.tx=0.0;
894   affine_matrix.ty=0.0;
895   artifact=GetImageArtifact(image,"deskew:auto-crop");
896   if (artifact == (const char *) NULL)
897     {
898       deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception);
899       clone_image=DestroyImage(clone_image);
900       return(deskew_image);
901     }
902   /*
903     Auto-crop image.
904   */
905   GetImageBackgroundColor(clone_image,(ssize_t) StringToLong(artifact),
906     exception);
907   deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception);
908   clone_image=DestroyImage(clone_image);
909   if (deskew_image == (Image *) NULL)
910     return((Image *) NULL);
911   median_image=StatisticImage(deskew_image,MedianStatistic,3,3,exception);
912   if (median_image == (Image *) NULL)
913     {
914       deskew_image=DestroyImage(deskew_image);
915       return((Image *) NULL);
916     }
917   geometry=GetImageBoundingBox(median_image,exception);
918   median_image=DestroyImage(median_image);
919   if (image->debug != MagickFalse)
920     (void) LogMagickEvent(TransformEvent,GetMagickModule(),"  Deskew geometry: "
921       "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double)
922       geometry.height,(double) geometry.x,(double) geometry.y);
923   crop_image=CropImage(deskew_image,&geometry,exception);
924   deskew_image=DestroyImage(deskew_image);
925   return(crop_image);
926 }
927 \f
928 /*
929 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
930 %                                                                             %
931 %                                                                             %
932 %                                                                             %
933 %   I n t e g r a l R o t a t e I m a g e                                     %
934 %                                                                             %
935 %                                                                             %
936 %                                                                             %
937 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
938 %
939 %  IntegralRotateImage() rotates the image an integral of 90 degrees.  It
940 %  allocates the memory necessary for the new Image structure and returns a
941 %  pointer to the rotated image.
942 %
943 %  The format of the IntegralRotateImage method is:
944 %
945 %      Image *IntegralRotateImage(const Image *image,size_t rotations,
946 %        ExceptionInfo *exception)
947 %
948 %  A description of each parameter follows.
949 %
950 %    o image: the image.
951 %
952 %    o rotations: Specifies the number of 90 degree rotations.
953 %
954 */
955 MagickExport Image *IntegralRotateImage(const Image *image,size_t rotations,
956   ExceptionInfo *exception)
957 {
958 #define RotateImageTag  "Rotate/Image"
959
960   CacheView
961     *image_view,
962     *rotate_view;
963
964   Image
965     *rotate_image;
966
967   MagickBooleanType
968     status;
969
970   MagickOffsetType
971     progress;
972
973   RectangleInfo
974     page;
975
976   ssize_t
977     y;
978
979   /*
980     Initialize rotated image attributes.
981   */
982   assert(image != (Image *) NULL);
983   page=image->page;
984   rotations%=4;
985   if (rotations == 0)
986     return(CloneImage(image,0,0,MagickTrue,exception));
987   if ((rotations == 1) || (rotations == 3))
988     rotate_image=CloneImage(image,image->rows,image->columns,MagickTrue,
989       exception);
990   else
991     rotate_image=CloneImage(image,image->columns,image->rows,MagickTrue,
992       exception);
993   if (rotate_image == (Image *) NULL)
994     return((Image *) NULL);
995   /*
996     Integral rotate the image.
997   */
998   status=MagickTrue;
999   progress=0;
1000   image_view=AcquireCacheView(image);
1001   rotate_view=AcquireCacheView(rotate_image);
1002   switch (rotations)
1003   {
1004     case 0:
1005     {
1006       /*
1007         Rotate 0 degrees.
1008       */
1009       break;
1010     }
1011     case 1:
1012     {
1013       size_t
1014         tile_height,
1015         tile_width;
1016
1017       ssize_t
1018         tile_y;
1019
1020       /*
1021         Rotate 90 degrees.
1022       */
1023       GetPixelCacheTileSize(image,&tile_width,&tile_height);
1024 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1025       #pragma omp parallel for schedule(static,1) shared(progress,status)
1026 #endif
1027       for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height)
1028       {
1029         register ssize_t
1030           tile_x;
1031
1032         if (status == MagickFalse)
1033           continue;
1034         tile_x=0;
1035         for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width)
1036         {
1037           MagickBooleanType
1038             sync;
1039
1040           register const Quantum
1041             *restrict p;
1042
1043           register Quantum
1044             *restrict q;
1045
1046           register ssize_t
1047             y;
1048
1049           size_t
1050             height,
1051             width;
1052
1053           width=tile_width;
1054           if ((tile_x+(ssize_t) tile_width) > (ssize_t) image->columns)
1055             width=(size_t) (tile_width-(tile_x+tile_width-image->columns));
1056           height=tile_height;
1057           if ((tile_y+(ssize_t) tile_height) > (ssize_t) image->rows)
1058             height=(size_t) (tile_height-(tile_y+tile_height-image->rows));
1059           p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height,
1060             exception);
1061           if (p == (const Quantum *) NULL)
1062             {
1063               status=MagickFalse;
1064               break;
1065             }
1066           for (y=0; y < (ssize_t) width; y++)
1067           {
1068             register const Quantum
1069               *restrict tile_pixels;
1070
1071             register ssize_t
1072               x;
1073
1074             if (status == MagickFalse)
1075               continue;
1076             q=QueueCacheViewAuthenticPixels(rotate_view,(ssize_t)
1077               (rotate_image->columns-(tile_y+height)),y+tile_x,height,1,
1078               exception);
1079             if (q == (Quantum *) NULL)
1080               {
1081                 status=MagickFalse;
1082                 continue;
1083               }
1084             tile_pixels=p+((height-1)*width+y)*GetPixelChannels(image);
1085             for (x=0; x < (ssize_t) height; x++)
1086             {
1087               register ssize_t
1088                 i;
1089
1090               for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1091               {
1092                 PixelChannel
1093                   channel;
1094
1095                 PixelTrait
1096                   rotate_traits,
1097                   traits;
1098
1099                 channel=GetPixelChannelMapChannel(image,i);
1100                 traits=GetPixelChannelMapTraits(image,channel);
1101                 rotate_traits=GetPixelChannelMapTraits(rotate_image,channel);
1102                 if ((traits == UndefinedPixelTrait) ||
1103                     (rotate_traits == UndefinedPixelTrait))
1104                   continue;
1105                 SetPixelChannel(rotate_image,channel,tile_pixels[i],q);
1106               }
1107               tile_pixels-=width*GetPixelChannels(image);
1108               q+=GetPixelChannels(rotate_image);
1109             }
1110             sync=SyncCacheViewAuthenticPixels(rotate_view,exception);
1111             if (sync == MagickFalse)
1112               status=MagickFalse;
1113           }
1114         }
1115         if (image->progress_monitor != (MagickProgressMonitor) NULL)
1116           {
1117             MagickBooleanType
1118               proceed;
1119
1120 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1121             #pragma omp critical (MagickCore_IntegralRotateImage)
1122 #endif
1123             proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height,
1124               image->rows);
1125             if (proceed == MagickFalse)
1126               status=MagickFalse;
1127           }
1128       }
1129       (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType)
1130         image->rows-1,image->rows);
1131       Swap(page.width,page.height);
1132       Swap(page.x,page.y);
1133       if (page.width != 0)
1134         page.x=(ssize_t) (page.width-rotate_image->columns-page.x);
1135       break;
1136     }
1137     case 2:
1138     {
1139       /*
1140         Rotate 180 degrees.
1141       */
1142 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1143       #pragma omp parallel for schedule(static,1) shared(progress,status)
1144 #endif
1145       for (y=0; y < (ssize_t) image->rows; y++)
1146       {
1147         MagickBooleanType
1148           sync;
1149
1150         register const Quantum
1151           *restrict p;
1152
1153         register Quantum
1154           *restrict q;
1155
1156         register ssize_t
1157           x;
1158
1159         if (status == MagickFalse)
1160           continue;
1161         p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
1162         q=QueueCacheViewAuthenticPixels(rotate_view,0,(ssize_t) (image->rows-y-
1163           1),image->columns,1,exception);
1164         if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
1165           {
1166             status=MagickFalse;
1167             continue;
1168           }
1169         q+=GetPixelChannels(rotate_image)*image->columns;
1170         for (x=0; x < (ssize_t) image->columns; x++)
1171         {
1172           register ssize_t
1173             i;
1174
1175           q-=GetPixelChannels(rotate_image);
1176           for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1177           {
1178             PixelChannel
1179               channel;
1180
1181             PixelTrait
1182               rotate_traits,
1183               traits;
1184
1185             channel=GetPixelChannelMapChannel(image,i);
1186             traits=GetPixelChannelMapTraits(image,channel);
1187             rotate_traits=GetPixelChannelMapTraits(rotate_image,channel);
1188             if ((traits == UndefinedPixelTrait) ||
1189                 (rotate_traits == UndefinedPixelTrait))
1190               continue;
1191             SetPixelChannel(rotate_image,channel,p[i],q);
1192           }
1193           p+=GetPixelChannels(image);
1194         }
1195         sync=SyncCacheViewAuthenticPixels(rotate_view,exception);
1196         if (sync == MagickFalse)
1197           status=MagickFalse;
1198         if (image->progress_monitor != (MagickProgressMonitor) NULL)
1199           {
1200             MagickBooleanType
1201               proceed;
1202
1203 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1204             #pragma omp critical (MagickCore_IntegralRotateImage)
1205 #endif
1206             proceed=SetImageProgress(image,RotateImageTag,progress++,
1207               image->rows);
1208             if (proceed == MagickFalse)
1209               status=MagickFalse;
1210           }
1211       }
1212       (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType)
1213         image->rows-1,image->rows);
1214       Swap(page.width,page.height);
1215       Swap(page.x,page.y);
1216       if (page.width != 0)
1217         page.x=(ssize_t) (page.width-rotate_image->columns-page.x);
1218       break;
1219     }
1220     case 3:
1221     {
1222       size_t
1223         tile_height,
1224         tile_width;
1225
1226       ssize_t
1227         tile_y;
1228
1229       /*
1230         Rotate 270 degrees.
1231       */
1232       GetPixelCacheTileSize(image,&tile_width,&tile_height);
1233       tile_width=image->columns;
1234 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1235       #pragma omp parallel for schedule(static,1) shared(progress,status)
1236 #endif
1237       for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height)
1238       {
1239         register ssize_t
1240           tile_x;
1241
1242         if (status == MagickFalse)
1243           continue;
1244         tile_x=0;
1245         for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width)
1246         {
1247           MagickBooleanType
1248             sync;
1249
1250           register const Quantum
1251             *restrict p;
1252
1253           register Quantum
1254             *restrict q;
1255
1256           register ssize_t
1257             y;
1258
1259           size_t
1260             height,
1261             width;
1262
1263           width=tile_width;
1264           if ((tile_x+(ssize_t) tile_width) > (ssize_t) image->columns)
1265             width=(size_t) (tile_width-(tile_x+tile_width-image->columns));
1266           height=tile_height;
1267           if ((tile_y+(ssize_t) tile_height) > (ssize_t) image->rows)
1268             height=(size_t) (tile_height-(tile_y+tile_height-image->rows));
1269           p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height,
1270             exception);
1271           if (p == (const Quantum *) NULL)
1272             {
1273               status=MagickFalse;
1274               break;
1275             }
1276           for (y=0; y < (ssize_t) width; y++)
1277           {
1278             register const Quantum
1279               *restrict tile_pixels;
1280
1281             register ssize_t
1282               x;
1283
1284             if (status == MagickFalse)
1285               continue;
1286             q=QueueCacheViewAuthenticPixels(rotate_view,tile_y,(ssize_t) (y+
1287               rotate_image->rows-(tile_x+width)),height,1,exception);
1288             if (q == (Quantum *) NULL)
1289               {
1290                 status=MagickFalse;
1291                 continue;
1292               }
1293             tile_pixels=p+((width-1)-y)*GetPixelChannels(image);
1294             for (x=0; x < (ssize_t) height; x++)
1295             {
1296               register ssize_t
1297                 i;
1298
1299               for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1300               {
1301                 PixelChannel
1302                   channel;
1303
1304                 PixelTrait
1305                   rotate_traits,
1306                   traits;
1307
1308                 channel=GetPixelChannelMapChannel(image,i);
1309                 traits=GetPixelChannelMapTraits(image,channel);
1310                 rotate_traits=GetPixelChannelMapTraits(rotate_image,channel);
1311                 if ((traits == UndefinedPixelTrait) ||
1312                     (rotate_traits == UndefinedPixelTrait))
1313                   continue;
1314                 SetPixelChannel(rotate_image,channel,tile_pixels[i],q);
1315               }
1316               tile_pixels+=width*GetPixelChannels(image);
1317               q+=GetPixelChannels(rotate_image);
1318             }
1319             sync=SyncCacheViewAuthenticPixels(rotate_view,exception);
1320             if (sync == MagickFalse)
1321               status=MagickFalse;
1322           }
1323         }
1324         if (image->progress_monitor != (MagickProgressMonitor) NULL)
1325           {
1326             MagickBooleanType
1327               proceed;
1328
1329 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1330             #pragma omp critical (MagickCore_IntegralRotateImage)
1331 #endif
1332             proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height,
1333               image->rows);
1334             if (proceed == MagickFalse)
1335               status=MagickFalse;
1336           }
1337       }
1338       (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType)
1339         image->rows-1,image->rows);
1340       Swap(page.width,page.height);
1341       Swap(page.x,page.y);
1342       if (page.width != 0)
1343         page.x=(ssize_t) (page.width-rotate_image->columns-page.x);
1344       break;
1345     }
1346   }
1347   rotate_view=DestroyCacheView(rotate_view);
1348   image_view=DestroyCacheView(image_view);
1349   rotate_image->type=image->type;
1350   rotate_image->page=page;
1351   if (status == MagickFalse)
1352     rotate_image=DestroyImage(rotate_image);
1353   return(rotate_image);
1354 }
1355 \f
1356 /*
1357 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1358 %                                                                             %
1359 %                                                                             %
1360 %                                                                             %
1361 +   X S h e a r I m a g e                                                     %
1362 %                                                                             %
1363 %                                                                             %
1364 %                                                                             %
1365 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1366 %
1367 %  XShearImage() shears the image in the X direction with a shear angle of
1368 %  'degrees'.  Positive angles shear counter-clockwise (right-hand rule), and
1369 %  negative angles shear clockwise.  Angles are measured relative to a vertical
1370 %  Y-axis.  X shears will widen an image creating 'empty' triangles on the left
1371 %  and right sides of the source image.
1372 %
1373 %  The format of the XShearImage method is:
1374 %
1375 %      MagickBooleanType XShearImage(Image *image,const MagickRealType degrees,
1376 %        const size_t width,const size_t height,
1377 %        const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception)
1378 %
1379 %  A description of each parameter follows.
1380 %
1381 %    o image: the image.
1382 %
1383 %    o degrees: A MagickRealType representing the shearing angle along the X
1384 %      axis.
1385 %
1386 %    o width, height, x_offset, y_offset: Defines a region of the image
1387 %      to shear.
1388 %
1389 %    o exception: return any errors or warnings in this structure.
1390 %
1391 */
1392 static MagickBooleanType XShearImage(Image *image,const MagickRealType degrees,
1393   const size_t width,const size_t height,const ssize_t x_offset,
1394   const ssize_t y_offset,ExceptionInfo *exception)
1395 {
1396 #define XShearImageTag  "XShear/Image"
1397
1398   typedef enum
1399   {
1400     LEFT,
1401     RIGHT
1402   } ShearDirection;
1403
1404   CacheView
1405     *image_view;
1406
1407   MagickBooleanType
1408     status;
1409
1410   MagickOffsetType
1411     progress;
1412
1413   PixelInfo
1414     background;
1415
1416   ssize_t
1417     y;
1418
1419   /*
1420     X shear image.
1421   */
1422   assert(image != (Image *) NULL);
1423   assert(image->signature == MagickSignature);
1424   if (image->debug != MagickFalse)
1425     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1426   status=MagickTrue;
1427   background=image->background_color;
1428   progress=0;
1429   image_view=AcquireCacheView(image);
1430 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1431   #pragma omp parallel for schedule(static,4) shared(progress,status)
1432 #endif
1433   for (y=0; y < (ssize_t) height; y++)
1434   {
1435     PixelInfo
1436       pixel,
1437       source,
1438       destination;
1439
1440     MagickRealType
1441       area,
1442       displacement;
1443
1444     register Quantum
1445       *restrict p,
1446       *restrict q;
1447
1448     register ssize_t
1449       i;
1450
1451     ShearDirection
1452       direction;
1453
1454     ssize_t
1455       step;
1456
1457     if (status == MagickFalse)
1458       continue;
1459     p=GetCacheViewAuthenticPixels(image_view,0,y_offset+y,image->columns,1,
1460       exception);
1461     if (p == (Quantum *) NULL)
1462       {
1463         status=MagickFalse;
1464         continue;
1465       }
1466     p+=x_offset*GetPixelChannels(image);
1467     displacement=degrees*(MagickRealType) (y-height/2.0);
1468     if (displacement == 0.0)
1469       continue;
1470     if (displacement > 0.0)
1471       direction=RIGHT;
1472     else
1473       {
1474         displacement*=(-1.0);
1475         direction=LEFT;
1476       }
1477     step=(ssize_t) floor((double) displacement);
1478     area=(MagickRealType) (displacement-step);
1479     step++;
1480     pixel=background;
1481     GetPixelInfo(image,&source);
1482     GetPixelInfo(image,&destination);
1483     switch (direction)
1484     {
1485       case LEFT:
1486       {
1487         /*
1488           Transfer pixels left-to-right.
1489         */
1490         if (step > x_offset)
1491           break;
1492         q=p-step*GetPixelChannels(image);
1493         for (i=0; i < (ssize_t) width; i++)
1494         {
1495           if ((x_offset+i) < step)
1496             {
1497               p+=GetPixelChannels(image);
1498               GetPixelInfoPixel(image,p,&pixel);
1499               q+=GetPixelChannels(image);
1500               continue;
1501             }
1502           GetPixelInfoPixel(image,p,&source);
1503           CompositePixelInfoAreaBlend(&pixel,(MagickRealType) pixel.alpha,
1504             &source,(MagickRealType) GetPixelAlpha(image,p),area,&destination);
1505           SetPixelInfoPixel(image,&destination,q);
1506           GetPixelInfoPixel(image,p,&pixel);
1507           p+=GetPixelChannels(image);
1508           q+=GetPixelChannels(image);
1509         }
1510         CompositePixelInfoAreaBlend(&pixel,(MagickRealType) pixel.alpha,
1511           &background,(MagickRealType) background.alpha,area,&destination);
1512         SetPixelInfoPixel(image,&destination,q);
1513         q+=GetPixelChannels(image);
1514         for (i=0; i < (step-1); i++)
1515         {
1516           SetPixelInfoPixel(image,&background,q);
1517           q+=GetPixelChannels(image);
1518         }
1519         break;
1520       }
1521       case RIGHT:
1522       {
1523         /*
1524           Transfer pixels right-to-left.
1525         */
1526         p+=width*GetPixelChannels(image);
1527         q=p+step*GetPixelChannels(image);
1528         for (i=0; i < (ssize_t) width; i++)
1529         {
1530           p-=GetPixelChannels(image);
1531           q-=GetPixelChannels(image);
1532           if ((size_t) (x_offset+width+step-i) >= image->columns)
1533             continue;
1534           GetPixelInfoPixel(image,p,&source);
1535           CompositePixelInfoAreaBlend(&pixel,(MagickRealType) pixel.alpha,
1536             &source,(MagickRealType) GetPixelAlpha(image,p),area,&destination);
1537           SetPixelInfoPixel(image,&destination,q);
1538           GetPixelInfoPixel(image,p,&pixel);
1539         }
1540         CompositePixelInfoAreaBlend(&pixel,(MagickRealType) pixel.alpha,
1541           &background,(MagickRealType) background.alpha,area,&destination);
1542         q-=GetPixelChannels(image);
1543         SetPixelInfoPixel(image,&destination,q);
1544         for (i=0; i < (step-1); i++)
1545         {
1546           q-=GetPixelChannels(image);
1547           SetPixelInfoPixel(image,&background,q);
1548         }
1549         break;
1550       }
1551     }
1552     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1553       status=MagickFalse;
1554     if (image->progress_monitor != (MagickProgressMonitor) NULL)
1555       {
1556         MagickBooleanType
1557           proceed;
1558
1559 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1560         #pragma omp critical (MagickCore_XShearImage)
1561 #endif
1562         proceed=SetImageProgress(image,XShearImageTag,progress++,height);
1563         if (proceed == MagickFalse)
1564           status=MagickFalse;
1565       }
1566   }
1567   image_view=DestroyCacheView(image_view);
1568   return(status);
1569 }
1570 \f
1571 /*
1572 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1573 %                                                                             %
1574 %                                                                             %
1575 %                                                                             %
1576 +   Y S h e a r I m a g e                                                     %
1577 %                                                                             %
1578 %                                                                             %
1579 %                                                                             %
1580 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1581 %
1582 %  YShearImage shears the image in the Y direction with a shear angle of
1583 %  'degrees'.  Positive angles shear counter-clockwise (right-hand rule), and
1584 %  negative angles shear clockwise.  Angles are measured relative to a
1585 %  horizontal X-axis.  Y shears will increase the height of an image creating
1586 %  'empty' triangles on the top and bottom of the source image.
1587 %
1588 %  The format of the YShearImage method is:
1589 %
1590 %      MagickBooleanType YShearImage(Image *image,const MagickRealType degrees,
1591 %        const size_t width,const size_t height,
1592 %        const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception)
1593 %
1594 %  A description of each parameter follows.
1595 %
1596 %    o image: the image.
1597 %
1598 %    o degrees: A MagickRealType representing the shearing angle along the Y
1599 %      axis.
1600 %
1601 %    o width, height, x_offset, y_offset: Defines a region of the image
1602 %      to shear.
1603 %
1604 %    o exception: return any errors or warnings in this structure.
1605 %
1606 */
1607 static MagickBooleanType YShearImage(Image *image,const MagickRealType degrees,
1608   const size_t width,const size_t height,const ssize_t x_offset,
1609   const ssize_t y_offset,ExceptionInfo *exception)
1610 {
1611 #define YShearImageTag  "YShear/Image"
1612
1613   typedef enum
1614   {
1615     UP,
1616     DOWN
1617   } ShearDirection;
1618
1619   CacheView
1620     *image_view;
1621
1622   MagickBooleanType
1623     status;
1624
1625   MagickOffsetType
1626     progress;
1627
1628   PixelInfo
1629     background;
1630
1631   ssize_t
1632     x;
1633
1634   /*
1635     Y Shear image.
1636   */
1637   assert(image != (Image *) NULL);
1638   assert(image->signature == MagickSignature);
1639   if (image->debug != MagickFalse)
1640     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1641   status=MagickTrue;
1642   progress=0;
1643   background=image->background_color;
1644   image_view=AcquireCacheView(image);
1645 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1646   #pragma omp parallel for schedule(static,4) shared(progress,status)
1647 #endif
1648   for (x=0; x < (ssize_t) width; x++)
1649   {
1650     ssize_t
1651       step;
1652
1653     MagickRealType
1654       area,
1655       displacement;
1656
1657     PixelInfo
1658       pixel,
1659       source,
1660       destination;
1661
1662     register Quantum
1663       *restrict p,
1664       *restrict q;
1665
1666     register ssize_t
1667       i;
1668
1669     ShearDirection
1670       direction;
1671
1672     if (status == MagickFalse)
1673       continue;
1674     p=GetCacheViewAuthenticPixels(image_view,x_offset+x,0,1,image->rows,
1675       exception);
1676     if (p == (Quantum *) NULL)
1677       {
1678         status=MagickFalse;
1679         continue;
1680       }
1681     p+=y_offset*GetPixelChannels(image);
1682     displacement=degrees*(MagickRealType) (x-width/2.0);
1683     if (displacement == 0.0)
1684       continue;
1685     if (displacement > 0.0)
1686       direction=DOWN;
1687     else
1688       {
1689         displacement*=(-1.0);
1690         direction=UP;
1691       }
1692     step=(ssize_t) floor((double) displacement);
1693     area=(MagickRealType) (displacement-step);
1694     step++;
1695     pixel=background;
1696     GetPixelInfo(image,&source);
1697     GetPixelInfo(image,&destination);
1698     switch (direction)
1699     {
1700       case UP:
1701       {
1702         /*
1703           Transfer pixels top-to-bottom.
1704         */
1705         if (step > y_offset)
1706           break;
1707         q=p-step*GetPixelChannels(image);
1708         for (i=0; i < (ssize_t) height; i++)
1709         {
1710           if ((y_offset+i) < step)
1711             {
1712               p+=GetPixelChannels(image);
1713               GetPixelInfoPixel(image,p,&pixel);
1714               q+=GetPixelChannels(image);
1715               continue;
1716             }
1717           GetPixelInfoPixel(image,p,&source);
1718           CompositePixelInfoAreaBlend(&pixel,(MagickRealType) pixel.alpha,
1719             &source,(MagickRealType) GetPixelAlpha(image,p),area,
1720             &destination);
1721           SetPixelInfoPixel(image,&destination,q);
1722           GetPixelInfoPixel(image,p,&pixel);
1723           p+=GetPixelChannels(image);
1724           q+=GetPixelChannels(image);
1725         }
1726         CompositePixelInfoAreaBlend(&pixel,(MagickRealType) pixel.alpha,
1727           &background,(MagickRealType) background.alpha,area,&destination);
1728         SetPixelInfoPixel(image,&destination,q);
1729         q+=GetPixelChannels(image);
1730         for (i=0; i < (step-1); i++)
1731         {
1732           SetPixelInfoPixel(image,&background,q);
1733           q+=GetPixelChannels(image);
1734         }
1735         break;
1736       }
1737       case DOWN:
1738       {
1739         /*
1740           Transfer pixels bottom-to-top.
1741         */
1742         p+=height*GetPixelChannels(image);
1743         q=p+step*GetPixelChannels(image);
1744         for (i=0; i < (ssize_t) height; i++)
1745         {
1746           p-=GetPixelChannels(image);
1747           q-=GetPixelChannels(image);
1748           if ((size_t) (y_offset+height+step-i) >= image->rows)
1749             continue;
1750           GetPixelInfoPixel(image,p,&source);
1751           CompositePixelInfoAreaBlend(&pixel,(MagickRealType) pixel.alpha,
1752             &source,(MagickRealType) GetPixelAlpha(image,p),area,
1753             &destination);
1754           SetPixelInfoPixel(image,&destination,q);
1755           GetPixelInfoPixel(image,p,&pixel);
1756         }
1757         CompositePixelInfoAreaBlend(&pixel,(MagickRealType) pixel.alpha,
1758           &background,(MagickRealType) background.alpha,area,&destination);
1759         q-=GetPixelChannels(image);
1760         SetPixelInfoPixel(image,&destination,q);
1761         for (i=0; i < (step-1); i++)
1762         {
1763           q-=GetPixelChannels(image);
1764           SetPixelInfoPixel(image,&background,q);
1765         }
1766         break;
1767       }
1768     }
1769     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1770       status=MagickFalse;
1771     if (image->progress_monitor != (MagickProgressMonitor) NULL)
1772       {
1773         MagickBooleanType
1774           proceed;
1775
1776 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1777         #pragma omp critical (MagickCore_YShearImage)
1778 #endif
1779         proceed=SetImageProgress(image,YShearImageTag,progress++,image->rows);
1780         if (proceed == MagickFalse)
1781           status=MagickFalse;
1782       }
1783   }
1784   image_view=DestroyCacheView(image_view);
1785   return(status);
1786 }
1787 \f
1788 /*
1789 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1790 %                                                                             %
1791 %                                                                             %
1792 %                                                                             %
1793 %   S h e a r I m a g e                                                       %
1794 %                                                                             %
1795 %                                                                             %
1796 %                                                                             %
1797 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1798 %
1799 %  ShearImage() creates a new image that is a shear_image copy of an existing
1800 %  one.  Shearing slides one edge of an image along the X or Y axis, creating
1801 %  a parallelogram.  An X direction shear slides an edge along the X axis,
1802 %  while a Y direction shear slides an edge along the Y axis.  The amount of
1803 %  the shear is controlled by a shear angle.  For X direction shears, x_shear
1804 %  is measured relative to the Y axis, and similarly, for Y direction shears
1805 %  y_shear is measured relative to the X axis.  Empty triangles left over from
1806 %  shearing the image are filled with the background color defined by member
1807 %  'background_color' of the image..  ShearImage() allocates the memory
1808 %  necessary for the new Image structure and returns a pointer to the new image.
1809 %
1810 %  ShearImage() is based on the paper "A Fast Algorithm for General Raster
1811 %  Rotatation" by Alan W. Paeth.
1812 %
1813 %  The format of the ShearImage method is:
1814 %
1815 %      Image *ShearImage(const Image *image,const double x_shear,
1816 %        const double y_shear,ExceptionInfo *exception)
1817 %
1818 %  A description of each parameter follows.
1819 %
1820 %    o image: the image.
1821 %
1822 %    o x_shear, y_shear: Specifies the number of degrees to shear the image.
1823 %
1824 %    o exception: return any errors or warnings in this structure.
1825 %
1826 */
1827 MagickExport Image *ShearImage(const Image *image,const double x_shear,
1828   const double y_shear,ExceptionInfo *exception)
1829 {
1830   Image
1831     *integral_image,
1832     *shear_image;
1833
1834   ssize_t
1835     x_offset,
1836     y_offset;
1837
1838   MagickBooleanType
1839     status;
1840
1841   PointInfo
1842     shear;
1843
1844   RectangleInfo
1845     border_info;
1846
1847   size_t
1848     y_width;
1849
1850   assert(image != (Image *) NULL);
1851   assert(image->signature == MagickSignature);
1852   if (image->debug != MagickFalse)
1853     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1854   assert(exception != (ExceptionInfo *) NULL);
1855   assert(exception->signature == MagickSignature);
1856   if ((x_shear != 0.0) && (fmod(x_shear,90.0) == 0.0))
1857     ThrowImageException(ImageError,"AngleIsDiscontinuous");
1858   if ((y_shear != 0.0) && (fmod(y_shear,90.0) == 0.0))
1859     ThrowImageException(ImageError,"AngleIsDiscontinuous");
1860   /*
1861     Initialize shear angle.
1862   */
1863   integral_image=CloneImage(image,0,0,MagickTrue,exception);
1864   if (integral_image == (Image *) NULL)
1865     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
1866   shear.x=(-tan(DegreesToRadians(fmod(x_shear,360.0))));
1867   shear.y=tan(DegreesToRadians(fmod(y_shear,360.0)));
1868   if ((shear.x == 0.0) && (shear.y == 0.0))
1869     return(integral_image);
1870   if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse)
1871     {
1872       integral_image=DestroyImage(integral_image);
1873       return(integral_image);
1874     }
1875   if (integral_image->matte == MagickFalse)
1876     (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception);
1877   /*
1878     Compute image size.
1879   */
1880   y_width=image->columns+(ssize_t) floor(fabs(shear.x)*image->rows+0.5);
1881   x_offset=(ssize_t) ceil((double) image->columns+((fabs(shear.x)*image->rows)-
1882     image->columns)/2.0-0.5);
1883   y_offset=(ssize_t) ceil((double) image->rows+((fabs(shear.y)*y_width)-
1884     image->rows)/2.0-0.5);
1885   /*
1886     Surround image with border.
1887   */
1888   integral_image->border_color=integral_image->background_color;
1889   integral_image->compose=CopyCompositeOp;
1890   border_info.width=(size_t) x_offset;
1891   border_info.height=(size_t) y_offset;
1892   shear_image=BorderImage(integral_image,&border_info,image->compose,exception);
1893   integral_image=DestroyImage(integral_image);
1894   if (shear_image == (Image *) NULL)
1895     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
1896   /*
1897     Shear the image.
1898   */
1899   if (shear_image->matte == MagickFalse)
1900     (void) SetImageAlphaChannel(shear_image,OpaqueAlphaChannel,exception);
1901   status=XShearImage(shear_image,shear.x,image->columns,image->rows,x_offset,
1902     (ssize_t) (shear_image->rows-image->rows)/2,exception);
1903   if (status == MagickFalse)
1904     {
1905       shear_image=DestroyImage(shear_image);
1906       return((Image *) NULL);
1907     }
1908   status=YShearImage(shear_image,shear.y,y_width,image->rows,(ssize_t)
1909     (shear_image->columns-y_width)/2,y_offset,exception);
1910   if (status == MagickFalse)
1911     {
1912       shear_image=DestroyImage(shear_image);
1913       return((Image *) NULL);
1914     }
1915   status=CropToFitImage(&shear_image,shear.x,shear.y,(MagickRealType)
1916     image->columns,(MagickRealType) image->rows,MagickFalse,exception);
1917   if (status == MagickFalse)
1918     {
1919       shear_image=DestroyImage(shear_image);
1920       return((Image *) NULL);
1921     }
1922   shear_image->compose=image->compose;
1923   shear_image->page.width=0;
1924   shear_image->page.height=0;
1925   return(shear_image);
1926 }
1927 \f
1928 /*
1929 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1930 %                                                                             %
1931 %                                                                             %
1932 %                                                                             %
1933 %   S h e a r R o t a t e I m a g e                                           %
1934 %                                                                             %
1935 %                                                                             %
1936 %                                                                             %
1937 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1938 %
1939 %  ShearRotateImage() creates a new image that is a rotated copy of an existing
1940 %  one.  Positive angles rotate counter-clockwise (right-hand rule), while
1941 %  negative angles rotate clockwise.  Rotated images are usually larger than
1942 %  the originals and have 'empty' triangular corners.  X axis.  Empty
1943 %  triangles left over from shearing the image are filled with the background
1944 %  color defined by member 'background_color' of the image.  ShearRotateImage
1945 %  allocates the memory necessary for the new Image structure and returns a
1946 %  pointer to the new image.
1947 %
1948 %  ShearRotateImage() is based on the paper "A Fast Algorithm for General
1949 %  Raster Rotatation" by Alan W. Paeth.  ShearRotateImage is adapted from a
1950 %  similar method based on the Paeth paper written by Michael Halle of the
1951 %  Spatial Imaging Group, MIT Media Lab.
1952 %
1953 %  The format of the ShearRotateImage method is:
1954 %
1955 %      Image *ShearRotateImage(const Image *image,const double degrees,
1956 %        ExceptionInfo *exception)
1957 %
1958 %  A description of each parameter follows.
1959 %
1960 %    o image: the image.
1961 %
1962 %    o degrees: Specifies the number of degrees to rotate the image.
1963 %
1964 %    o exception: return any errors or warnings in this structure.
1965 %
1966 */
1967 MagickExport Image *ShearRotateImage(const Image *image,const double degrees,
1968   ExceptionInfo *exception)
1969 {
1970   Image
1971     *integral_image,
1972     *rotate_image;
1973
1974   MagickBooleanType
1975     status;
1976
1977   MagickRealType
1978     angle;
1979
1980   PointInfo
1981     shear;
1982
1983   RectangleInfo
1984     border_info;
1985
1986   size_t
1987     height,
1988     rotations,
1989     width,
1990     y_width;
1991
1992   ssize_t
1993     x_offset,
1994     y_offset;
1995
1996   /*
1997     Adjust rotation angle.
1998   */
1999   assert(image != (Image *) NULL);
2000   assert(image->signature == MagickSignature);
2001   if (image->debug != MagickFalse)
2002     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2003   assert(exception != (ExceptionInfo *) NULL);
2004   assert(exception->signature == MagickSignature);
2005   angle=degrees;
2006   while (angle < -45.0)
2007     angle+=360.0;
2008   for (rotations=0; angle > 45.0; rotations++)
2009     angle-=90.0;
2010   rotations%=4;
2011   /*
2012     Calculate shear equations.
2013   */
2014   integral_image=IntegralRotateImage(image,rotations,exception);
2015   if (integral_image == (Image *) NULL)
2016     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
2017   shear.x=(-tan((double) DegreesToRadians(angle)/2.0));
2018   shear.y=sin((double) DegreesToRadians(angle));
2019   if ((shear.x == 0.0) && (shear.y == 0.0))
2020     return(integral_image);
2021   if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse)
2022     {
2023       integral_image=DestroyImage(integral_image);
2024       return(integral_image);
2025     }
2026   if (integral_image->matte == MagickFalse)
2027     (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception);
2028   /*
2029     Compute image size.
2030   */
2031   width=image->columns;
2032   height=image->rows;
2033   if ((rotations == 1) || (rotations == 3))
2034     {
2035       width=image->rows;
2036       height=image->columns;
2037     }
2038   y_width=width+(ssize_t) floor(fabs(shear.x)*height+0.5);
2039   x_offset=(ssize_t) ceil((double) width+((fabs(shear.y)*height)-width)/2.0-
2040     0.5);
2041   y_offset=(ssize_t) ceil((double) height+((fabs(shear.y)*y_width)-height)/2.0-
2042     0.5);
2043   /*
2044     Surround image with a border.
2045   */
2046   integral_image->border_color=integral_image->background_color;
2047   integral_image->compose=CopyCompositeOp;
2048   border_info.width=(size_t) x_offset;
2049   border_info.height=(size_t) y_offset;
2050   rotate_image=BorderImage(integral_image,&border_info,image->compose,
2051     exception);
2052   integral_image=DestroyImage(integral_image);
2053   if (rotate_image == (Image *) NULL)
2054     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
2055   /*
2056     Rotate the image.
2057   */
2058   status=XShearImage(rotate_image,shear.x,width,height,x_offset,(ssize_t)
2059     (rotate_image->rows-height)/2,exception);
2060   if (status == MagickFalse)
2061     {
2062       rotate_image=DestroyImage(rotate_image);
2063       return((Image *) NULL);
2064     }
2065   status=YShearImage(rotate_image,shear.y,y_width,height,(ssize_t)
2066     (rotate_image->columns-y_width)/2,y_offset,exception);
2067   if (status == MagickFalse)
2068     {
2069       rotate_image=DestroyImage(rotate_image);
2070       return((Image *) NULL);
2071     }
2072   status=XShearImage(rotate_image,shear.x,y_width,rotate_image->rows,(ssize_t)
2073     (rotate_image->columns-y_width)/2,0,exception);
2074   if (status == MagickFalse)
2075     {
2076       rotate_image=DestroyImage(rotate_image);
2077       return((Image *) NULL);
2078     }
2079   status=CropToFitImage(&rotate_image,shear.x,shear.y,(MagickRealType) width,
2080     (MagickRealType) height,MagickTrue,exception);
2081   if (status == MagickFalse)
2082     {
2083       rotate_image=DestroyImage(rotate_image);
2084       return((Image *) NULL);
2085     }
2086   rotate_image->compose=image->compose;
2087   rotate_image->page.width=0;
2088   rotate_image->page.height=0;
2089   return(rotate_image);
2090 }