summaryrefslogtreecommitdiffstats
path: root/digikam/imageplugins/coreplugin/imageeffect_autocorrection.cpp
blob: bd116d66884bef38e65a0ce12b1abe167c588f35 (plain)
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
/* ============================================================
 *
 * This file is a part of digiKam project
 * http://www.digikam.org
 *
 * Date        : 2005-05-31
 * Description : Auto-Color correction tool.
 *
 * Copyright (C) 2005-2007 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * 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.
 * 
 * ============================================================ */

 // TQt includes.
 
#include <tqcolor.h>
#include <tqgroupbox.h>
#include <tqhgroupbox.h>
#include <tqvgroupbox.h>
#include <tqhbuttongroup.h> 
#include <tqradiobutton.h>
#include <tqvgroupbox.h>
#include <tqhbuttongroup.h> 
#include <tqlabel.h>
#include <tqlayout.h>
#include <tqframe.h>
#include <tqtimer.h>
#include <tqvbox.h>
#include <tqlabel.h>
#include <tqpushbutton.h>
#include <tqcheckbox.h>
#include <tqcombobox.h>
#include <tqlistbox.h>
#include <tqwhatsthis.h>
#include <tqtooltip.h>

// KDE includes.

#include <kcursor.h>
#include <kstandarddirs.h>
#include <tdeconfig.h>
#include <tdelocale.h>
#include <tdeapplication.h>

// Digikam includes.

#include "imageiface.h"
#include "imagewidget.h"
#include "histogramwidget.h"
#include "colorgradientwidget.h"
#include "dimgimagefilters.h"
#include "whitebalance.h"
#include "dimg.h"
#include "listboxpreviewitem.h"

// Local includes.

#include "imageeffect_autocorrection.h"
#include "imageeffect_autocorrection.moc"

