~ubuntu-branches/ubuntu/karmic/digikam/karmic-backports

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
/* ============================================================
 *
 * This file is a part of digiKam project
 * http://www.digikam.org
 *
 * Date        : 2005-24-01
 * Description : misc image filters
 *
 * Copyright (C) 2004-2009 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * Original Equalise and StretchContrast Algorithms copyright 2002
 * by Daniel M. Duley <mosfet@kde.org> from KImageEffect API.
 *
 * Original Normalize Image algorithm copyrighted 1997 by
 * Adam D. Moss <adam@foxbox.org> from Gimp 2.0 implementation.
 *
 * Original channel mixer algorithm copyrighted 2002 by
 * Martin Guldahl <mguldahl at xmission dot com> from Gimp 2.2
 *
 * This program is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General
 * Public License as published by the Free Software Foundation;
 * either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * ============================================================ */

#include "dimgimagefilters.h"

// C++ includes

#include <cstring>
#include <cstdlib>

// KDE includes

#include <kdebug.h>

// Local includes

#include "imagehistogram.h"
#include "imagelevels.h"
#include "dcolor.h"
#include "dimggaussianblur.h"
#include "dimgsharpen.h"
#include "dimgunsharpmask.h"
#include "dimgrefocus.h"
#include "globals.h"

