summaryrefslogtreecommitdiffstats
path: root/src/imageplugins/inpainting/inpaintingtool.cpp
blob: 2ada52bf93b4b5160c8e62b3e4a0f6373fda4e69 (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
/* ============================================================
 *
 * 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-2009 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++ includes.

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

// TQt includes.

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

// KDE includes.

#include <tdeaboutdata.h>
#include <tdeapplication.h>
#include <kcursor.h>
#include <tdefiledialog.h>
#include <tdeglobalsettings.h>
#include <khelpmenu.h>
#include <kiconloader.h>
#include <tdelocale.h>
#include <tdemessagebox.h>
#include <tdepopupmenu.h>
#include <kprogress.h>
#include <kstandarddirs.h>
#include <kurllabel.h>

// Local includes.

#include "daboutdata.h"
#include "ddebug.h"
#include "dimgthreadedfilter.h"
#include "imageiface.h"
#include "imagewidget.h"
#include "editortoolsettings.h"
#include "greycstorationsettings.h"
#include "greycstorationwidget.h"
#include "greycstorationiface.h"
#include "inpaintingtool.h"
#include "inpaintingtool.moc"

using namespace Digikam;

namespace DigikamInPaintingImagesPlugin
{

InPaintingTool::InPaintingTool(TQObject* parent)
              : EditorToolThreaded(parent)
{
    setName("inpainting");
    setToolName(i18n("Inpainting"));
    setToolIcon(SmallIcon("inpainting"));

    m_isComputed = false;

    m_previewWidget = new ImageWidget("inpainting Tool", 0,
                                      i18n("<p>Here you can see the image selection preview with "
                                           "inpainting applied."),
                                           true, ImageGuideWidget::HVGuideMode, false, true);
    setToolView(m_previewWidget);

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

    m_gboxSettings = new EditorToolSettings(EditorToolSettings::Default|
                                            EditorToolSettings::Try|
                                            EditorToolSettings::Load|
                                            EditorToolSettings::SaveAs|
                                            EditorToolSettings::Ok|
                                            EditorToolSettings::Cancel);
    TQGridLayout* gridSettings = new TQGridLayout(m_gboxSettings->plainPage(), 2, 1);
    m_mainTab = new TQTabWidget( m_gboxSettings->plainPage() );

    TQWidget* firstPage = new TQWidget( m_mainTab );
    TQGridLayout* grid  = new TQGridLayout( firstPage, 2, 2);
    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->setMargin(m_gboxSettings->spacingHint());
    grid->setSpacing(m_gboxSettings->spacingHint());
    grid->setRowStretch(1, 10);

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

    m_settingsWidget = new GreycstorationWidget(m_mainTab);

    gridSettings->addMultiCellWidget(m_mainTab,                               0, 0, 1, 1);
    gridSettings->addMultiCellWidget(new TQLabel(m_gboxSettings->plainPage()), 1, 1, 1, 1);
    gridSettings->setMargin(m_gboxSettings->spacingHint());
    gridSettings->setSpacing(m_gboxSettings->spacingHint());
    gridSettings->setRowStretch(1, 10);

    setToolSettings(m_gboxSettings);
    init();

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

    connect(cimgLogoLabel, TQ_SIGNAL(leftClickedURL(const TQString&)),
            this, TQ_SLOT(processCImgURL(const TQString&)));

    connect(m_inpaintingTypeCB, TQ_SIGNAL(activated(int)),
            this, TQ_SLOT(slotResetValues(int)));

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

    GreycstorationSettings defaults;
    defaults.setInpaintingDefaultSettings();
    m_settingsWidget->setDefaultSettings(defaults);
}

InPaintingTool::~InPaintingTool()
{
}

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

void InPaintingTool::readSettings()
{
    TDEConfig* config = kapp->config();
    config->setGroup("inpainting Tool");

    GreycstorationSettings settings;
    GreycstorationSettings defaults;
    defaults.setInpaintingDefaultSettings();

    settings.fastApprox = config->readBoolEntry("FastApprox", defaults.fastApprox);
    settings.interp     = config->readNumEntry("Interpolation", defaults.interp);
    settings.amplitude  = config->readDoubleNumEntry("Amplitude", defaults.amplitude);
    settings.sharpness  = config->readDoubleNumEntry("Sharpness", defaults.sharpness);
    settings.anisotropy = config->readDoubleNumEntry("Anisotropy", defaults.anisotropy);
    settings.alpha      = config->readDoubleNumEntry("Alpha", defaults.alpha);
    settings.sigma      = config->readDoubleNumEntry("Sigma", defaults.sigma);
    settings.gaussPrec  = config->readDoubleNumEntry("GaussPrec", defaults.gaussPrec);
    settings.dl         = config->readDoubleNumEntry("Dl", defaults.dl);
    settings.da         = config->readDoubleNumEntry("Da", defaults.da);
    settings.nbIter     = config->readNumEntry("Iteration", defaults.nbIter);
    settings.tile       = config->readNumEntry("Tile", defaults.tile);
    settings.btile      = config->readNumEntry("BTile", defaults.btile);
    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 InPaintingTool::writeSettings()
{
    GreycstorationSettings settings = m_settingsWidget->getSettings();
    TDEConfig* config = kapp->config();
    config->setGroup("inpainting Tool");
    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);
    m_previewWidget->writeSettings();
    config->sync();
}

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

    slotResetSettings();
}

void InPaintingTool::slotResetSettings()
{
    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 InPaintingTool::processCImgURL(const TQString& url)
{
    TDEApplication::kApplication()->invokeBrowser(url);
}

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

    ImageIface iface(0, 0);
    uchar *data     = iface.getOriginalImage();
    m_originalImage = 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();

    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);

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

void InPaintingTool::prepareFinal()
{
    if (!m_isComputed)
    {
        prepareEffect();
    }
    else
    {
        Digikam::DImgThreadedFilter::EventData *eventData = new Digikam::DImgThreadedFilter::EventData();
        eventData->progress  = 100;
        eventData->starting  = false;
        eventData->success   = true;
        TQApplication::postEvent(this, new TQCustomEvent(TQEvent::User, eventData));
    }
}

void InPaintingTool::putPreviewData()
{
    ImageIface* iface               = m_previewWidget->imageIface();
    GreycstorationSettings settings = m_settingsWidget->getSettings();

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

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

void InPaintingTool::putFinalData()
{
    ImageIface iface(0, 0);

    if (!m_isComputed)
        m_cropImage = filter()->getTargetImage();

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

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

void InPaintingTool::slotLoadSettings()
{
    KURL loadInpaintingFile = KFileDialog::getOpenURL(TDEGlobalSettings::documentPath(),
                                            TQString( "*" ), kapp->activeWindow(),
                                            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(kapp->activeWindow(),
                        i18n("\"%1\" is not a Photograph Inpainting settings text file.")
                        .arg(loadInpaintingFile.fileName()));
           file.close();
           return;
        }
    }
    else
        KMessageBox::error(kapp->activeWindow(), 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 InPaintingTool::slotSaveAsSettings()
{
    KURL saveRestorationFile = KFileDialog::getSaveURL(TDEGlobalSettings::documentPath(),
                                            TQString( "*" ), kapp->activeWindow(),
                                            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(kapp->activeWindow(), i18n("Cannot save settings to the Photograph Inpainting text file."));

    file.close();
}

}  // NameSpace DigikamInPaintingImagesPlugin