namespace DigikamImagesPluginCore
{

ImageEffect_AutoCorrection::ImageEffect_AutoCorrection(TQWidget* parent)
                          : Digikam::ImageDlgBase(parent, i18n("Auto Color Correction"), 
                            "autocorrection", false), m_destinationPreviewData(0L)
{
    setHelp("autocolorcorrectiontool.anchor", "digikam");
    
    // -------------------------------------------------------------

    m_previewWidget = new Digikam::ImageWidget("autocorrection Tool Dialog", plainPage(),
                                               i18n("<p>Here you can see the auto-color correction tool "
                                                    "preview. You can pick color on image "
                                                    "to see the color level corresponding on histogram."));
    setPreviewAreaWidget(m_previewWidget);
    
    // -------------------------------------------------------------

    Digikam::ImageIface iface(0, 0);
    m_thumbnailImage = iface.getOriginalImg()->smoothScale(128, 128, TQSize::ScaleMin);

    TQWidget *gboxSettings     = new TQWidget(plainPage());
    TQGridLayout* gridSettings = new TQGridLayout( gboxSettings, 4, 4, spacingHint());

    TQLabel *label1 = new TQLabel(i18n("Channel:"), gboxSettings);
    label1->setAlignment ( TQt::AlignRight | TQt::AlignVCenter );
    m_channelCB = new TQComboBox( false, gboxSettings );
    m_channelCB->insertItem( i18n("Luminosity") );
    m_channelCB->insertItem( i18n("Red") );
    m_channelCB->insertItem( i18n("Green") );
    m_channelCB->insertItem( i18n("Blue") );
    TQWhatsThis::add( m_channelCB, i18n("<p>Select the histogram channel to display here:<p>"
                                       "<b>Luminosity</b>: display the image's luminosity values.<p>"
                                       "<b>Red</b>: display the red image-channel values.<p>"
                                       "<b>Green</b>: display the green image-channel values.<p>"
                                       "<b>Blue</b>: display the blue image-channel values.<p>"));

    m_scaleBG = new TQHButtonGroup(gboxSettings);
    m_scaleBG->setExclusive(true);
    m_scaleBG->setFrameShape(TQFrame::NoFrame);
    m_scaleBG->setInsideMargin( 0 );
    TQWhatsThis::add( m_scaleBG, i18n("<p>Select the histogram scale here.<p>"
                                     "If the image's maximal counts are small, you can use the linear scale.<p>"
                                     "Logarithmic scale can be used when the maximal counts are big; "
                                     "if it is used, all values (small and large) will be visible on the graph."));
    
    TQPushButton *linHistoButton = new TQPushButton( m_scaleBG );
    TQToolTip::add( linHistoButton, i18n( "<p>Linear" ) );
    m_scaleBG->insert(linHistoButton, Digikam::HistogramWidget::LinScaleHistogram);
    TDEGlobal::dirs()->addResourceType("histogram-lin", TDEGlobal::dirs()->kde_default("data") + "digikam/data");
    TQString directory = TDEGlobal::dirs()->findResourceDir("histogram-lin", "histogram-lin.png");
    linHistoButton->setPixmap( TQPixmap( directory + "histogram-lin.png" ) );
    linHistoButton->setToggleButton(true);
    
    TQPushButton *logHistoButton = new TQPushButton( m_scaleBG );
    TQToolTip::add( logHistoButton, i18n( "<p>Logarithmic" ) );
    m_scaleBG->insert(logHistoButton, Digikam::HistogramWidget::LogScaleHistogram);
    TDEGlobal::dirs()->addResourceType("histogram-log", TDEGlobal::dirs()->kde_default("data") + "digikam/data");
    directory = TDEGlobal::dirs()->findResourceDir("histogram-log", "histogram-log.png");
    logHistoButton->setPixmap( TQPixmap( directory + "histogram-log.png" ) );
    logHistoButton->setToggleButton(true);       

    TQHBoxLayout* l1 = new TQHBoxLayout();
    l1->addWidget(label1);
    l1->addWidget(m_channelCB);
    l1->addStretch(10);
    l1->addWidget(m_scaleBG);
    
    gridSettings->addMultiCellLayout(l1, 0, 0, 0, 4);

    // -------------------------------------------------------------

    TQVBox *histoBox   = new TQVBox(gboxSettings);
    m_histogramWidget = new Digikam::HistogramWidget(256, 140, histoBox, false, true, true);
    TQWhatsThis::add( m_histogramWidget, i18n("<p>Here you can see the target preview image histogram drawing "
                                             "of the selected image channel. This one is re-computed at any "
                                             "settings changes."));
    TQLabel *space = new TQLabel(histoBox);
    space->setFixedHeight(1);
    m_hGradient = new Digikam::ColorGradientWidget( Digikam::ColorGradientWidget::Horizontal, 10, histoBox );
    m_hGradient->setColors( TQColor( "black" ), TQColor( "white" ) );
    
    gridSettings->addMultiCellWidget(histoBox, 1, 2, 0, 4);

    // -------------------------------------------------------------
    
    m_correctionTools = new TQListBox(gboxSettings);
    m_correctionTools->setColumnMode(1);
    m_correctionTools->setVariableWidth(false);
    m_correctionTools->setVariableHeight(false);
    Digikam::ListBoxWhatsThis* whatsThis = new Digikam::ListBoxWhatsThis(m_correctionTools);

    TQPixmap pix = getThumbnailForEffect(AutoLevelsCorrection);
    Digikam::ListBoxPreviewItem *item = new Digikam::ListBoxPreviewItem(pix, i18n("Auto Levels"));
    whatsThis->add( item, i18n("<b>Auto Levels</b>:"
                               "<p>This option maximizes the tonal range in the Red, "
                               "Green, and Blue channels. It searches the image shadow and highlight "
                               "limit values and adjusts the Red, Green, and Blue channels "
                               "to a full histogram range.</p>"));
    m_correctionTools->insertItem(item, AutoLevelsCorrection);

    pix = getThumbnailForEffect(NormalizeCorrection);
    item = new Digikam::ListBoxPreviewItem(pix, i18n("Normalize"));
    whatsThis->add( item, i18n("<b>Normalize</b>:"
                               "<p>This option 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.</p>"));
    m_correctionTools->insertItem(item, NormalizeCorrection);

    pix = getThumbnailForEffect(EqualizeCorrection);
    item = new Digikam::ListBoxPreviewItem(pix, i18n("Equalize"));
    whatsThis->add( item, i18n("<b>Equalize</b>:"
                               "<p>This option 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.</p>"));
    m_correctionTools->insertItem(item, EqualizeCorrection);

    pix = getThumbnailForEffect(StretchContrastCorrection);
    item = new Digikam::ListBoxPreviewItem(pix, i18n("Stretch Contrast"));
    whatsThis->add( item, i18n("<b>Stretch Contrast</b>:"
                               "<p>This option enhances the contrast and brightness "
                               "of the RGB values of an image by stretching the lowest "
                               "and highest values to their fullest range, adjusting "
                               "everything in between.</p>"));
    m_correctionTools->insertItem(item, StretchContrastCorrection);

    pix = getThumbnailForEffect(AutoExposureCorrection);
    item = new Digikam::ListBoxPreviewItem(pix, i18n("Auto Exposure"));
    whatsThis->add( item, i18n("<b>Auto Exposure</b>:"
                               "<p>This option enhances the contrast and brightness "
                               "of the RGB values of an image to calculate optimal "
                               "exposition and black level using image histogram "
                               "properties.</p>"));
    m_correctionTools->insertItem(item, AutoExposureCorrection);

    // -------------------------------------------------------------
    
    m_correctionTools->setFocus();
    gridSettings->addMultiCellWidget(m_correctionTools, 3, 3, 0, 4);
    gridSettings->setRowStretch(3, 10);
    setUserAreaWidget(gboxSettings);
   
    // -------------------------------------------------------------
    
    connect(m_channelCB, TQT_SIGNAL(activated(int)),
            this, TQT_SLOT(slotChannelChanged(int)));

    connect(m_scaleBG, TQT_SIGNAL(released(int)),
            this, TQT_SLOT(slotScaleChanged(int)));

    connect(m_previewWidget, TQT_SIGNAL(spotPositionChangedFromTarget( const Digikam::DColor &, const TQPoint & )),
            this, TQT_SLOT(slotColorSelectedFromTarget( const Digikam::DColor & )));

    connect(m_correctionTools, TQT_SIGNAL(highlighted(int)),
            this, TQT_SLOT(slotEffect()));
    
    connect(m_previewWidget, TQT_SIGNAL(signalResized()),
            this, TQT_SLOT(slotEffect()));
}

ImageEffect_AutoCorrection::~ImageEffect_AutoCorrection()
{
    m_histogramWidget->stopHistogramComputation();

    if (m_destinationPreviewData) 
       delete [] m_destinationPreviewData;
       
    delete m_histogramWidget;
    delete m_previewWidget;
}

void ImageEffect_AutoCorrection::slotChannelChanged(int channel)
{
    switch(channel)
    {
        case LuminosityChannel:
            m_histogramWidget->m_channelType = Digikam::HistogramWidget::ValueHistogram;
            m_hGradient->setColors( TQColor( "black" ), TQColor( "white" ) );
            break;
    
        case RedChannel:
            m_histogramWidget->m_channelType = Digikam::HistogramWidget::RedChannelHistogram;
            m_hGradient->setColors( TQColor( "black" ), TQColor( "red" ) );
            break;
    
        case GreenChannel:         
            m_histogramWidget->m_channelType = Digikam::HistogramWidget::GreenChannelHistogram;
            m_hGradient->setColors( TQColor( "black" ), TQColor( "green" ) );
            break;
    
        case BlueChannel:         
            m_histogramWidget->m_channelType = Digikam::HistogramWidget::BlueChannelHistogram;
            m_hGradient->setColors( TQColor( "black" ), TQColor( "blue" ) );
            break;
    }

    m_histogramWidget->repaint(false);
}

void ImageEffect_AutoCorrection::slotScaleChanged(int scale)
{
    m_histogramWidget->m_scaleType = scale;
    m_histogramWidget->repaint(false);
}

void ImageEffect_AutoCorrection::slotColorSelectedFromTarget( const Digikam::DColor &color )
{
    m_histogramWidget->setHistogramGuideByColor(color);
}

void ImageEffect_AutoCorrection::readUserSettings()
{
    TDEConfig* config = kapp->config();
    config->setGroup("autocorrection Tool Dialog");
    m_channelCB->setCurrentItem(config->readNumEntry("Histogram Channel", 0));    // Luminosity.
    m_scaleBG->setButton(config->readNumEntry("Histogram Scale", Digikam::HistogramWidget::LogScaleHistogram));
    m_correctionTools->setCurrentItem(config->readNumEntry("Auto Correction Filter", AutoLevelsCorrection));
    slotChannelChanged(m_channelCB->currentItem());
    slotScaleChanged(m_scaleBG->selectedId());
}

void ImageEffect_AutoCorrection::writeUserSettings()
{
    TDEConfig* config = kapp->config();
    config->setGroup("autocorrection Tool Dialog");
    config->writeEntry("Histogram Channel", m_channelCB->currentItem());
    config->writeEntry("Histogram Scale", m_scaleBG->selectedId());
    config->writeEntry("Auto Correction Filter", m_correctionTools->currentItem());
    config->sync();
}

void ImageEffect_AutoCorrection::resetValues()
{
    m_correctionTools->blockSignals(true);
    m_correctionTools->setCurrentItem(AutoLevelsCorrection);
    m_correctionTools->blockSignals(false);
}

void ImageEffect_AutoCorrection::slotEffect()
{
    kapp->setOverrideCursor( KCursor::waitCursor() );

    m_histogramWidget->stopHistogramComputation();

    if (m_destinationPreviewData) 
       delete [] m_destinationPreviewData;
       
    Digikam::ImageIface* iface      = m_previewWidget->imageIface();
    uchar *m_destinationPreviewData = iface->getPreviewImage();
    int w                           = iface->previewWidth();
    int h                           = iface->previewHeight();
    bool sb                         = iface->previewSixteenBit();

    autoCorrection(m_destinationPreviewData, w, h, sb, m_correctionTools->currentItem());

    iface->putPreviewImage(m_destinationPreviewData);
    m_previewWidget->updatePreview();

    // Update histogram.
   
    m_histogramWidget->updateData(m_destinationPreviewData, w, h, sb, 0, 0, 0, false);

    kapp->restoreOverrideCursor();
}

TQPixmap ImageEffect_AutoCorrection::getThumbnailForEffect(AutoCorrectionType type)
{
    Digikam::DImg thumb = m_thumbnailImage.copy();
    autoCorrection(thumb.bits(), thumb.width(), thumb.height(), thumb.sixteenBit(), type);
    return (thumb.convertToPixmap());
}


void ImageEffect_AutoCorrection::finalRendering()
{
    kapp->setOverrideCursor( KCursor::waitCursor() );
    Digikam::ImageIface* iface = m_previewWidget->imageIface();
    uchar *data                = iface->getOriginalImage();
    int w                      = iface->originalWidth();
    int h                      = iface->originalHeight();
    bool sb                    = iface->originalSixteenBit();

    if (data)
    {
       int type = m_correctionTools->currentItem();
       autoCorrection(data, w, h, sb, type);
       TQString name;
       
       switch (type)
       {
          case AutoLevelsCorrection:
             name = i18n("Auto Levels");
          break;

          case NormalizeCorrection:
             name = i18n("Normalize");
          break;

          case EqualizeCorrection:
             name = i18n("Equalize");
          break;

          case StretchContrastCorrection:
             name = i18n("Stretch Contrast");
          break;

          case AutoExposureCorrection:
             name = i18n("Auto Exposure");
          break;
       }
                                                  
       iface->putOriginalImage(name, data);
       delete [] data;
    }

    kapp->restoreOverrideCursor();
    accept();
}

void ImageEffect_AutoCorrection::autoCorrection(uchar *data, int w, int h, bool sb, int type)
{
    Digikam::DImgImageFilters filter;

    switch (type)
    {
        case AutoLevelsCorrection:
            filter.autoLevelsCorrectionImage(data, w, h, sb);
            break;
        
        case NormalizeCorrection:
            filter.normalizeImage(data, w, h, sb);
            break;
        
        case EqualizeCorrection:
            filter.equalizeImage(data, w, h, sb);
            break;
        
        case StretchContrastCorrection:
            filter.stretchContrastImage(data, w, h, sb);
            break;

        case AutoExposureCorrection:
            Digikam::WhiteBalance wbFilter(sb);
            double blackLevel;
            double exposureLevel;
            wbFilter.autoExposureAdjustement(data, w, h, sb, blackLevel, exposureLevel);
            wbFilter.whiteBalance(data, w, h, sb, blackLevel, exposureLevel);            
        break;
    }
}

}  // NameSpace DigikamImagesPluginCore