namespace Digikam
{

/** Performs an histogram equalization of the image.
    this method adjusts the brightness of colors across the
    active image so that the histogram for the value channel
    is as nearly as possible flat, that is, so that each possible
    brightness value appears at about the same number of pixels
    as each other value. Sometimes Equalize works wonderfully at
    enhancing the contrasts in an image. Other times it gives
    garbage. It is a very powerful operation, which can either work
    miracles on an image or destroy it.*/
void DImgImageFilters::equalizeImage(uchar *data, int w, int h, bool sixteenBit)
{
    if (!data || !w || !h)
    {
       kWarning() << ("DImgImageFilters::equalizeImage: no image data available!");
       return;
    }

    struct double_packet  high, low, intensity;
    struct double_packet *map;
    struct int_packet    *equalize_map;
    register long         i;

    // Create an histogram of the current image.
    ImageHistogram *histogram = new ImageHistogram(data, w, h, sixteenBit);
    histogram->calculate();

    // Memory allocation.
    map          = new double_packet[histogram->getHistogramSegments()];
    equalize_map = new int_packet[histogram->getHistogramSegments()];

    if( !histogram || !map || !equalize_map )
    {
       if(histogram)
           delete histogram;

       if(map)
           delete [] map;

       if(equalize_map)
           delete [] equalize_map;

       kWarning() << ("DImgImageFilters::equalizeImage: Unable to allocate memory!");
       return;
    }

    // Integrate the histogram to get the equalization map.

    memset(&intensity, 0, sizeof(struct double_packet));
    memset(&high,      0, sizeof(struct double_packet));
    memset(&low,       0, sizeof(struct double_packet));

    for(i = 0 ; i < histogram->getHistogramSegments() ; ++i)
    {
       intensity.red   += histogram->getValue(RedChannel, i);
       intensity.green += histogram->getValue(GreenChannel, i);
       intensity.blue  += histogram->getValue(BlueChannel, i);
       intensity.alpha += histogram->getValue(AlphaChannel, i);
       map[i]           = intensity;
    }

    // Stretch the histogram.

    low  = map[0];
    high = map[histogram->getHistogramSegments()-1];
    memset(equalize_map, 0, histogram->getHistogramSegments()*sizeof(int_packet));

    // TODO magic number 256
    for(i = 0 ; i < histogram->getHistogramSegments() ; ++i)
    {
       if(high.red != low.red)
          equalize_map[i].red = (uint)(((256*histogram->getHistogramSegments() -1) *
                                (map[i].red-low.red))/(high.red-low.red));

       if(high.green != low.green)
          equalize_map[i].green = (uint)(((256*histogram->getHistogramSegments() -1) *
                                  (map[i].green-low.green))/(high.green-low.green));

       if(high.blue != low.blue)
          equalize_map[i].blue = (uint)(((256*histogram->getHistogramSegments() -1) *
                                 (map[i].blue-low.blue))/(high.blue-low.blue));

       if(high.alpha != low.alpha)
          equalize_map[i].alpha = (uint)(((256*histogram->getHistogramSegments() -1) *
                                  (map[i].alpha-low.alpha))/(high.alpha-low.alpha));
    }

    delete histogram;
    delete [] map;

    // Apply results to image.
    // TODO magic number 257
    if (!sixteenBit)        // 8 bits image.
    {
        uchar red, green, blue, alpha;
        uchar *ptr = data;

        for (i = 0 ; i < w*h ; ++i)
        {
            blue  = ptr[0];
            green = ptr[1];
            red   = ptr[2];
            alpha = ptr[3];

            if(low.red != high.red)
                red = (equalize_map[red].red)/257;

            if(low.green != high.green)
                green = (equalize_map[green].green)/257;

            if(low.blue != high.blue)
                blue = (equalize_map[blue].blue)/257;

            if(low.alpha != high.alpha)
                alpha = (equalize_map[alpha].alpha)/257;

            ptr[0] = blue;
            ptr[1] = green;
            ptr[2] = red;
            ptr[3] = alpha;
            ptr   += 4;
        }
    }
    else               // 16 bits image.
    {
        unsigned short red, green, blue, alpha;
        unsigned short *ptr = (unsigned short *)data;

        for (i = 0 ; i < w*h ; ++i)
        {
            blue  = ptr[0];
            green = ptr[1];
            red   = ptr[2];
            alpha = ptr[3];

            if(low.red != high.red)
                red = (equalize_map[red].red)/257;

            if(low.green != high.green)
                green = (equalize_map[green].green)/257;

            if(low.blue != high.blue)
                blue = (equalize_map[blue].blue)/257;

            if(low.alpha != high.alpha)
                alpha = (equalize_map[alpha].alpha)/257;

            ptr[0] = blue;
            ptr[1] = green;
            ptr[2] = red;
            ptr[3] = alpha;
            ptr   += 4;
        }
    }

    delete [] equalize_map;
}

/** Performs histogram normalization of the image. The algorithm normalizes
    the pixel values from an image for to span the full range
    of color values. This is a contrast enhancement technique.*/
void DImgImageFilters::stretchContrastImage(uchar *data, int w, int h, bool sixteenBit)
{
    if (!data || !w || !h)
    {
       kWarning() << ("DImgImageFilters::stretchContrastImage: no image data available!");
       return;
    }

    struct double_packet  high, low, intensity;
    struct int_packet    *normalize_map;
    long long             number_pixels;
    register long         i;
    unsigned long         threshold_intensity;

    // Create an histogram of the current image.
    ImageHistogram *histogram = new ImageHistogram(data, w, h, sixteenBit);
    histogram->calculate();

    // Memory allocation.
    normalize_map = new int_packet[histogram->getHistogramSegments()];

    if( !histogram || !normalize_map )
    {
       if(histogram)
           delete histogram;

       if(normalize_map)
           delete [] normalize_map;

       kWarning() << ("DImgImageFilters::stretchContrastImage: Unable to allocate memory!");
       return;
    }

    // Find the histogram boundaries by locating the 0.1 percent levels.

    number_pixels = (long long)(w*h);
    threshold_intensity = number_pixels / 1000;

    memset(&high, 0, sizeof(struct double_packet));
    memset(&low,  0, sizeof(struct double_packet));

    // Red.

    memset(&intensity, 0, sizeof(struct double_packet));

    for(high.red = histogram->getMaxSegmentIndex() ; high.red != 0 ; --high.red)
    {
       intensity.red += histogram->getValue(RedChannel, (int)high.red);

       if( intensity.red > threshold_intensity )
          break;
    }

    if( low.red == high.red )
    {
       threshold_intensity = 0;
       memset(&intensity, 0, sizeof(struct double_packet));

       for(low.red = 0 ; low.red < histogram->getMaxSegmentIndex() ; ++low.red)
       {
          intensity.red += histogram->getValue(RedChannel, (int)low.red);

          if( intensity.red > threshold_intensity )
              break;
       }

       memset(&intensity, 0, sizeof(struct double_packet));

       for(high.red = histogram->getMaxSegmentIndex() ; high.red != 0 ; --high.red)
       {
          intensity.red += histogram->getValue(RedChannel, (int)high.red);

          if( intensity.red > threshold_intensity )
             break;
       }
    }

    // Green.

    memset(&intensity, 0, sizeof(struct double_packet));

    for(high.green = histogram->getMaxSegmentIndex() ; high.green != 0 ; --high.green)
    {
       intensity.green += histogram->getValue(GreenChannel, (int)high.green);

       if( intensity.green > threshold_intensity )
          break;
    }

    if( low.green == high.green )
    {
       threshold_intensity = 0;
       memset(&intensity, 0, sizeof(struct double_packet));

       for(low.green = 0 ; low.green < histogram->getMaxSegmentIndex() ; ++low.green)
       {
          intensity.green += histogram->getValue(GreenChannel, (int)low.green);

          if( intensity.green > threshold_intensity )
             break;
       }

       memset(&intensity, 0, sizeof(struct double_packet));

       for(high.green = histogram->getMaxSegmentIndex() ; high.green != 0 ; --high.green)
       {
          intensity.green += histogram->getValue(GreenChannel, (int)high.green);

          if( intensity.green > threshold_intensity )
             break;
       }
    }

    // Blue.

    memset(&intensity, 0, sizeof(struct double_packet));

    for(high.blue = histogram->getMaxSegmentIndex() ; high.blue != 0 ; --high.blue)
    {
       intensity.blue += histogram->getValue(BlueChannel, (int)high.blue);

       if( intensity.blue > threshold_intensity )
          break;
    }

    if( low.blue == high.blue )
    {
       threshold_intensity = 0;
       memset(&intensity, 0, sizeof(struct double_packet));

       for(low.blue = 0 ; low.blue < histogram->getMaxSegmentIndex() ; ++low.blue)
       {
          intensity.blue += histogram->getValue(BlueChannel, (int)low.blue);

          if( intensity.blue > threshold_intensity )
              break;
       }

       memset(&intensity, 0, sizeof(struct double_packet));

       for(high.blue = histogram->getMaxSegmentIndex() ; high.blue != 0 ; --high.blue)
       {
          intensity.blue += histogram->getValue(BlueChannel, (int)high.blue);

          if( intensity.blue > threshold_intensity )
             break;
       }
    }

    // Alpha.

    memset(&intensity, 0, sizeof(struct double_packet));

    for(high.alpha = histogram->getMaxSegmentIndex() ; high.alpha != 0 ; --high.alpha)
    {
       intensity.alpha += histogram->getValue(AlphaChannel, (int)high.alpha);

       if( intensity.alpha > threshold_intensity )
          break;
    }

    if( low.alpha == high.alpha )
    {
       threshold_intensity = 0;
       memset(&intensity, 0, sizeof(struct double_packet));

       for(low.alpha = 0 ; low.alpha < histogram->getMaxSegmentIndex() ; ++low.alpha)
       {
          intensity.alpha += histogram->getValue(AlphaChannel, (int)low.alpha);

          if( intensity.alpha > threshold_intensity )
             break;
       }

       memset(&intensity, 0, sizeof(struct double_packet));

       for(high.alpha = histogram->getMaxSegmentIndex() ; high.alpha != 0 ; --high.alpha)
       {
          intensity.alpha += histogram->getValue(AlphaChannel, (int)high.alpha);

          if( intensity.alpha > threshold_intensity )
             break;
       }
    }

    // Stretch the histogram to create the normalized image mapping.

    memset(normalize_map, 0, histogram->getHistogramSegments()*sizeof(struct int_packet));

    // TODO magic number 256
    for(i = 0 ; i <= (long)histogram->getMaxSegmentIndex() ; ++i)
    {
       if(i < (long) low.red)
          normalize_map[i].red = 0;
       else if (i > (long) high.red)
          normalize_map[i].red = (256*histogram->getHistogramSegments() -1);
       else if (low.red != high.red)
          normalize_map[i].red = (int)(((256*histogram->getHistogramSegments() -1)*(i-low.red))/(high.red-low.red));

       if(i < (long) low.green)
          normalize_map[i].green = 0;
       else if (i > (long) high.green)
          normalize_map[i].green = (256*histogram->getHistogramSegments() -1);
       else if (low.green != high.green)
          normalize_map[i].green = (int)(((256*histogram->getHistogramSegments() -1)*(i-low.green))/(high.green-low.green));

       if(i < (long) low.blue)
          normalize_map[i].blue = 0;
       else if (i > (long) high.blue)
          normalize_map[i].blue = (256*histogram->getHistogramSegments() -1);
       else if (low.blue != high.blue)
          normalize_map[i].blue = (int)(((256*histogram->getHistogramSegments() -1)*(i-low.blue))/(high.blue-low.blue));

       if(i < (long) low.alpha)
          normalize_map[i].alpha = 0;
       else if (i > (long) high.alpha)
          normalize_map[i].alpha = (256*histogram->getHistogramSegments() -1);
       else if (low.alpha != high.alpha)
          normalize_map[i].alpha = (int)(((256*histogram->getHistogramSegments() -1)*(i-low.alpha))/(high.alpha-low.alpha));
    }

    // Apply result to image.
    // TODO magic number 257
    if (!sixteenBit)        // 8 bits image.
    {
        uchar red, green, blue, alpha;
        uchar *ptr = data;

        for (i = 0 ; i < w*h ; ++i)
        {
            blue  = ptr[0];
            green = ptr[1];
            red   = ptr[2];
            alpha = ptr[3];

            if(low.red != high.red)
                red = (normalize_map[red].red)/257;

            if(low.green != high.green)
                green = (normalize_map[green].green)/257;

            if(low.blue != high.blue)
                blue = (normalize_map[blue].blue)/257;

            if(low.alpha != high.alpha)
                alpha = (normalize_map[alpha].alpha)/257;

            ptr[0] = blue;
            ptr[1] = green;
            ptr[2] = red;
            ptr[3] = alpha;
            ptr += 4;
        }
    }
    else               // 16 bits image.
    {
        unsigned short red, green, blue, alpha;
        unsigned short *ptr = (unsigned short *)data;

        for (i = 0 ; i < w*h ; ++i)
        {
            blue  = ptr[0];
            green = ptr[1];
            red   = ptr[2];
            alpha = ptr[3];

            if(low.red != high.red)
                red = (normalize_map[red].red)/257;

            if(low.green != high.green)
                green = (normalize_map[green].green)/257;

            if(low.blue != high.blue)
                blue = (normalize_map[blue].blue)/257;

            if(low.alpha != high.alpha)
                alpha = (normalize_map[alpha].alpha)/257;

            ptr[0] = blue;
            ptr[1] = green;
            ptr[2] = red;
            ptr[3] = alpha;
            ptr += 4;
        }
    }

    delete histogram;
    delete [] normalize_map;
}

/** This method scales brightness values across the active
    image so that the darkest point becomes black, and the
    brightest point becomes as bright as possible without
    altering its hue. This is often a magic fix for
    images that are dim or washed out.*/
void DImgImageFilters::normalizeImage(uchar *data, int w, int h, bool sixteenBit)
{
    NormalizeParam  param;
    int             x, i;
    unsigned short  range;

    int segments = sixteenBit ? NUM_SEGMENTS_16BIT : NUM_SEGMENTS_8BIT;

    // Memory allocation.

    param.lut = new unsigned short[segments];

    // Find min. and max. values.

    param.min = segments-1;
    param.max = 0;

    if (!sixteenBit)        // 8 bits image.
    {
        uchar red, green, blue;
        uchar *ptr = data;

        for (i = 0 ; i < w*h ; ++i)
        {
            blue  = ptr[0];
            green = ptr[1];
            red   = ptr[2];

            if (red < param.min) param.min = red;
            if (red > param.max) param.max = red;

            if (green < param.min) param.min = green;
            if (green > param.max) param.max = green;

            if (blue < param.min) param.min = blue;
            if (blue > param.max) param.max = blue;

            ptr += 4;
        }
    }
    else               // 16 bits image.
    {
        unsigned short red, green, blue;
        unsigned short *ptr = (unsigned short *)data;

        for (i = 0 ; i < w*h ; ++i)
        {
            blue  = ptr[0];
            green = ptr[1];
            red   = ptr[2];

            if (red < param.min) param.min = red;
            if (red > param.max) param.max = red;

            if (green < param.min) param.min = green;
            if (green > param.max) param.max = green;

            if (blue < param.min) param.min = blue;
            if (blue > param.max) param.max = blue;

            ptr += 4;
        }
    }

    // Calculate LUT.

    range = (unsigned short)(param.max - param.min);

    if (range != 0)
    {
       for (x = (int)param.min ; x <= (int)param.max ; ++x)
          param.lut[x] = (unsigned short)((segments-1) * (x - param.min) / range);
    }
    else
       param.lut[(int)param.min] = (unsigned short)param.min;

    // Apply LUT to image.

    if (!sixteenBit)        // 8 bits image.
    {
        uchar red, green, blue;
        uchar *ptr = data;

        for (i = 0 ; i < w*h ; ++i)
        {
            blue  = ptr[0];
            green = ptr[1];
            red   = ptr[2];

            ptr[0] = param.lut[blue];
            ptr[1] = param.lut[green];
            ptr[2] = param.lut[red];

            ptr += 4;
        }
    }
    else               // 16 bits image.
    {
        unsigned short red, green, blue;
        unsigned short *ptr = (unsigned short *)data;

        for (i = 0 ; i < w*h ; ++i)
        {
            blue  = ptr[0];
            green = ptr[1];
            red   = ptr[2];

            ptr[0] = param.lut[blue];
            ptr[1] = param.lut[green];
            ptr[2] = param.lut[red];

            ptr += 4;
        }
    }

     delete [] param.lut;
}

/** Performs histogram auto correction of levels.
    This method maximizes the tonal range in the Red,
    Green, and Blue channels. It search the image shadow and highlight
    limit values and adjust the Red, Green, and Blue channels
    to a full histogram range.*/
void DImgImageFilters::autoLevelsCorrectionImage(uchar *data, int w, int h, bool sixteenBit)
{
    if (!data || !w || !h)
    {
       kWarning() << ("DImgImageFilters::autoLevelsCorrectionImage: no image data available!");
       return;
    }
    uchar* desData;

    // Create the new empty destination image data space.
    if (sixteenBit)
       desData = new uchar[w*h*8];
    else
       desData = new uchar[w*h*4];

    // Create an histogram of the current image.
    ImageHistogram *histogram = new ImageHistogram(data, w, h, sixteenBit);
    histogram->calculate();

    // Create an empty instance of levels to use.
    ImageLevels *levels = new ImageLevels(sixteenBit);

    // Initialize an auto levels correction of the histogram.
    levels->levelsAuto(histogram);

    // Calculate the LUT to apply on the image.
    levels->levelsLutSetup(AlphaChannel);

    // Apply the lut to the image.
    levels->levelsLutProcess(data, desData, w, h);

    if (sixteenBit)
       memcpy (data, desData, w*h*8);
    else
       memcpy (data, desData, w*h*4);

    delete [] desData;
    delete histogram;
    delete levels;
}

/** Performs image colors inversion. This tool is used for negate image
    resulting of a positive film scanned.*/
void DImgImageFilters::invertImage(uchar *data, int w, int h, bool sixteenBit)
{
    if (!data || !w || !h)
    {
       kWarning() << ("DImgImageFilters::invertImage: no image data available!");
       return;
    }

    if (!sixteenBit)        // 8 bits image.
    {
        uchar *ptr = data;

        for (int i = 0 ; i < w*h ; ++i)
        {
            ptr[0] = 255 - ptr[0];
            ptr[1] = 255 - ptr[1];
            ptr[2] = 255 - ptr[2];
            ptr[3] = 255 - ptr[3];
            ptr += 4;
        }
    }
    else               // 16 bits image.
    {
        unsigned short *ptr = (unsigned short *)data;

        for (int i = 0 ; i < w*h ; ++i)
        {
            ptr[0] = 65535 - ptr[0];
            ptr[1] = 65535 - ptr[1];
            ptr[2] = 65535 - ptr[2];
            ptr[3] = 65535 - ptr[3];
            ptr += 4;
        }
    }
}

/** Mix RGB channel color from image*/
void DImgImageFilters::channelMixerImage(uchar *data, int Width, int Height, bool sixteenBit,
                                         bool bPreserveLum, bool bMonochrome,
                                         float rrGain, float rgGain, float rbGain,
                                         float grGain, float ggGain, float gbGain,
                                         float brGain, float bgGain, float bbGain)
{
    if (!data || !Width || !Height)
    {
       kWarning() << ("DImgImageFilters::channelMixerImage: no image data available!");
       return;
    }

    register int i;

    double rnorm = CalculateNorm (rrGain, rgGain, rbGain, bPreserveLum);
    double gnorm = CalculateNorm (grGain, ggGain, gbGain, bPreserveLum);
    double bnorm = CalculateNorm (brGain, bgGain, bbGain, bPreserveLum);

    if (!sixteenBit)        // 8 bits image.
    {
        uchar  nGray, red, green, blue;
        uchar *ptr = data;

        for (i = 0 ; i < Width*Height ; ++i)
        {
            blue  = ptr[0];
            green = ptr[1];
            red   = ptr[2];

            if (bMonochrome)
            {
                nGray = MixPixel (rrGain, rgGain, rbGain,
                                  (unsigned short)red, (unsigned short)green, (unsigned short)blue,
                                  sixteenBit, rnorm);
                ptr[0] = ptr[1] = ptr[2] = nGray;
            }
            else
            {
                ptr[0] = (uchar)MixPixel (brGain, bgGain, bbGain,
                                          (unsigned short)red, (unsigned short)green, (unsigned short)blue,
                                          sixteenBit, bnorm);
                ptr[1] = (uchar)MixPixel (grGain, ggGain, gbGain,
                                          (unsigned short)red, (unsigned short)green, (unsigned short)blue,
                                          sixteenBit, gnorm);
                ptr[2] = (uchar)MixPixel (rrGain, rgGain, rbGain,
                                          (unsigned short)red, (unsigned short)green, (unsigned short)blue,
                                          sixteenBit, rnorm);
            }

            ptr += 4;
        }
    }
    else               // 16 bits image.
    {
        unsigned short  nGray, red, green, blue;
        unsigned short *ptr = (unsigned short *)data;

        for (i = 0 ; i < Width*Height ; ++i)
        {
            blue  = ptr[0];
            green = ptr[1];
            red   = ptr[2];

            if (bMonochrome)
            {
                nGray = MixPixel (rrGain, rgGain, rbGain, red, green, blue, sixteenBit, rnorm);
                ptr[0] = ptr[1] = ptr[2] = nGray;
            }
            else
            {
                ptr[0] = MixPixel (brGain, bgGain, bbGain, red, green, blue, sixteenBit, bnorm);
                ptr[1] = MixPixel (grGain, ggGain, gbGain, red, green, blue, sixteenBit, gnorm);
                ptr[2] = MixPixel (rrGain, rgGain, rbGain, red, green, blue, sixteenBit, rnorm);
            }

            ptr += 4;
        }
    }
}

/** Change color tonality of an image for applying a RGB color mask.*/
void DImgImageFilters::changeTonality(uchar *data, int width, int height, bool sixteenBit,
                                      int redMask, int greenMask, int blueMask)
{
    if (!data || !width || !height)
    {
       kWarning() << ("DImgImageFilters::changeTonality: no image data available!");
       return;
    }

    int hue, sat, lig;

    DColor mask(redMask, greenMask, blueMask, 0, sixteenBit);
    mask.getHSL(&hue, &sat, &lig);

    if (!sixteenBit)        // 8 bits image.
    {
        uchar *ptr = data;

        for (int i = 0 ; i < width*height ; ++i)
        {
            // Convert to grayscale using tonal mask

            lig = ROUND (0.3 * ptr[2] + 0.59 * ptr[1] + 0.11 * ptr[0]);

            mask.setRGB(hue, sat, lig, sixteenBit);

            ptr[0] = (uchar)mask.blue();
            ptr[1] = (uchar)mask.green();
            ptr[2] = (uchar)mask.red();
            ptr += 4;
        }
    }
    else               // 16 bits image.
    {
        unsigned short *ptr = (unsigned short *)data;

        for (int i = 0 ; i < width*height ; ++i)
        {
            // Convert to grayscale using tonal mask

            lig = ROUND (0.3 * ptr[2] + 0.59 * ptr[1] + 0.11 * ptr[0]);

            mask.setRGB(hue, sat, lig, sixteenBit);

            ptr[0] = (unsigned short)mask.blue();
            ptr[1] = (unsigned short)mask.green();
            ptr[2] = (unsigned short)mask.red();
            ptr += 4;
        }
    }
}

/** Function to apply the GaussianBlur on an image. This method do not use a
    dedicated thread.*/
void DImgImageFilters::gaussianBlurImage(uchar *data, int width, int height, bool sixteenBit, int radius)
{
    if (!data || !width || !height)
    {
       kWarning() << ("DImgImageFilters::gaussianBlurImage: no image data available!");
       return;
    }

    if (radius > 100) radius = 100;
    if (radius <= 0) return;

    DImg orgImage(width, height, sixteenBit, true, data);
    DImgGaussianBlur *filter = new DImgGaussianBlur(&orgImage, 0L, radius);
    filter->startFilterDirectly();
    DImg imDest = filter->getTargetImage();
    memcpy( data, imDest.bits(), imDest.numBytes() );
    delete filter;
}

/** Function to apply the sharpen filter on an image. This method do not use a
    dedicated thread.*/
void DImgImageFilters::sharpenImage(uchar *data, int width, int height, bool sixteenBit, int radius)
{
    if (!data || !width || !height)
    {
       kWarning() << ("DImgImageFilters::sharpenImage: no image data available!");
       return;
    }

    if (radius > 100) radius = 100;
    if (radius <= 0) return;

    DImg orgImage(width, height, sixteenBit, true, data);
    DImgSharpen *filter = new DImgSharpen(&orgImage, 0L, radius);
    filter->startFilterDirectly();
    DImg imDest = filter->getTargetImage();
    memcpy(data, imDest.bits(), imDest.numBytes());
    delete filter;
}

void DImgImageFilters::unsharpMaskImage(uchar *data, int width, int height, bool sixteenBit,
        int radius, double amount, double threshold)
{
    if (!data || !width || !height)
    {
       kWarning() << ("DImgImageFilters::unsharpMaskImage: no image data available!");
       return;
    }

    DImg orgImage(width, height, sixteenBit, true, data);
    DImgUnsharpMask *filter = new DImgUnsharpMask(&orgImage, 0L, radius, amount, threshold);
    filter->startFilterDirectly();
    DImg imDest = filter->getTargetImage();
    memcpy(data, imDest.bits(), imDest.numBytes());
    delete filter;
}

void DImgImageFilters::refocusImage(uchar *data, int width, int height, bool sixteenBit,
        int matrixSize, double radius, double gauss, double correlation, double noise)
{
    if (!data || !width || !height)
    {
       kWarning() << ("DImgImageFilters::refocusImage: no image data available!");
       return;
    }

    DImg orgImage(width, height, sixteenBit, true, data);
    DImgRefocus *filter = new DImgRefocus(&orgImage, 0L, matrixSize,
            radius, gauss, correlation, noise);
    filter->startFilterDirectly();
    DImg imDest = filter->getTargetImage();
    memcpy(data, imDest.bits(), imDest.numBytes());
    delete filter;
}

/** Function to perform pixel antialiasing with 8 bits/color/pixel images. This method is used to smooth target
    image in transformation  method like free rotation or shear tool. */
void DImgImageFilters::pixelAntiAliasing(uchar *data, int Width, int Height, double X, double Y,
                                         uchar *A, uchar *R, uchar *G, uchar *B)
{
    int nX, nY, j;
    double lfWeightX[2], lfWeightY[2], lfWeight;
    double lfTotalR = 0.0, lfTotalG = 0.0, lfTotalB = 0.0, lfTotalA = 0.0;

    nX = (int)X;
    nY = (int)Y;

    if (Y >= 0.0)
        lfWeightY[0] = 1.0 - (lfWeightY[1] = Y - (double)nY);
    else
        lfWeightY[1] = 1.0 - (lfWeightY[0] = -(Y - (double)nY));

    if (X >= 0.0)
        lfWeightX[0] = 1.0 - (lfWeightX[1] = X - (double)nX);
    else
        lfWeightX[1] = 1.0 - (lfWeightX[0] = -(X - (double)nX));

    for (int loopx = 0; loopx <= 1; ++loopx)
    {
        for (int loopy = 0; loopy <= 1; ++loopy)
        {
            lfWeight = lfWeightX[loopx] * lfWeightY[loopy];
            j = setPositionAdjusted (Width, Height, nX + loopx, nY + loopy);

            lfTotalB += ((double)data[j] * lfWeight);
            ++j;
            lfTotalG += ((double)data[j] * lfWeight);
            ++j;
            lfTotalR += ((double)data[j] * lfWeight);
            ++j;
            lfTotalA += ((double)data[j] * lfWeight);
            ++j;
        }
    }

    *B = CLAMP0255((int)lfTotalB);
    *G = CLAMP0255((int)lfTotalG);
    *R = CLAMP0255((int)lfTotalR);
    *A = CLAMP0255((int)lfTotalA);
}

/** Function to perform pixel antialiasing with 16 bits/color/pixel images. This method is used to smooth target
    image in transformation  method like free rotation or shear tool. */
void DImgImageFilters::pixelAntiAliasing16(unsigned short *data, int Width, int Height, double X, double Y,
                                           unsigned short *A, unsigned short *R, unsigned short *G,
                                           unsigned short *B)
{
    int nX, nY, j;
    double lfWeightX[2], lfWeightY[2], lfWeight;
    double lfTotalR = 0.0, lfTotalG = 0.0, lfTotalB = 0.0, lfTotalA = 0.0;

    nX = (int)X;
    nY = (int)Y;

    if (Y >= 0.0)
        lfWeightY[0] = 1.0 - (lfWeightY[1] = Y - (double)nY);
    else
        lfWeightY[1] = 1.0 - (lfWeightY[0] = -(Y - (double)nY));

    if (X >= 0.0)
        lfWeightX[0] = 1.0 - (lfWeightX[1] = X - (double)nX);
    else
        lfWeightX[1] = 1.0 - (lfWeightX[0] = -(X - (double)nX));

    for (int loopx = 0; loopx <= 1; ++loopx)
    {
        for (int loopy = 0; loopy <= 1; ++loopy)
        {
            lfWeight = lfWeightX[loopx] * lfWeightY[loopy];
            j = setPositionAdjusted (Width, Height, nX + loopx, nY + loopy);

            lfTotalB += ((double)data[j] * lfWeight);
            ++j;
            lfTotalG += ((double)data[j] * lfWeight);
            ++j;
            lfTotalR += ((double)data[j] * lfWeight);
            ++j;
            lfTotalA += ((double)data[j] * lfWeight);
            ++j;
        }
    }

    *B = CLAMP065535((int)lfTotalB);
    *G = CLAMP065535((int)lfTotalG);
    *R = CLAMP065535((int)lfTotalR);
    *A = CLAMP065535((int)lfTotalA);
}

}  // namespace Digikam