-
Notifications
You must be signed in to change notification settings - Fork 0
/
colorpicker.cpp
executable file
·2386 lines (2244 loc) · 72 KB
/
colorpicker.cpp
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
// Copyright 2022-present Contributors to the colorpicker project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/mikaelsundell/colorpicker
#include "colorpicker.h"
#include "picker.h"
#include "dragger.h"
#include "editor.h"
#include "eventfilter.h"
#include "icctransform.h"
#include "mac.h"
#include <QAction>
#include <QActionGroup>
#include <QBuffer>
#include <QClipboard>
#include <QColorSpace>
#include <QDateTime>
#include <QDesktopServices>
#include <QDir>
#include <QFileInfo>
#include <QMenu>
#include <QMimeData>
#include <QMouseEvent>
#include <QPainter>
#include <QPointer>
#include <QPrinter>
#include <QScreen>
#include <QSettings>
#include <QStandardPaths>
#include <QTextDocument>
#include <QTextTable>
#include <QUrl>
#include <QWindow>
// stdc++
#include <random>
// opencv
#include <opencv2/opencv.hpp>
#include <opencv2/core/utils/logger.hpp>
// generated files
#include "ui_about.h"
#include "ui_colorpicker.h"
class ColorpickerPrivate : public QObject
{
Q_OBJECT
public:
enum RgbChannel
{
R, G, B
};
enum HsvChannel
{
H, S, V
};
enum HslChannel
{
HslH, HslS, HslL
};
enum Format
{
Int8bit,
Int10bit,
Float,
Hex,
Percentage
};
enum Display
{
Hsv,
Hsl
};
enum Mode
{
None,
Pick,
Drag
};
public:
ColorpickerPrivate();
void init();
void stylesheet();
void update();
void view();
void widget();
void buttons();
void profile();
void blank();
void activate();
void deactivate();
void dropEvent(QDropEvent* event);
bool eventFilter(QObject* object, QEvent* event);
bool blocked();
void loadSettings();
void saveSettings();
public Q_SLOTS:
void toggleDisplay();
void togglePin(bool checked);
void toggleActive(bool checked);
void pick();
void drag();
void pickClosed();
void dragClosed();
void togglePick();
void toggleDrag();
void copyRGB();
void copyHSV();
void copyHSL();
void copyHEX();
void copyIccProfile();
void copyColor();
void as8bitValues();
void as10bitValues();
void asFloatValues();
void asHexValues();
void asPercentageValues();
void asHSVValues();
void asHSLValues();
void magnify1x();
void magnify2x();
void magnify3x();
void magnify4x();
void magnify5x();
void capture1();
void capture2();
void capture4();
void capture8();
void capture16();
void capture32();
void capture64();
void toggleMouseLocation();
void iccConvertProfileChanged(int index);
void toggleColors();
void toggleRGB();
void toggleR();
void toggleG();
void toggleB();
void toggleHSV();
void toggleH();
void toggleS();
void toggleV();
void next();
void previous();
void apertureChanged(int value);
void markerSizeChanged(int value);
void backgroundOpacityChanged(int value);
void angleChanged(int value);
void iqlineChanged(int state);
void zoomChanged(int state);
void saturationChanged(int state);
void segmentedChanged(int state);
void labelsChanged(int state);
void editorChanged(int value);
void pdf();
void clear();
void about();
void openGithubReadme();
void openGithubIssues();
Q_SIGNALS:
void readOnly(bool readOnly);
public:
class About : public QDialog
{
public: About(QWidget *parent = nullptr)
: QDialog(parent)
{
QScopedPointer<Ui_About> about;
about.reset(new Ui_About());
about->setupUi(this);
about->name->setText(MACOSX_BUNDLE_BUNDLE_NAME);
about->version->setText(MACOSX_BUNDLE_LONG_VERSION_STRING);
about->copyright->setText(MACOSX_BUNDLE_COPYRIGHT);
QString url = GITHUBURL;
about->github->setText(QString("Github project: <a href='%1'>%1</a>").arg(url));
about->github->setTextFormat(Qt::RichText);
about->github->setTextInteractionFlags(Qt::TextBrowserInteraction);
about->github->setOpenExternalLinks(true);
QFile file(":/files/resources/Copyright.txt");
file.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream in(&file);
QString text = in.readAll();
file.close();
about->licenses->setText(text);
}
};
class State
{
public:
QColor color;
QRect rect;
int magnify;
QImage image;
QPoint cursor;
QPoint origin;
int displayNumber;
QString iccProfile;
};
class Edit
{
public:
enum Type
{
Rgb,
Hsv
};
RgbChannel rgbChannel;
HsvChannel hsvChannel;
Type type;
};
class Palette
{
public:
QList<QColor> colors;
QList<QPoint> positions;
};
QRect grabRect(QPoint cursor);
QImage grabBuffer(QRect rect);
Palette grabPalette(QImage image);
bool underMouse(QWidget* widget);
float channelRgb(QColor color, RgbChannel channel);
float channelHsv(QColor color, HsvChannel channel);
float channelHsl(QColor color, HslChannel channel);
QString formatRgb(QColor color, RgbChannel channel);
QString formatHsv(QColor color, HsvChannel channel);
QString formatHsl(QColor color, HslChannel channel);
QString asFloat(float channel);
QString asHex(int channel);
QString asPercentage(float channel);
QString asDegree(float channel);
QByteArray asBase64(const QImage& image, QString format);
cv::Mat asBGR(const cv::Mat& mat);
cv::Mat asFloat32(const cv::Mat& mat);
QColor asColor(const cv::Vec3f& vec);
QList<QPair<QColor,QPair<QString,QString>>> asColors();
int width;
int height;
int aperture;
int magnify;
int displayNumber;
QString iccProfile;
QString iccCursorProfile;
QPoint cursor;
bool active;
bool mouselocation;
Format format;
Display display;
Mode mode;
State state;
Edit edit;
int opencvk;
int opencvcolors;
qsizetype selected;
QRect dragrect;
QSize size;
QList<State> states;
QPointer<Colorpicker> window;
QList<QColor> dragcolors;
QList<QPoint> dragpositions;
QScopedPointer<Picker> picker;
QScopedPointer<Dragger> dragger;
QScopedPointer<Editor> editor;
QScopedPointer<Eventfilter> displayfilter;
QScopedPointer<Eventfilter> colorsfilter;
QScopedPointer<Ui_Colorpicker> ui;
};
ColorpickerPrivate::ColorpickerPrivate()
: width(128)
, height(128)
, aperture(50)
, magnify(1)
, active(true)
, mouselocation(true)
, format(Format::Int8bit)
, display(Display::Hsv)
, mode(Mode::None)
, opencvk(20)
, opencvcolors(8)
, selected(-1)
{
}
void
ColorpickerPrivate::init()
{
mac::setDarkAppearance();
// icc profile
ICCTransform* transform = ICCTransform::instance();
QDir resources(QApplication::applicationDirPath() + "/../Resources");
QString inputProfile = resources.filePath("sRGB2014.icc"); // built-in Qt input profile
transform->setInputProfile(inputProfile);
profile();
// ui
ui.reset(new Ui_Colorpicker());
ui->setupUi(window);
// layout
// needed to keep .ui fixed size from setupUi
window->setFixedSize(window->size());
// utils
picker.reset(new Picker(window.data()));
dragger.reset(new Dragger(window.data()));
// editor
editor.reset(new Editor(window.data()));
editor->setObjectName("editor");
// settings
loadSettings();
// resources
QDir iccfiles(QApplication::applicationDirPath() + "/../ICCProfiles");
ui->iccColorProfile->insertSeparator(ui->iccColorProfile->count());
for(QFileInfo iccfile : iccfiles.entryInfoList( QStringList( "*.icc" )))
{
ui->iccColorProfile->addItem
("Convert to " + iccfile.baseName(), QVariant::fromValue(iccfile.filePath()));
if (iccfile.filePath() == iccProfile) {
ui->iccColorProfile->setCurrentIndex(ui->iccColorProfile->count() - 1);
}
}
// actions
ui->toggleActive->setDefaultAction(ui->active);
ui->togglePin->setDefaultAction(ui->pin);
// event filter
window->installEventFilter(this);
// display filter
displayfilter.reset(new Eventfilter);
ui->displayBar->installEventFilter(displayfilter.data());
// color filter
colorsfilter.reset(new Eventfilter);
ui->colorsBar->installEventFilter(colorsfilter.data());
// connect
connect(displayfilter.data(), &Eventfilter::pressed, ui->toggleDisplay, &QPushButton::click);
connect(colorsfilter.data(), &Eventfilter::pressed, ui->toggleColors, &QPushButton::click);
connect(ui->toggleDisplay, &QPushButton::pressed, this, &ColorpickerPrivate::toggleDisplay);
connect(ui->toggleColors, &QPushButton::pressed, this, &ColorpickerPrivate::toggleColors);
connect(ui->iccColorProfile, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ColorpickerPrivate::iccConvertProfileChanged);
connect(ui->r, &Label::triggered, this, &ColorpickerPrivate::toggleR);
connect(ui->g, &Label::triggered, this, &ColorpickerPrivate::toggleG);
connect(ui->b, &Label::triggered, this, &ColorpickerPrivate::toggleB);
connect(ui->h, &Label::triggered, this, &ColorpickerPrivate::toggleH);
connect(ui->s, &Label::triggered, this, &ColorpickerPrivate::toggleS);
connect(ui->v, &Label::triggered, this, &ColorpickerPrivate::toggleV);
connect(ui->next, &QAction::triggered, this, &ColorpickerPrivate::next);
connect(ui->previous, &QAction::triggered, this, &ColorpickerPrivate::previous);
connect(ui->pick, &QAction::triggered, this, &ColorpickerPrivate::togglePick);
connect(ui->togglePick, &QPushButton::released, this, &ColorpickerPrivate::togglePick);
connect(ui->drag, &QAction::triggered, this, &ColorpickerPrivate::toggleDrag);
connect(ui->toggleDrag, &QPushButton::released, this, &ColorpickerPrivate::toggleDrag);
connect(ui->copyRGBAsText, &QAction::triggered, this, &ColorpickerPrivate::copyRGB);
connect(ui->copyHSVAsText, &QAction::triggered, this, &ColorpickerPrivate::copyHSV);
connect(ui->copyHSLAsText, &QAction::triggered, this, &ColorpickerPrivate::copyHSL);
connect(ui->copyHexAsText, &QAction::triggered, this, &ColorpickerPrivate::copyHEX);
connect(ui->copyIccAsText, &QAction::triggered, this, &ColorpickerPrivate::copyIccProfile);
connect(ui->copyColorAsBitmap, &QAction::triggered, this, &ColorpickerPrivate::copyColor);
connect(ui->active, &QAction::toggled, this, &ColorpickerPrivate::toggleActive);
connect(ui->pin, &QAction::toggled, this, &ColorpickerPrivate::togglePin);
connect(ui->as8bitValues, &QAction::triggered, this, &ColorpickerPrivate::as8bitValues);
connect(ui->as10bitValues, &QAction::triggered, this, &ColorpickerPrivate::as10bitValues);
connect(ui->asFloatValues, &QAction::triggered, this, &ColorpickerPrivate::asFloatValues);
connect(ui->asHexadecimalValues, &QAction::triggered, this, &ColorpickerPrivate::asHexValues);
connect(ui->asPercentageValues, &QAction::triggered, this, &ColorpickerPrivate::asPercentageValues);
{
QActionGroup* actions = new QActionGroup(this);
actions->setExclusive(true);
{
actions->addAction(ui->as8bitValues);
actions->addAction(ui->as10bitValues);
actions->addAction(ui->asFloatValues);
actions->addAction(ui->asHexadecimalValues);
actions->addAction(ui->asPercentageValues);
}
}
connect(ui->asHSVDisplay, &QAction::triggered, this, &ColorpickerPrivate::asHSVValues);
connect(ui->asHSLDisplay, &QAction::triggered, this, &ColorpickerPrivate::asHSLValues);
{
QActionGroup* actions = new QActionGroup(this);
actions->setExclusive(true);
{
actions->addAction(ui->asHSVDisplay);
actions->addAction(ui->asHSLDisplay);
}
}
connect(ui->magnify1x, &QAction::triggered, this, &ColorpickerPrivate::magnify1x);
connect(ui->magnify2x, &QAction::triggered, this, &ColorpickerPrivate::magnify2x);
connect(ui->magnify3x, &QAction::triggered, this, &ColorpickerPrivate::magnify3x);
connect(ui->magnify4x, &QAction::triggered, this, &ColorpickerPrivate::magnify4x);
connect(ui->magnify5x, &QAction::triggered, this, &ColorpickerPrivate::magnify5x);
{
QActionGroup* actions = new QActionGroup(this);
actions->setExclusive(true);
for(QAction* action : ui->magnify->actions())
actions->addAction(action);
}
connect(ui->capture1, &QAction::triggered, this, &ColorpickerPrivate::capture1);
connect(ui->capture2, &QAction::triggered, this, &ColorpickerPrivate::capture2);
connect(ui->capture4, &QAction::triggered, this, &ColorpickerPrivate::capture4);
connect(ui->capture8, &QAction::triggered, this, &ColorpickerPrivate::capture8);
connect(ui->capture16, &QAction::triggered, this, &ColorpickerPrivate::capture16);
connect(ui->capture32, &QAction::triggered, this, &ColorpickerPrivate::capture32);
connect(ui->capture64, &QAction::triggered, this, &ColorpickerPrivate::capture64);
{
QActionGroup* actions = new QActionGroup(this);
actions->setExclusive(true);
for(QAction* action : ui->captureColors->actions())
actions->addAction(action);
}
connect(ui->toggleMouseLocation, &QAction::triggered, this, &ColorpickerPrivate::toggleMouseLocation);
connect(ui->aperture, &QSlider::valueChanged, this, &ColorpickerPrivate::apertureChanged);
connect(ui->markerSize, &QSlider::valueChanged, this, &ColorpickerPrivate::markerSizeChanged);
connect(ui->backgroundOpacity, &QSlider::valueChanged, this, &ColorpickerPrivate::backgroundOpacityChanged);
connect(ui->angle, &QSlider::valueChanged, this, &ColorpickerPrivate::angleChanged);
connect(ui->iqline, &QCheckBox::stateChanged, this, &ColorpickerPrivate::iqlineChanged);
connect(ui->zoom, &QCheckBox::stateChanged, this, &ColorpickerPrivate::zoomChanged);
connect(ui->saturation, &QCheckBox::stateChanged, this, &ColorpickerPrivate::saturationChanged);
connect(ui->segmented, &QCheckBox::stateChanged, this, &ColorpickerPrivate::segmentedChanged);
connect(ui->labels, &QCheckBox::stateChanged, this, &ColorpickerPrivate::labelsChanged);
connect(ui->clear, &QAction::triggered, this, &ColorpickerPrivate::clear);
connect(ui->toggleClear, &QPushButton::pressed, this, &ColorpickerPrivate::clear);
connect(ui->pdf, &QPushButton::pressed, this, &ColorpickerPrivate::pdf);
connect(ui->about, &QAction::triggered, this, &ColorpickerPrivate::about);
connect(ui->openGithubReadme, &QAction::triggered, this, &ColorpickerPrivate::openGithubReadme);
connect(ui->openGithubIssues, &QAction::triggered, this, &ColorpickerPrivate::openGithubIssues);
connect(picker.get(), &Picker::triggered, this, &ColorpickerPrivate::pick);
connect(picker.get(), &Picker::closed, this, &ColorpickerPrivate::pickClosed);
connect(dragger.get(), &Dragger::triggered, this, &ColorpickerPrivate::drag);
connect(dragger.get(), &Dragger::closed, this, &ColorpickerPrivate::dragClosed);
connect(editor.get(), &Editor::valueChanged, this, &ColorpickerPrivate::editorChanged);
// signals
connect(this, &ColorpickerPrivate::readOnly, ui->r, &Label::setReadOnly);
connect(this, &ColorpickerPrivate::readOnly, ui->g, &Label::setReadOnly);
connect(this, &ColorpickerPrivate::readOnly, ui->b, &Label::setReadOnly);
connect(this, &ColorpickerPrivate::readOnly, ui->h, &Label::setReadOnly);
connect(this, &ColorpickerPrivate::readOnly, ui->s, &Label::setReadOnly);
connect(this, &ColorpickerPrivate::readOnly, ui->v, &Label::setReadOnly);
size = window->size();
// stylesheet
stylesheet();
// debug
#ifdef QT_DEBUG
QMenu* menu = ui->menubar->addMenu("Debug");
{
QAction* action = new QAction("Reload stylesheet...", this);
action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_S));
menu->addAction(action);
connect(action, &QAction::triggered, [&]() {
this->stylesheet();
});
}
#endif
}
void
ColorpickerPrivate::stylesheet()
{
QDir resources(QApplication::applicationDirPath());
QFile stylesheet(resources.absolutePath() + "/../Resources/App.css");
stylesheet.open(QFile::ReadOnly);
QString qss = stylesheet.readAll();
QRegularExpression hslRegex("hsl\\(\\s*(\\d+)\\s*,\\s*(\\d+)%\\s*,\\s*(\\d+)%\\s*\\)");
QString transformqss = qss;
QRegularExpressionMatchIterator i = hslRegex.globalMatch(transformqss);
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
if (match.hasMatch()) {
if (!match.captured(1).isEmpty() &&
!match.captured(2).isEmpty() &&
!match.captured(3).isEmpty())
{
int h = match.captured(1).toInt();
int s = match.captured(2).toInt();
int l = match.captured(3).toInt();
QColor color = QColor::fromHslF(h / 360.0f, s / 100.0f, l / 100.0f);
// icc profile
ICCTransform* transform = ICCTransform::instance();
color = transform->map(color.rgb());
QString hsl = QString("hsl(%1, %2%, %3%)")
.arg(color.hue() == -1 ? 0 : color.hue())
.arg(static_cast<int>(color.hslSaturationF() * 100))
.arg(static_cast<int>(color.lightnessF() * 100));
transformqss.replace(match.captured(0), hsl);
}
}
}
qApp->setStyleSheet(transformqss);
}
QRect
ColorpickerPrivate::grabRect(QPoint pos)
{
int w = int(width / float(magnify));
int h = int(height / float(magnify));
int x = pos.x() - w / 2;
int y = pos.y() - h / 2;
if (width % magnify > 0)
++w;
if (height % magnify > 0)
++h;
return(QRect(x, y, w, h));
}
QImage
ColorpickerPrivate::grabBuffer(QRect rect)
{
int x = rect.x();
int y = rect.y();
int w = rect.width();
int h = rect.height();
WId id = 0;
if (mode == Mode::Pick) {
id = picker->winId();
}
if (mode == Mode::Drag) {
id = dragger->winId();
}
QImage buffer;
const QBrush blackBrush = QBrush(Qt::black);
buffer = mac::grabImage(x, y, w, h, id);
QRegion geom(x, y, w, h);
QRect screenRect;
const auto screens = QGuiApplication::screens();
for (auto screen : screens)
{
screenRect |= screen->geometry();
}
geom -= screenRect;
const auto rectsInRegion = geom.rectCount();
if (rectsInRegion > 0) {
QPainter p(&buffer);
p.translate(-x, -y);
p.setPen(Qt::NoPen);
p.setBrush(blackBrush);
p.drawRects(geom.begin(), rectsInRegion);
p.end();
}
return buffer;
}
ColorpickerPrivate::Palette
ColorpickerPrivate::grabPalette(QImage image)
{
Palette palette;
QImage buffer = image.convertToFormat(QImage::Format_RGB888); // opencv need 24-bit RGB only
qreal dpr = buffer.devicePixelRatio();
int width = buffer.width();
int height = buffer.height();
if (width > 5 && height > 5)
{
cv::utils::logging::setLogLevel(cv::utils::logging::LOG_LEVEL_SILENT);
cv::Mat matrix = cv::Mat(buffer.height(), buffer.width(), CV_8UC3, (void*)buffer.constBits(), buffer.bytesPerLine());
matrix = asFloat32(asBGR(matrix));
cv::Mat serialized = matrix.reshape(1, static_cast<int>(matrix.total()));
serialized.convertTo(serialized, CV_32F);
// perform k-means clustering
std::vector<int> labels;
cv::Mat centers;
cv::kmeans(serialized, opencvk, labels, cv::TermCriteria(cv::TermCriteria::MAX_ITER + cv::TermCriteria::EPS, 10, 1.0), 3, cv::KMEANS_PP_CENTERS, centers);
// diversity selection logic
// calculates pairwise distances between all cluster centers to identify similar colors.
std::vector<std::vector<double>> distances(centers.rows, std::vector<double>(centers.rows, 0));
for (int i = 0; i < centers.rows; ++i) {
for (int j = i + 1; j < centers.rows; ++j) {
distances[i][j] = distances[j][i] = cv::norm(centers.row(i) - centers.row(j));
}
}
std::set<int> selectedindices;
while (selectedindices.size() < opencvcolors)
{
double maxmindistance = 0;
int candidateindex = -1;
for (int i = 0; i < centers.rows; ++i) {
if (selectedindices.find(i) != selectedindices.end()) continue;
double minDistance = std::numeric_limits<double>::max();
for (int j : selectedindices) {
minDistance = std::min(minDistance, distances[i][j]);
}
if (minDistance > maxmindistance) {
maxmindistance = minDistance;
candidateindex = i;
}
}
if (candidateindex != -1) {
selectedindices.insert(candidateindex);
} else {
break;
}
}
// create a matrix for the selected diverse centers.
cv::Mat diversecenters(static_cast<int>(selectedindices.size()), centers.cols, centers.type());
int idx = 0;
for (int selectedIndex : selectedindices) {
centers.row(selectedIndex).copyTo(diversecenters.row(idx++));
}
// reassign each pixel in the image to the color of the closest diverse center.
for (size_t i = 0; i < labels.size(); ++i) {
int clusterIndex = static_cast<int>(std::distance(selectedindices.begin(), selectedindices.find(labels[i])));
for (int j = 0; j < 3; ++j) { // assuming 3 channels
serialized.at<float>(static_cast<int>(i * 3 + j)) = diversecenters.at<float>(clusterIndex, j);
}
}
const int seed = 101010; // ultimate question of life in binary
std::mt19937 gen(seed);
// convert to hue and get pixel (x, y) coordinates
std::unordered_map<int, std::vector<int>> indicesmap;
for (int i = 0; i < labels.size(); ++i) {
indicesmap[labels[i]].push_back(i);
}
for (int i = 0; i < diversecenters.rows; ++i) {
cv::Vec3f center = diversecenters.at<cv::Vec3f>(i);
auto it = std::next(selectedindices.begin(), i);
if (it != selectedindices.end()) {
int originallabel = *it;
std::vector<int> &indices = indicesmap[originallabel];
std::uniform_int_distribution<> dis(0, static_cast<int>(indices.size() - 1));
int index = indices[dis(gen)];
QPoint position = QPoint(index % width, index / width) / dpr;
{
palette.colors.push_back(asColor(center));
palette.positions.push_back(position);
}
}
}
}
return palette;
}
bool
ColorpickerPrivate::underMouse(QWidget* widget) {
QPoint pos = widget->mapFromGlobal(QCursor::pos());
return widget->rect().contains(pos);
}
void
ColorpickerPrivate::update()
{
if (!active)
return;
QRect grab = grabRect(cursor);
QImage buffer = grabBuffer(grab);
QScreen* screen = QGuiApplication::screenAt(cursor);
qreal dpr = buffer.devicePixelRatio();
// paint with device pixel ratio and apply
// transforms and fill in user space
QColor color;
QRect rect(
(grab.width() - aperture) / 2,
(grab.height() - aperture) / 2,
aperture, aperture
);
int colorR=0, colorG=0, colorB=0;
for(int cx = rect.left(); cx <= rect.right(); cx++)
{
for(int cy = rect.top(); cy <= rect.bottom(); cy++)
{
QColor pixel = buffer.pixel(cx * dpr, cy * dpr);
colorR += pixel.red();
colorG += pixel.green();
colorB += pixel.blue();
}
}
int size = rect.width() * rect.height();
color = QColor(colorR / size, colorG / size, colorB / size);
// icc profile
ICCTransform* transform = ICCTransform::instance();
QString iccCurrentProfile = iccProfile;
if (!iccCurrentProfile.length()) {
iccCurrentProfile = iccCursorProfile;
}
if (iccCurrentProfile != iccCursorProfile) {
color = transform->map(color.rgb(), iccCursorProfile, iccCurrentProfile);
buffer = transform->map(buffer, iccCursorProfile, iccCurrentProfile);
}
// state
{
state = State{
color,
rect,
magnify,
buffer,
cursor,
screen->geometry().topLeft(),
displayNumber,
iccCurrentProfile
};
}
view();
widget();
}
void
ColorpickerPrivate::view()
{
qreal dpr = state.image.devicePixelRatio();
const QBrush blackBrush = QBrush(Qt::black);
QColor color;
QImage image;
// icc profile
ICCTransform* transform = ICCTransform::instance();
if (state.iccProfile != transform->outputProfile()) {
color = transform->map(state.color.rgb(), state.iccProfile, transform->outputProfile());
image = transform->map(state.image, state.iccProfile, transform->outputProfile());
}
else {
color = state.color;
image = state.image;
}
// pixmap
QPixmap pixmap(width * dpr, height * dpr);
pixmap.setDevicePixelRatio(dpr);
{
QPainter p(&pixmap);
p.save();
p.scale(state.magnify, state.magnify);
p.fillRect(QRect(0, 0, width, height), blackBrush);
p.drawImage(0, 0, image);
p.setPen(QPen(Qt::NoPen));
p.fillRect(state.rect, QBrush(color));
QTransform transform = p.transform();
p.restore();
QRect frame = QRect(transform.mapRect(state.rect));
p.setPen(QPen(Qt::gray));
p.setBrush(QBrush(Qt::NoBrush));
p.drawRect(frame);
p.end();
}
ui->view->setPixmap(pixmap);
}
void
ColorpickerPrivate::widget()
{
// color profile
{
if (!active) {
int index = ui->iccColorProfile->findData(state.iccProfile);
if (index > 0) {
if (ui->iccColorProfile->currentIndex() != index) {
ui->iccColorProfile->setCurrentIndex(ui->iccColorProfile->findData(state.iccProfile));
}
} else {
ui->iccColorProfile->setCurrentIndex(0);
}
}
}
// display
{
ui->display->setText(QString("Display #%1").arg(state.displayNumber));
QFontMetrics metrics(ui->iccProfile->font());
QString text = metrics.elidedText(QFileInfo(iccCursorProfile).baseName(), Qt::ElideRight, ui->iccProfile->width());
ui->iccProfile->setText(text);
}
// rgb
{
ui->r->setText(QString("%1").arg(formatRgb(state.color, RgbChannel::R)));
ui->g->setText(QString("%1").arg(formatRgb(state.color, RgbChannel::G)));
ui->b->setText(QString("%1").arg(formatRgb(state.color, RgbChannel::B)));
}
// hsv
{
if (display == Display::Hsv) {
ui->display1Label->setText("H");
ui->display2Label->setText("S");
ui->display3Label->setText("V");
ui->h->setText(QString("%1").arg(formatHsv(state.color, HsvChannel::H)));
ui->s->setText(QString("%1").arg(formatHsv(state.color, HsvChannel::S)));
ui->v->setText(QString("%1").arg(formatHsv(state.color, HsvChannel::V)));
} else {
ui->display1Label->setText("H");
ui->display2Label->setText("S");
ui->display3Label->setText("L");
ui->h->setText(QString("%1").arg(formatHsl(state.color, HslChannel::HslH)));
ui->s->setText(QString("%1").arg(formatHsl(state.color, HslChannel::HslS)));
ui->v->setText(QString("%1").arg(formatHsl(state.color, HslChannel::HslL)));
}
}
// mouse location
{
QPoint screenpos = state.cursor - state.origin;
ui->mouseLocation->setText(QString("(%1, %2)").arg(screenpos.x()).arg(screenpos.y()));
}
// color wheel
{
QList<QPair<QColor,QPair<QString,QString>>> colors = asColors();
if (active) {
if (dragcolors.count() > 0) {
QString iccCurrentProfile = iccProfile;
if (!iccCurrentProfile.length()) {
iccCurrentProfile = iccCursorProfile;
}
for(QColor dragcolor : dragcolors) {
QColor color = dragcolor;
colors.push_back(QPair<QColor,QPair<QString,QString>>(
color.rgb(),
QPair<QString,QString>(QFileInfo(iccCurrentProfile).baseName(), iccCurrentProfile)
));
}
}
else
{
colors.push_back(QPair<QColor,QPair<QString,QString>>(
state.color,
QPair<QString,QString>(QFileInfo(state.iccProfile).baseName(), state.iccProfile)
));
}
// push current state, use as selected
ui->colorWheel->setColors(colors, true);
}
else
{
// restore colors, skip selected
ui->colorWheel->setColors(colors, false);
}
}
QColor color = state.color;
// icc profile
ICCTransform* transform = ICCTransform::instance();
if (state.iccProfile != transform->outputProfile()) {
color = transform->map(color.rgb(), state.iccProfile, iccCursorProfile); // use display picker display
}
// picker
if (mode == Mode::Pick) {
picker->setColor(color);
picker->update(cursor);
}
// drag
if (mode == Mode::Drag) {
dragger->update(cursor);
}
buttons();
}
void
ColorpickerPrivate::buttons()
{
bool enabled = false;
if (states.size()) {
enabled = true;
}
ui->clear->setEnabled(enabled);
ui->toggleClear->setEnabled(enabled);
ui->copyRGBAsText->setEnabled(enabled);
ui->copyHSVAsText->setEnabled(enabled);
ui->copyHSLAsText->setEnabled(enabled);
ui->copyHexAsText->setEnabled(enabled);
ui->copyIccAsText->setEnabled(enabled);
ui->copyColorAsBitmap->setEnabled(enabled);
ui->pdf->setEnabled(enabled);
}
void
ColorpickerPrivate::profile()
{
QString outputProfile = mac::grabIccProfileUrl(window->winId());
// icc profile
ICCTransform* transform = ICCTransform::instance();
transform->setOutputProfile(outputProfile);
}
void
ColorpickerPrivate::blank()
{
qreal dpr = window->devicePixelRatio();
const QBrush blackBrush = QBrush(Qt::black);
// image
QImage image(width * dpr, height * dpr, QImage::Format_ARGB32_Premultiplied);
image.setDevicePixelRatio(dpr);
{
QPainter p(&image);
p.fillRect(QRect(0, 0, width, height), blackBrush);
p.end();
}
QColor color = Qt::black;
// icc profile
QString iccCurrentProfile = iccProfile;
if (!iccCurrentProfile.length()) {
iccCurrentProfile = iccCursorProfile;
}
// state
state = State{
color,
QRect(),
magnify,
image,
QPoint(),
QPoint(),
displayNumber,
iccCurrentProfile
};
ui->view->setPixmap(QPixmap::fromImage(image));
// rgb
{
ui->r->setText(QString("%1").arg(formatRgb(color, RgbChannel::R)));
ui->g->setText(QString("%1").arg(formatRgb(color, RgbChannel::G)));
ui->b->setText(QString("%1").arg(formatRgb(color, RgbChannel::B)));
}
// hsv
{
ui->h->setText(QString("%1").arg(formatHsv(color, HsvChannel::H)));
ui->s->setText(QString("%1").arg(formatHsv(color, HsvChannel::S)));
ui->v->setText(QString("%1").arg(formatHsv(color, HsvChannel::V)));
}
ui->mouseLocation->setText(QString("(%1, %2)").arg(0).arg(0));
ui->colorWheel->setColors(asColors());
}
void
ColorpickerPrivate::activate()
{
ui->active->setChecked(true);
}
void
ColorpickerPrivate::deactivate()
{
ui->active->setChecked(false);
}
void
ColorpickerPrivate::dropEvent(QDropEvent *event)
{
const QMimeData *mimeData = event->mimeData();
QList<QImage> images;
if (mimeData->hasUrls()) {
QList<QUrl> urls = mimeData->urls();
for (const QUrl &url : urls) {
if (url.isLocalFile()) {
QString filePath = url.toLocalFile();
QImage image(filePath);
if (!image.isNull()) {
if (image.format() != QImage::Format_ARGB32_Premultiplied) {
image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied); // works better with QPixmap draw_iamge
}
images.append(image);
}
}
}
}
if (mimeData->hasImage()) {
images.append(qvariant_cast<QImage>(event->mimeData()->imageData()));
}
// icc profile
ICCTransform* transform = ICCTransform::instance();
QString iccCurrentProfile = iccProfile;
if (!iccCurrentProfile.length()) {
iccCurrentProfile = iccCursorProfile;
}
for(QImage image : images) {
QColorSpace colorspace = image.colorSpace(); // embedded colorspace
if (colorspace.isValid()) {
QString iccColorspaceProfile = colorspace.description();
if (iccCurrentProfile != iccColorspaceProfile) {
image = transform->map(image, colorspace, iccCurrentProfile);
}
} else {
if (iccCurrentProfile != iccCursorProfile) {
image = transform->map(image, iccCursorProfile, iccCurrentProfile);
}
}
Palette palette = grabPalette(image);
if (palette.colors.size()) {
for (int i = 0; i < palette.colors.size(); ++i) {
QPoint pos = palette.positions.at(i);
QRect grab = grabRect(pos);
QImage buffer = image.copy(grab);
// paint with device pixel ratio and apply
// transforms and fill in user space
QColor color = palette.colors.at(i);
QRect rect(
(grab.width() - aperture) / 2,
(grab.height() - aperture) / 2,
aperture, aperture
);
// state
State drag = State{
color,
rect,
magnify,
buffer,
pos,
QPoint(0, 0),
displayNumber,
iccCurrentProfile