-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
453 lines (401 loc) · 17.1 KB
/
mainwindow.cpp
File metadata and controls
453 lines (401 loc) · 17.1 KB
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
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QMenu * mnFile = new QMenu("File"); // создаём меню Файл
// —-------— здесь добавляем пункт меню и подключаем его к слоту----
QAction *opnAction = new QAction("Open",mnFile);
QAction *saveAction = new QAction("Save",mnFile);
//далее соединяем сигналы со слотами и добавляем действия в менюбар
connect(opnAction, SIGNAL(triggered()), this, SLOT(loadImage()));
mnFile->addAction(opnAction);
connect(saveAction, SIGNAL(triggered()), this, SLOT(saveImage()));
mnFile->addAction(saveAction);
ui->menuBar->addMenu(mnFile); // Добавляем пункты меню в menuBar, т.е. те, которые будут отображаться в гл. окне
connect(ui->verticalSlider, SIGNAL(valueChanged(int)),
this, SLOT(vSliderChanged(int)));
connect(ui->horizontalSlider, SIGNAL(valueChanged(int)),
this, SLOT(hSliderChanged(int)));
connect(ui->sourceBtn, SIGNAL(toggled(bool)),
this, SLOT(radio()));
connect(ui->resultBtn, SIGNAL(toggled(bool)),
this, SLOT(radio()));
connect(ui->applyButton, SIGNAL(clicked()),
this, SLOT(saveSlot()));
ui->toolBox->removeItem(0);
ui->toolBox->removeItem(0);
//а теперь попробуем сделать так, чтобы большие картинки не разрывали юзеру экран
QDesktopWidget desktop;
maxHeight=desktop.availableGeometry().height() - 240;
maxWidth=desktop.availableGeometry().width() - 460;
//qDebug() << maxHeight << maxWidth;
/*---------------------------------------------------*/
qDebug() << "been here";
QPixmap pixmap = QPixmap(":placeholders/background.png");
image = pixmap.toImage();
result = image;
imageScaled = reduceSize(image);
resultScaled = reduceSize(result);
setupEverything(image, imageScaled);
sourceGist=makeGist(image,4);
resultGist=sourceGist;
ui->gistLabel->setPixmap(sourceGist);
colorer = new Colorer();
ui->toolBox->addItem(colorer, "Color correction");
colorer->setSource(this);
colorer->setImage(image);
curver = new Curver();
ui->toolBox->addItem(curver, "Curves");
curver->setSource(this);
curver->setImage(image);
sAver = new SimpleAver();
ui->toolBox->addItem(sAver, "Simple noise reduction");
sAver->setSource(this);
sAver->setImage(image);
aAver = new AdaptAver();
ui->toolBox->addItem(aAver, "Adaptive noise reduction");
aAver->setSource(this);
aAver->setImage(image);
bilaterator = new Bilaterator();
ui->toolBox->addItem(bilaterator, "Bilateral filter");
bilaterator->setSource(this);
bilaterator->setImage(image);
sharper = new Sharper();
ui->toolBox->addItem(sharper, "Edge sharpening");
sharper->setSource(this);
sharper->setImage(image);
edger = new Edger();
ui->toolBox->addItem(edger, "Edge detection");
edger->setSource(this);
edger->setImage(image);
//добавим окно "Help"
QMenu * mnHelp = new QMenu("Help"); // создаём меню Файл
QAction *aboutAction = new QAction("How to use",mnHelp);
connect(aboutAction, SIGNAL(triggered()), this, SLOT(makeHelp()));
mnHelp->addAction(aboutAction);
QAction *realAboutAction = new QAction("About",mnHelp);
connect(realAboutAction, SIGNAL(triggered()), this, SLOT(makeAbout()));
mnHelp->addAction(realAboutAction);
ui->menuBar->addMenu(mnHelp);
}
MainWindow::~MainWindow()
{
delete ui;
delete edger;
delete sharper;
delete bilaterator;
delete aAver;
delete sAver;
delete curver;
delete colorer;
}
void MainWindow::makeHelp()
{ //делаем оконшко about
whatIsThis = new HelpWindow();
whatIsThis->show();
whatIsThis->setWindowTitle("How to use");
}
void MainWindow::makeAbout()
{
aboutThis = new AboutWindow();
aboutThis->show();
aboutThis->setWindowTitle("About");
}
void MainWindow::loadImage() //загружаем картинку
{ //qDebug() << "loadimage";
QString fileName = QFileDialog::getOpenFileName(0, tr("Open"), "",
tr("Images") +
"(*.jpg *.jpeg *.png *.bmp "
"*.gif *.pbm *.pgm *.ppm "
"*.tiff *.xbm *.xpm);;" +
tr("All Files") +
"(*.*)");
if (fileName.isEmpty())
return;
image = QImage(fileName);
if (image.format() == QImage::Format_Invalid)
return;
result = QImage(image);
imageScaled = reduceSize(image);
resultScaled = reduceSize(result);
showImage(&imageScaled);
setupEverything(image, imageScaled);
sourceGist=makeGist(image,4);
ui->gistLabel->setPixmap(sourceGist);
sAver->setImage(image);
aAver->setImage(image);
curver->setImage(image);
sharper->setImage(image);
edger->setImage(image);
colorer->setImage(image);
bilaterator->setImage(image);
}
void MainWindow::setupEverything(QImage image, QImage imageScaled)
{ //настраиваем классы и интерфейс при загрузке новой картинки
ui->horizontalSlider->setMaximumWidth(imageScaled.width()-1);
ui->horizontalSlider->setMaximum(image.width()-1);
ui->verticalSlider->setMaximumHeight(imageScaled.height()-1);
ui->verticalSlider->setMaximum(image.height()-1);
ui->horizontalSlider->setValue(image.width()/2);
ui->verticalSlider->setValue(image.height()/2);
//ui->cutLabel->setPixmap(doCut(&image,10));
}
QImage MainWindow::reduceSize(QImage picture)
{ // эта функция делает уменьшенную большую картинку для отображения в интерфейсе
//qDebug() << "we've got " << picture.height() << picture.width();
if ((picture.width()>maxWidth)&&(picture.height()>maxHeight))
{
if ((picture.width()-maxWidth)>=(picture.height()-maxHeight))
picture=picture.scaledToWidth(maxWidth, Qt::SmoothTransformation);
if ((picture.width()-maxWidth)<(picture.height()-maxHeight))
picture=picture.scaledToHeight(maxHeight, Qt::SmoothTransformation);
//qDebug() << "derp1";
return picture;
}
if (picture.width()>maxWidth)
{
picture=picture.scaledToWidth(maxWidth, Qt::SmoothTransformation);
//qDebug() << "derp2";
}
if (picture.height()>maxHeight)
{
picture=picture.scaledToHeight(maxHeight, Qt::SmoothTransformation);
//qDebug() << "derp3";
}
//qDebug() << "returning " << picture.height() << picture.width();
return picture;
}
void MainWindow::saveImage()
{//сохраняем картинку
QString fileName = QFileDialog::getSaveFileName(0, tr("Save"), "",
tr("PNG") +
"(*.png);;" +
tr("All Files") +
"(*.*)");
if (fileName.isEmpty())
return;
result.save(fileName);
}
void MainWindow::showImage(QImage *picture)
{ //функция, отрисовывающая исходное изображение
QPixmap pixmap; //картинку нельзя показать когда она в QImage
pixmap.convertFromImage(*picture); //конвертируем картинку в pixmap
ui->display->setPixmap(pixmap); //отображаем пиксмап в лейбле
}
QPixmap MainWindow::doCut(QImage *picture, int y)
{ //рисуем срез функции яркости
cuty=y;
QList<int> line; //заготовка под линию пикселей
for (int x = 0; x < picture->width(); x++)
{
QColor pixel = picture->pixel(x, y);
line << pixel.lightness(); //записываем пиксели
}
QImage tgist(picture->width(), 64, QImage::Format_RGB32);
for (int x = 0; x < tgist.width(); x++)
{//рисуем снизу вверх
for (int y = 0; y < line[x]/4; y++)
{ //сначала черным
tgist.setPixel(x, y, qRgb(0,0,0));//pixel.rgb());
}
for (int y = line[x]/4; y < tgist.height(); y++)
{ //потом белым
tgist.setPixel(x, y, qRgb(255,255,255));//pixel.rgb());
}
}
tgist = tgist.mirrored(0,1); //отзеркаливаем потому что пока что картинка перевернута
tgist = tgist.scaled(imageScaled.width(), tgist.height(), Qt::IgnoreAspectRatio);
QPixmap pixmap;
pixmap.convertFromImage(tgist);
return pixmap; //и возвращаем
}
QPixmap MainWindow::doCutVert(QImage *picture, int a)
{ //рисуем срез функции яркости
cutx=a;
QList<int> line; //заготовка под линию пикселей
for (int y = 0; y < picture->height(); y++)
{
QColor pixel = picture->pixel(a, y);
line << pixel.lightness(); //записываем пиксели
}
QImage tgist(64, picture->height(), QImage::Format_RGB32);
//qDebug() << tgist.height() << tgist.width();
for (int y = 0; y < tgist.height(); y++)
{//рисуем снизу вверх
//if (y>=600) qDebug() << tgist.height() << tgist.width();
for (int x = 0; x < line[y]/4; x++)
{ //сначала черным
tgist.setPixel(x, y, qRgb(0,0,0));//pixel.rgb());
}
for (int x = line[y]/4; x < tgist.width(); x++)
{ //потом белым
tgist.setPixel(x, y, qRgb(255,255,255));//pixel.rgb());
}
}
tgist = tgist.scaled(tgist.width(), imageScaled.height(), Qt::IgnoreAspectRatio);
QPixmap pixmap;
pixmap.convertFromImage(tgist);
return pixmap; //и возвращаем
}
QPixmap MainWindow::makeGist(QImage &greyPic, int mode)
{//функция, пересчитывающая яркости пикселей и выдающая гистограмму
QImage gist(256,128, QImage::Format_RGB32);
for (int z=1; z<3; z++)
{
for (int j = 0; j < 255; j++)
{ //сначала всех пикселей ноль штук
array[j] = 0;
};
for (int x = 0; x < greyPic.width(); x++)
for (int y = 0; y < greyPic.height(); y++)
{ //для каждого пикселя
QColor pixel = greyPic.pixel(x, y); //получаем пиксель
int color;
if (mode == 1)
color = pixel.red(); //считываем его яркость в переменную color
if (mode == 2)
color = pixel.green(); //считываем его яркость в переменную color
if (mode == 3)
color = pixel.blue(); //считываем его яркость в переменную color
else
color = pixel.lightness(); //считываем его яркость в переменную color
array[color] = array[color]+1; //и увеличиваем счетчик соответствующей яркости на 1
}
int big = 0; //найдем самый большой элемент массива
for (int m = 0; m < 256; m++)
{
if (array[m] >= big)
big = array[m]; //и запишем его в переменную big
} //теперь нам нужно нормализовать массив чтобы самый большой элемент не превысил 255
double coef = 0;
coef = 128.0 / big; //для этого посчитали нормализующий коэффициент
for (int m = 0; m < 256; m++)
{
array[m] = array[m]*coef; //применяем его ко всем элементам
}
for (int x = 0; x < gist.width(); x++)
for (int y = 0; y < gist.height(); y++)
{ // сначала закрашиваем её белым цветом
QColor pixel = QColor(255,255,255);//gist.pixel(x, y);
gist.setPixel(x, y, pixel.rgb());
}
for (int x = 0; x < gist.width(); x++)
if (array[x]>>0) //теперь нанесем черные столбцы толщиной в 1 пиксель
for (int y = 0; y < array[x]; y++) //столбцы имеют высоту от нуля до значения распространенности соответствующей яркости
{ //т.е. например если 50% всех пикселей имеют яркость 120 то 120й столбик будет иметь высоту в 50% * 255 = 127
QColor pixel = QColor(0,0,0);
gist.setPixel(x, y, pixel.rgb());
}
gist = gist.mirrored(0,1); //зеркалим гистограмму чтобы не была вверх ногами
}
QPixmap pixmap; //картинку нельзя показать когда она в QImage
pixmap.convertFromImage(gist); //конвертируем картинку в pixmap
return pixmap;
}
void MainWindow::drawCurveOnGist(QList<int> sourceArray)
{
QImage gist = sourceGist.toImage();
for (int x = 0; x < gist.width(); x++)
{ //сверху синей линией нанесём чистый график функции
QColor pixel = gist.pixel(x, 10);
pixel.setRed(0);
pixel.setGreen(128);
pixel.setBlue(255);
gist.setPixel(x,sourceArray[x]/2, pixel.rgb());
}
QPixmap pixmap; //картинку нельзя показать когда она в QImage
pixmap.convertFromImage(gist); //конвертируем картинку в pixmap
ui->gistLabel->setPixmap(pixmap);
}
QList<int> MainWindow::retrieveAray()
{ //функция возвращает массив array в виде QList
QList<int> list;
for (int i=1; i<256; i++)
{
list << array[i];
}
return list;
}
void MainWindow::vSliderChanged(int value)
{
QImage* link;
if (ui->sourceBtn->isChecked()==true)
link = ℑ
else
link = &result;
ui->horizCutLabel->setPixmap(doCut(link, value));
}
void MainWindow::hSliderChanged(int value)
{
QImage* link;
if (ui->sourceBtn->isChecked()==true)
link = ℑ
else
link = &result;
ui->vertiCutLabel->setPixmap(doCutVert(link, value));
}
void MainWindow::radio()
{ //функция срабатывающая при переключении на исходное изображение
if (ui->sourceBtn->isChecked())
{
output = image;
showImage(&imageScaled); //показываем картинку
ui->horizCutLabel->setPixmap(doCut(&image,cuty));
ui->vertiCutLabel->setPixmap(doCutVert(&image,cutx));
ui->gistLabel->setPixmap(sourceGist);
}
if (ui->resultBtn->isChecked())
{
output = result;
showImage(&resultScaled); //показываем картинку
ui->horizCutLabel->setPixmap(doCut(&result,cuty));
ui->vertiCutLabel->setPixmap(doCutVert(&result,cutx));
ui->gistLabel->setPixmap(resultGist);
}
}
void MainWindow::saveSlot()
{ //сохранить изменения, внесенные фильтрами
image=result;
imageScaled=resultScaled;
showImage(&imageScaled);
ui->horizCutLabel->setPixmap(doCut(&result,cuty));
ui->vertiCutLabel->setPixmap(doCutVert(&result,cutx));
resultGist=makeGist(result,4);
sourceGist=resultGist;
ui->gistLabel->setPixmap(resultGist);
sAver->setImage(image);
aAver->setImage(image);
curver->setImage(image);
sharper->setImage(image);
edger->setImage(image);
colorer->setImage(image);
bilaterator->setImage(image);
colorer->dropSliders();
}
void MainWindow::receiveResult(QImage picture)
{ //получить результат
result = picture;
resultScaled = reduceSize(result);
showImage(&resultScaled);
ui->resultBtn->setChecked(true);
ui->horizCutLabel->setPixmap(doCut(&result,cuty));
ui->vertiCutLabel->setPixmap(doCutVert(&result,cutx));
resultGist=makeGist(result,4);
sourceGist=makeGist(image,4);
ui->gistLabel->setPixmap(resultGist);
}
void MainWindow::setMaxProgress(int value)
{
ui->progressBar->setMaximum(value);
ui->toolBox->setDisabled(1);
}
void MainWindow::setProgress(int value)
{
ui->progressBar->setValue(value);
if (ui->progressBar->value()==ui->progressBar->maximum())
ui->toolBox->setDisabled(0);
qApp->processEvents();
}