16084
|
1 |
#include "tracer.h"
|
|
2 |
|
16092
|
3 |
#include <QJsonObject>
|
16084
|
4 |
#include <QRandomGenerator>
|
|
5 |
#include <QSvgGenerator>
|
|
6 |
|
16092
|
7 |
Tracer::Tracer(QObject *parent) : QObject{parent} {}
|
16084
|
8 |
|
|
9 |
double Tracer::bestSolution() const { return bestSolution_; }
|
|
10 |
|
16085
|
11 |
void Tracer::start(const QString &fileName) {
|
16084
|
12 |
qDebug() << "Starting using" << fileName;
|
|
13 |
|
|
14 |
bestSolution_ = 0;
|
|
15 |
solutions_.clear();
|
|
16 |
generation_.clear();
|
16085
|
17 |
referenceImage_ = QImage{};
|
16084
|
18 |
|
16085
|
19 |
referenceImage_.load(QUrl(fileName).toLocalFile());
|
16084
|
20 |
|
16085
|
21 |
if (referenceImage_.isNull()) {
|
16084
|
22 |
qDebug("Failed to load image");
|
|
23 |
return;
|
|
24 |
}
|
|
25 |
|
16092
|
26 |
referenceImage_ = referenceImage_.convertedTo(QImage::Format_RGBA8888);
|
|
27 |
|
16085
|
28 |
for (int i = 0; i < 600; ++i) {
|
16092
|
29 |
generation_.append(Solution{referenceImage_.size(), atoms_});
|
16084
|
30 |
}
|
|
31 |
}
|
|
32 |
|
|
33 |
void Tracer::step() {
|
16085
|
34 |
const auto size = generation_.size();
|
16092
|
35 |
const auto keepSize = 1;
|
|
36 |
const auto replaceSize = 10;
|
16085
|
37 |
const auto kept = generation_.mid(0, keepSize);
|
|
38 |
generation_ = generation_.mid(0, size - replaceSize);
|
|
39 |
|
16092
|
40 |
std::for_each(std::begin(generation_), std::end(generation_),
|
|
41 |
[](auto &s) { s.mutate(); });
|
|
42 |
|
16085
|
43 |
for (int i = 0; i < replaceSize; ++i) {
|
16092
|
44 |
generation_.append(Solution{referenceImage_.size(), atoms_});
|
16085
|
45 |
}
|
|
46 |
|
|
47 |
auto rg = QRandomGenerator::global();
|
|
48 |
|
16092
|
49 |
for (qsizetype i = 0; i < size; i += 6) {
|
16085
|
50 |
const auto first = rg->bounded(size);
|
|
51 |
const auto second = rg->bounded(size);
|
|
52 |
|
|
53 |
if (first != second) {
|
|
54 |
generation_[first].crossover(generation_[second]);
|
|
55 |
}
|
|
56 |
}
|
|
57 |
|
|
58 |
std::for_each(std::begin(solutions_), std::end(solutions_),
|
16092
|
59 |
[](const auto &fn) { QFile::remove(fn); });
|
16084
|
60 |
solutions_.clear();
|
|
61 |
|
16085
|
62 |
generation_.append(kept);
|
16084
|
63 |
|
16085
|
64 |
for (auto &solution : generation_) {
|
|
65 |
solution.render(newFileName());
|
|
66 |
|
|
67 |
solution.calculateFitness(referenceImage_);
|
|
68 |
|
16092
|
69 |
solution.fitness += solution.cost() * 1e4;
|
16084
|
70 |
}
|
|
71 |
|
16085
|
72 |
std::sort(std::begin(generation_), std::end(generation_),
|
|
73 |
[](const auto &a, const auto &b) { return a.fitness < b.fitness; });
|
|
74 |
|
|
75 |
std::for_each(std::begin(generation_) + size, std::end(generation_),
|
|
76 |
[](const auto &s) { QFile::remove(s.fileName); });
|
|
77 |
generation_.remove(size, kept.size());
|
16084
|
78 |
|
16085
|
79 |
bestSolution_ = generation_[0].fitness;
|
|
80 |
|
|
81 |
std::transform(std::begin(generation_), std::end(generation_),
|
|
82 |
std::back_inserter(solutions_),
|
|
83 |
[](const auto &a) { return a.fileName; });
|
|
84 |
|
|
85 |
emit bestSolutionChanged();
|
16084
|
86 |
emit solutionsChanged();
|
|
87 |
}
|
|
88 |
|
|
89 |
QStringList Tracer::solutions() const { return solutions_; }
|
|
90 |
|
|
91 |
QString Tracer::newFileName() {
|
|
92 |
static qlonglong counter{0};
|
|
93 |
counter += 1;
|
|
94 |
return tempDir_.filePath(
|
|
95 |
QStringLiteral("hedgehog_%1.svg").arg(counter, 3, 32, QChar(u'_')));
|
|
96 |
}
|
|
97 |
|
16092
|
98 |
Solution::Solution(QSizeF size, const QJsonArray &atoms) : size{size} {
|
16084
|
99 |
fitness = 0;
|
16092
|
100 |
|
|
101 |
std::transform(std::begin(atoms), std::end(atoms),
|
|
102 |
std::back_inserter(primitives),
|
|
103 |
[&](const auto &a) { return Primitive{size, a.toObject()}; });
|
16084
|
104 |
}
|
|
105 |
|
16085
|
106 |
void Solution::calculateFitness(const QImage &target) {
|
|
107 |
QImage candidate{fileName};
|
|
108 |
|
|
109 |
if (candidate.isNull()) {
|
|
110 |
fitness = 1e32;
|
|
111 |
return;
|
|
112 |
}
|
|
113 |
|
16092
|
114 |
candidate = candidate.convertedTo(QImage::Format_RGBA8888);
|
|
115 |
|
16085
|
116 |
// Both images assumed same size, same format
|
|
117 |
double diffSum = 0;
|
|
118 |
int width = target.width();
|
|
119 |
int height = target.height();
|
|
120 |
|
|
121 |
for (int y = 0; y < height; ++y) {
|
16092
|
122 |
const auto candScan = reinterpret_cast<const QRgb *>(candidate.scanLine(y));
|
|
123 |
const auto targScan = reinterpret_cast<const QRgb *>(target.scanLine(y));
|
16085
|
124 |
for (int x = 0; x < width; ++x) {
|
|
125 |
// Compare RGBA channels
|
|
126 |
const QRgb cPix = candScan[x];
|
|
127 |
const QRgb tPix = targScan[x];
|
|
128 |
// const auto ca = qAlpha(cPix) / 255.0;
|
|
129 |
const auto ta = qAlpha(tPix) / 255.0;
|
|
130 |
const auto dr = qRed(cPix) - qRed(tPix);
|
|
131 |
const auto dg = qGreen(cPix) - qGreen(tPix);
|
|
132 |
const auto db = qBlue(cPix) - qBlue(tPix);
|
|
133 |
const auto da = qAlpha(cPix) - qAlpha(tPix);
|
16092
|
134 |
diffSum += (dr * dr + dg * dg + db * db) * ta + da * da;
|
16085
|
135 |
}
|
|
136 |
}
|
|
137 |
|
|
138 |
fitness = diffSum;
|
|
139 |
}
|
|
140 |
|
|
141 |
void Solution::render(const QString &fileName) {
|
|
142 |
this->fileName = fileName;
|
|
143 |
|
16084
|
144 |
const auto imageSize = size.toSize();
|
|
145 |
|
|
146 |
QSvgGenerator generator;
|
|
147 |
generator.setFileName(fileName);
|
|
148 |
generator.setSize(imageSize);
|
|
149 |
generator.setViewBox(QRect(0, 0, imageSize.width(), imageSize.height()));
|
|
150 |
generator.setTitle("Hedgehog");
|
|
151 |
generator.setDescription("Approximation of a target image using primitives");
|
|
152 |
|
|
153 |
QPainter painter;
|
|
154 |
painter.begin(&generator);
|
|
155 |
painter.setRenderHint(QPainter::Antialiasing, true);
|
|
156 |
|
16085
|
157 |
for (const auto &primitive : primitives) {
|
16084
|
158 |
painter.setPen(primitive.pen);
|
|
159 |
painter.setBrush(primitive.brush);
|
|
160 |
painter.resetTransform();
|
|
161 |
painter.translate(primitive.origin);
|
|
162 |
painter.rotate(primitive.rotation);
|
|
163 |
|
|
164 |
switch (primitive.type) {
|
|
165 |
case Polygon: {
|
|
166 |
QPolygonF polygon;
|
|
167 |
polygon.append({0, 0});
|
|
168 |
polygon.append(primitive.points);
|
|
169 |
|
|
170 |
painter.drawPolygon(polygon);
|
|
171 |
break;
|
|
172 |
}
|
|
173 |
case Circle:
|
|
174 |
painter.drawEllipse({0, 0}, primitive.radius1, primitive.radius2);
|
|
175 |
break;
|
|
176 |
}
|
|
177 |
}
|
|
178 |
|
|
179 |
painter.end();
|
|
180 |
}
|
|
181 |
|
|
182 |
double Solution::cost() const {
|
|
183 |
return std::accumulate(primitives.constBegin(), primitives.constEnd(), 0,
|
|
184 |
[](auto a, auto p) { return a + p.cost(); });
|
|
185 |
}
|
|
186 |
|
16092
|
187 |
void Solution::mutate() {
|
16085
|
188 |
if (primitives.isEmpty()) {
|
|
189 |
return;
|
|
190 |
}
|
|
191 |
|
|
192 |
auto rg = QRandomGenerator::global();
|
16092
|
193 |
double mutationRate = 0.1;
|
16085
|
194 |
|
|
195 |
for (auto &prim : primitives) {
|
|
196 |
// Pen width
|
|
197 |
if (rg->bounded(1.0) < mutationRate) {
|
16092
|
198 |
prim.pen.setWidthF(prim.pen.widthF() * (rg->bounded(0.5) + 0.8) + 0.01);
|
16085
|
199 |
}
|
|
200 |
|
|
201 |
// Origin
|
|
202 |
if (rg->bounded(1.0) < mutationRate) {
|
16092
|
203 |
prim.origin += QPointF(rg->bounded(4.0) - 2.0, rg->bounded(4.0) - 2.0);
|
16085
|
204 |
}
|
|
205 |
|
|
206 |
if (prim.type == Polygon) {
|
|
207 |
// Points
|
|
208 |
for (auto &pt : prim.points) {
|
|
209 |
if (rg->bounded(1.0) < mutationRate) {
|
16092
|
210 |
pt += QPointF(rg->bounded(2.0) - 1.0, rg->bounded(2.0) - 1.0);
|
16085
|
211 |
}
|
|
212 |
}
|
|
213 |
} else { // Circle/ellipse
|
|
214 |
if (rg->bounded(1.0) < mutationRate) {
|
16092
|
215 |
prim.radius1 *= rg->bounded(0.5) + 0.8;
|
16085
|
216 |
}
|
|
217 |
if (rg->bounded(1.0) < mutationRate) {
|
16092
|
218 |
prim.radius2 *= rg->bounded(0.5) + 0.8;
|
16085
|
219 |
}
|
|
220 |
if (rg->bounded(1.0) < mutationRate) {
|
|
221 |
prim.rotation = rg->bounded(90.0);
|
|
222 |
}
|
|
223 |
}
|
|
224 |
}
|
|
225 |
|
|
226 |
if (rg->bounded(1.0) < mutationRate) {
|
16092
|
227 |
const auto i = rg->bounded(primitives.size());
|
16085
|
228 |
|
16092
|
229 |
primitives.insert(i, primitives[i]);
|
16085
|
230 |
}
|
|
231 |
|
|
232 |
if (rg->bounded(1.0) < mutationRate) {
|
16092
|
233 |
const auto a = rg->bounded(primitives.size());
|
|
234 |
const auto b = rg->bounded(primitives.size());
|
|
235 |
|
|
236 |
qSwap(primitives[a], primitives[b]);
|
|
237 |
}
|
|
238 |
|
|
239 |
if (rg->bounded(1.0) < mutationRate) {
|
|
240 |
const auto i = rg->bounded(primitives.size());
|
16085
|
241 |
|
|
242 |
primitives.remove(i);
|
|
243 |
}
|
|
244 |
}
|
|
245 |
|
|
246 |
void Solution::crossover(Solution &other) {
|
|
247 |
auto rg = QRandomGenerator::global();
|
|
248 |
|
16092
|
249 |
const auto n = qMin(primitives.size(), other.primitives.size());
|
16085
|
250 |
|
16092
|
251 |
if (n <= 1) {
|
|
252 |
return;
|
|
253 |
}
|
16085
|
254 |
|
16092
|
255 |
// swap one element
|
|
256 |
const auto cp = rg->bounded(n);
|
|
257 |
const auto ocp = rg->bounded(n);
|
16085
|
258 |
|
16092
|
259 |
qSwap(primitives[cp], other.primitives[ocp]);
|
16085
|
260 |
}
|
|
261 |
|
16092
|
262 |
Primitive::Primitive(QSizeF size, const QJsonObject &atom) {
|
16084
|
263 |
auto rg = QRandomGenerator::global();
|
|
264 |
auto randomPoint = [&]() -> QPointF {
|
|
265 |
return {rg->bounded(size.width()), rg->bounded(size.height())};
|
|
266 |
};
|
|
267 |
|
16092
|
268 |
if (atom["type"] == "polygon") {
|
16084
|
269 |
type = Polygon;
|
|
270 |
|
16092
|
271 |
for (int i = 1; i < atom["length"].toInt(3); ++i) {
|
|
272 |
points.append(randomPoint());
|
|
273 |
}
|
|
274 |
} else if (atom["type"] == "circle") {
|
16084
|
275 |
type = Circle;
|
|
276 |
|
16085
|
277 |
radius1 = rg->bounded(size.width() * 0.2) + 2;
|
|
278 |
radius2 = rg->bounded(size.width() * 0.2) + 2;
|
16084
|
279 |
rotation = rg->bounded(90);
|
|
280 |
}
|
|
281 |
|
16092
|
282 |
const auto pens = atom["pens"].toVariant().toStringList();
|
|
283 |
pen = QPen(pens[rg->bounded(pens.length())]);
|
|
284 |
pen.setWidthF(rg->bounded(size.width() * 0.05));
|
|
285 |
pen.setJoinStyle(Qt::RoundJoin);
|
|
286 |
|
|
287 |
const auto brushes = atom["brushes"].toVariant().toStringList();
|
|
288 |
brush = QBrush(QColor(brushes[rg->bounded(brushes.length())]));
|
16084
|
289 |
|
|
290 |
origin = randomPoint();
|
|
291 |
}
|
|
292 |
|
|
293 |
double Primitive::cost() const { return 1.0 + 0.1 * points.length(); }
|
16092
|
294 |
|
|
295 |
QJsonArray Tracer::atoms() const { return atoms_; }
|
|
296 |
|
|
297 |
void Tracer::setAtoms(const QJsonArray &newAtoms) {
|
|
298 |
if (atoms_ == newAtoms) return;
|
|
299 |
atoms_ = newAtoms;
|
|
300 |
emit atomsChanged();
|
|
301 |
}
|