summaryrefslogtreecommitdiffstats
path: root/digikam/imageplugins/inpainting/imageeffect_inpainting.cpp
blob: 99dee40a05bee17e7842165563abbec0847e737a (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
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
/* ============================================================
 *
 * This file is a part of digiKam project
 * http://www.digikam.org
 *
 * Date        : 2005-03-30
 * Description : a digiKam image editor plugin to inpaint
 *               a photograph
 * 
 * Copyright (C) 2005-2008 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.
 * 
 * ============================================================ */

// C++ include.

#include <cstdio>
#include <cmath>
#include <cstring>

// TQt includes.

#include <tqvgroupbox.h>
#include <tqlabel.h>
#include <tqpushbutton.h>
#include <tqtooltip.h>
#include <tqwhatsthis.h>
#include <tqlayout.h>
#include <tqframe.h>
#include <tqcheckbox.h>
#include <tqcombobox.h>
#include <tqtabwidget.h>
#include <tqtimer.h>
#include <tqevent.h>
#include <tqpixmap.h>
#include <tqpainter.h>
#include <tqbrush.h>
#include <tqfile.h>

// KDE includes.

#include <kcursor.h>
#include <kurllabel.h>
#include <klocale.h>
#include <kaboutdata.h>
#include <khelpmenu.h>
#include <kiconloader.h>
#include <kapplication.h>
#include <kpopupmenu.h>
#include <kfiledialog.h>
#include <kstandarddirs.h>
#include <kprogress.h>
#include <kmessagebox.h>
#include <knuminput.h>
#include <kglobalsettings.h>
#include <kpassivepopup.h>

// Local includes.

#include "version.h"
#include "ddebug.h"
#include "imageiface.h"
#include "greycstorationsettings.h"
#include "greycstorationwidget.h"
#include "greycstorationiface.h"
#include "imageeffect_inpainting.h"
#include "imageeffect_inpainting.moc"

namespace DigikamInPaintingImagesPlugin
{

class InPaintingPassivePopup : public KPassivePopup
{
public:

    InPaintingPassivePopup(TQWidget* parent) : KPassivePopup(parent), m_parent(parent) {}

protected:

    virtual void positionSelf() { move(m_parent->x() + 30, m_parent->y() + 30); }

private:

    TQWidget* m_parent;
};

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

void ImageEffect_InPainting::inPainting(TQWidget* parent)
{
    // -- check if we actually have a selection --------------------

    Digikam::ImageIface iface(0, 0);

    int w = iface.selectedWidth();
    int h = iface.selectedHeight();

    if (!w || !h)
    {
        InPaintingPassivePopup* popup = new InPaintingPassivePopup(parent);
        popup->setView(i18n("Inpainting Photograph Tool"),
                       i18n("You need to select a region to inpaint to use "
                            "this tool"));
        popup->setAutoDelete(true);
        popup->setTimeout(2500);
        popup->show();
        return;
    }

    // -- run the dlg ----------------------------------------------
    
    ImageEffect_InPainting_Dialog dlg(parent);
    dlg.exec();
}

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

ImageEffect_InPainting_Dialog::ImageEffect_InPainting_Dialog(TQWidget* parent)
                             : Digikam::ImageGuideDlg(parent, i18n("Photograph Inpainting"), 
                                                      "inpainting", true, true, false, 
                                                      Digikam::ImageGuideWidget::HVGuideMode, 
                                                      0, true, true, true)
{
    m_isComputed = false;
    TQString whatsThis;

    TDEAboutData* about = new TDEAboutData("digikam",
                                       I18N_NOOP("Photograph Inpainting"),
                                       digikam_version,
                                       I18N_NOOP("A digiKam image plugin to inpaint a photograph."),
                                       TDEAboutData::License_GPL,
                                       "(c) 2005-2008, Gilles Caulier",
                                       0,
                                       "http://www.digikam.org");

    about->addAuthor("Gilles Caulier", I18N_NOOP("Author and maintainer"),
                     "caulier dot gilles at gmail dot com");

    about->addAuthor("David Tschumperle", I18N_NOOP("CImg library"), 0,
                     "http://cimg.sourceforge.net");

    about->addAuthor("Gerhard Kulzer", I18N_NOOP("Feedback and plugin polishing"),
                     "gerhard at kulzer.net");

    setAboutData(about);

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

    TQWidget *gboxSettings     = new TQWidget(plainPage());
    TQGridLayout* gridSettings = new TQGridLayout(gboxSettings, 2, 1, spacingHint());
    m_mainTab = new TQTabWidget( gboxSettings );

    TQWidget* firstPage = new TQWidget( m_mainTab );
    TQGridLayout* grid  = new TQGridLayout( firstPage, 2, 2, marginHint(), spacingHint());
    m_mainTab->addTab( firstPage, i18n("Preset") );

    KURLLabel *cimgLogoLabel = new KURLLabel(firstPage);
    cimgLogoLabel->setText(TQString());
    cimgLogoLabel->setURL("http://cimg.sourceforge.net");
    TDEGlobal::dirs()->addResourceType("logo-cimg", TDEGlobal::dirs()->kde_default("data") + "digikam/data");
    TQString directory = TDEGlobal::dirs()->findResourceDir("logo-cimg", "logo-cimg.png");
    cimgLogoLabel->setPixmap( TQPixmap( directory + "logo-cimg.png" ) );
    TQToolTip::add(cimgLogoLabel, i18n("Visit CImg library website"));

    TQLabel *typeLabel = new TQLabel(i18n("Filtering type:"), firstPage);
    typeLabel->setAlignment ( TQt::AlignRight | TQt::AlignVCenter);
    m_inpaintingTypeCB = new TQComboBox( false, firstPage );
    m_inpaintingTypeCB->insertItem( i18n("None") );
    m_inpaintingTypeCB->insertItem( i18n("Remove Small Artefact") );
    m_inpaintingTypeCB->insertItem( i18n("Remove Medium Artefact") );
    m_inpaintingTypeCB->insertItem( i18n("Remove Large Artefact") );
    TQWhatsThis::add( m_inpaintingTypeCB, i18n("<p>Select the filter preset to use for photograph restoration:<p>"
                                               "<b>None</b>: Most common values. Puts settings to default.<p>"
                                               "<b>Remove Small Artefact</b>: inpaint small image artefact like image glitch.<p>"
                                               "<b>Remove Medium Artefact</b>: inpaint medium image artefact.<p>"
                                               "<b>Remove Large Artefact</b>: inpaint image artefact like unwanted object.<p>"));

    grid->addMultiCellWidget(cimgLogoLabel, 0, 0, 1, 1);
    grid->addMultiCellWidget(typeLabel, 1, 1, 0, 0);
    grid->addMultiCellWidget(m_inpaintingTypeCB, 1, 1, 1, 1);
    grid->setRowStretch(1, 10);

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

    m_settingsWidget = new Digikam::GreycstorationWidget(m_mainTab);

    gridSettings->addMultiCellWidget(m_mainTab, 0, 0, 1, 1);
    gridSettings->addMultiCellWidget(new TQLabel(gboxSettings), 1, 1, 1, 1);
    setUserAreaWidget(gboxSettings);

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

    connect(cimgLogoLabel, TQT_SIGNAL(leftClickedURL(const TQString&)),
            this, TQT_SLOT(processCImgURL(const TQString&)));

    connect(m_inpaintingTypeCB, TQT_SIGNAL(activated(int)),
            this, TQT_SLOT(slotResetValues(int)));
}

ImageEffect_InPainting_Dialog::~ImageEffect_InPainting_Dialog()
{
}

void ImageEffect_InPainting_Dialog::renderingFinished()
{
    m_mainTab->setEnabled(true);
}

void ImageEffect_InPainting_Dialog::readUserSettings()
{
    KConfig* config = kapp->config();
    config->setGroup("inpainting Tool Dialog");

    Digikam::GreycstorationSettings settings;
    settings.fastApprox = config->readBoolEntry("FastApprox", true);
    settings.interp     = config->readNumEntry("Interpolation",
                          Digikam::GreycstorationSettings::NearestNeighbor);
    settings.amplitude  = config->readDoubleNumEntry("Amplitude", 20.0);
    settings.sharpness  = config->readDoubleNumEntry("Sharpness", 0.3);
    settings.anisotropy = config->readDoubleNumEntry("Anisotropy", 1.0);
    settings.alpha      = config->readDoubleNumEntry("Alpha", 0.8);
    settings.sigma      = config->readDoubleNumEntry("Sigma", 2.0);
    settings.gaussPrec  = config->readDoubleNumEntry("GaussPrec", 2.0);
    settings.dl         = config->readDoubleNumEntry("Dl", 0.8);
    settings.da         = config->readDoubleNumEntry("Da", 30.0);
    settings.nbIter     = config->readNumEntry("Iteration", 30);
    settings.tile       = config->readNumEntry("Tile", 512);
    settings.btile      = config->readNumEntry("BTile", 4);
    m_settingsWidget->setSettings(settings);

    int p = config->readNumEntry("Preset", NoPreset);
    m_inpaintingTypeCB->setCurrentItem(p);
    if (p == NoPreset)
        m_settingsWidget->setEnabled(true);
    else        
        m_settingsWidget->setEnabled(false);
}

void ImageEffect_InPainting_Dialog::writeUserSettings()
{
    Digikam::GreycstorationSettings settings = m_settingsWidget->getSettings();
    KConfig* config = kapp->config();
    config->setGroup("inpainting Tool Dialog");
    config->writeEntry("Preset", m_inpaintingTypeCB->currentItem());
    config->writeEntry("FastApprox", settings.fastApprox);
    config->writeEntry("Interpolation", settings.interp);
    config->writeEntry("Amplitude", settings.amplitude);
    config->writeEntry("Sharpness", settings.sharpness);
    config->writeEntry("Anisotropy", settings.anisotropy);
    config->writeEntry("Alpha", settings.alpha);
    config->writeEntry("Sigma", settings.sigma);
    config->writeEntry("GaussPrec", settings.gaussPrec);
    config->writeEntry("Dl", settings.dl);
    config->writeEntry("Da", settings.da);
    config->writeEntry("Iteration", settings.nbIter);
    config->writeEntry("Tile", settings.tile);
    config->writeEntry("BTile", settings.btile);
    config->sync();
}

void ImageEffect_InPainting_Dialog::slotResetValues(int i)
{
    if (i == NoPreset)
        m_settingsWidget->setEnabled(true);
    else        
        m_settingsWidget->setEnabled(false);

    resetValues();
}

void ImageEffect_InPainting_Dialog::resetValues()
{
    Digikam::GreycstorationSettings settings;
    settings.setInpaintingDefaultSettings();    

    switch(m_inpaintingTypeCB->currentItem())
    {
        case RemoveSmallArtefact:
            // We use default settings here.
            break;
        
        case RemoveMediumArtefact:
        {
            settings.amplitude = 50.0;
            settings.nbIter    = 50;
            break;
        }

        case RemoveLargeArtefact:
        {
            settings.amplitude = 100.0;
            settings.nbIter    = 100;
            break;
        }
    }

    m_settingsWidget->setSettings(settings);
}

void ImageEffect_InPainting_Dialog::processCImgURL(const TQString& url)
{
    TDEApplication::kApplication()->invokeBrowser(url);
}

void ImageEffect_InPainting_Dialog::prepareEffect()
{
    m_mainTab->setEnabled(false);

    Digikam::ImageIface iface(0, 0);
    uchar *data     = iface.getOriginalImage();
    m_originalImage = Digikam::DImg(iface.originalWidth(), iface.originalHeight(),
                                    iface.originalSixteenBit(), iface.originalHasAlpha(), data);
    delete [] data;

    // Selected area from the image and mask creation:
    //
    // We optimize the computation time to use the current selected area in image editor
    // and to create an inpainting mask with it. Because inpainting is done by interpolation
    // neighboor pixels which can be located far from the selected area, we need to ajust the
    // mask size in according with the parameter algorithms, especially 'amplitude'.
    // Mask size is computed like this :
    //
    // (image_size_x + 2*amplitude , image_size_y + 2*amplitude)
    

    TQRect selectionRect = TQRect(iface.selectedXOrg(), iface.selectedYOrg(),
                                iface.selectedWidth(), iface.selectedHeight());

    TQPixmap inPaintingMask(iface.originalWidth(), iface.originalHeight());
    inPaintingMask.fill(TQt::black);
    TQPainter p(&inPaintingMask);
    p.fillRect( selectionRect, TQBrush(TQt::white) );
    p.end();

    Digikam::GreycstorationSettings settings = m_settingsWidget->getSettings();

    int x1 = (int)(selectionRect.left()   - 2*settings.amplitude);
    int y1 = (int)(selectionRect.top()    - 2*settings.amplitude);
    int x2 = (int)(selectionRect.right()  + 2*settings.amplitude);
    int y2 = (int)(selectionRect.bottom() + 2*settings.amplitude);
    m_maskRect = TQRect(x1, y1, x2-x1, y2-y1);

    // Mask area normalization.
    // We need to check if mask area is out of image size else inpainting give strange results.

    if (m_maskRect.left()   < 0) m_maskRect.setLeft(0);
    if (m_maskRect.top()    < 0) m_maskRect.setTop(0);
    if (m_maskRect.right()  > iface.originalWidth())  m_maskRect.setRight(iface.originalWidth());
    if (m_maskRect.bottom() > iface.originalHeight()) m_maskRect.setBottom(iface.originalHeight());

    m_maskImage = inPaintingMask.convertToImage().copy(m_maskRect);
    m_cropImage = m_originalImage.copy(m_maskRect);

    m_threadedFilter = dynamic_cast<Digikam::DImgThreadedFilter *>(
                       new Digikam::GreycstorationIface(
                                    &m_cropImage,
                                    settings,
                                    Digikam::GreycstorationIface::InPainting, 
                                    0, 0,
                                    m_maskImage, this));
}

void ImageEffect_InPainting_Dialog::prepareFinal()
{
    if (!m_isComputed)
    {
        setProgressVisible(true);
        prepareEffect();
    }
    else
    {
        putFinalData();
        kapp->restoreOverrideCursor();
        accept();
    }
}

void ImageEffect_InPainting_Dialog::putPreviewData()
{
    Digikam::ImageIface* iface               = m_imagePreviewWidget->imageIface();
    Digikam::GreycstorationSettings settings = m_settingsWidget->getSettings();

    m_cropImage = m_threadedFilter->getTargetImage();
    TQRect cropSel((int)(2*settings.amplitude), (int)(2*settings.amplitude), 
                  iface->selectedWidth(), iface->selectedHeight());
    Digikam::DImg imDest = m_cropImage.copy(cropSel);

    iface->putPreviewImage((imDest.smoothScale(iface->previewWidth(),
                                               iface->previewHeight())).bits());
    m_imagePreviewWidget->updatePreview();
    m_isComputed = true;
}

void ImageEffect_InPainting_Dialog::putFinalData(void)
{
    Digikam::ImageIface iface(0, 0);
    
    if (!m_isComputed)
        m_cropImage = m_threadedFilter->getTargetImage();

    m_originalImage.bitBltImage(&m_cropImage, m_maskRect.left(), m_maskRect.top());

    iface.putOriginalImage(i18n("InPainting"), m_originalImage.bits());
}

void ImageEffect_InPainting_Dialog::slotUser3()
{
    KURL loadInpaintingFile = KFileDialog::getOpenURL(TDEGlobalSettings::documentPath(),
                                            TQString( "*" ), this,
                                            TQString( i18n("Photograph Inpainting Settings File to Load")) );
    if( loadInpaintingFile.isEmpty() )
       return;

    TQFile file(loadInpaintingFile.path());

    if ( file.open(IO_ReadOnly) )
    {
        if (!m_settingsWidget->loadSettings(file, TQString("# Photograph Inpainting Configuration File V2")))
        {
           KMessageBox::error(this,
                        i18n("\"%1\" is not a Photograph Inpainting settings text file.")
                        .arg(loadInpaintingFile.fileName()));
           file.close();
           return;
        }
    }
    else
        KMessageBox::error(this, i18n("Cannot load settings from the Photograph Inpainting text file."));

    file.close();
    m_inpaintingTypeCB->blockSignals(true);
    m_inpaintingTypeCB->setCurrentItem(NoPreset);
    m_inpaintingTypeCB->blockSignals(false);
    m_settingsWidget->setEnabled(true);             
}

void ImageEffect_InPainting_Dialog::slotUser2()
{
    KURL saveRestorationFile = KFileDialog::getSaveURL(TDEGlobalSettings::documentPath(),
                                            TQString( "*" ), this,
                                            TQString( i18n("Photograph Inpainting Settings File to Save")) );
    if( saveRestorationFile.isEmpty() )
       return;

    TQFile file(saveRestorationFile.path());

    if ( file.open(IO_WriteOnly) )
        m_settingsWidget->saveSettings(file, TQString("# Photograph Inpainting Configuration File V2"));
    else
        KMessageBox::error(this, i18n("Cannot save settings to the Photograph Inpainting text file."));

    file.close();
}

}  // NameSpace DigikamInPaintingImagesPlugin