Approximating Images with a Single Continuous Thread
Muriz Serifovic
2015-11-04
Introduction
By using ordinary linear least squares for the optimization task, defined by
$$
\min _{x}\|A x-y\|_{2}^{2} \quad \text { with } \quad A : \mathbb{R}^{n} \rightarrow \mathbb{R}^{m}
$$
we propose an algorithm which takes an image as input and turns it
into a linked string graph that best attempts to re-assemble the image input.
Results
The algorithm finds the darkest line between two pins. It adds this line to a new blank image and removes the same line from the original image. The output is an image created out of straight lines where every line goes through the whole image.
Background
Each possible thread between two pins is one column of \(A\): the image of that single line. In practice the least-squares problem above is not solved directly. The solution is built greedily, one thread at a time: from the pin the thread currently sits on, take the darkest line, add it to the output and subtract it from what is left of the original.
Code
The core algorithm implementation:
// Initialize circle of pins around the image
private void init() {
double rad = Math.min(img.getWidth(), img.getHeight()) / 2;
for (int i = 0; i < numberOfPins; ++i) {
double d = Math.PI * 2.0 * (double)i / (double)numberOfPins;
px[i] = img.getWidth()/2 + Math.sin(d) * rad;
py[i] = img.getHeight()/2 + Math.cos(d) * rad;
}
}
// Core optimization: Find darkest line between pins
void calculateLine() {
double limit = 1000000;
int bestFirstPin = 0, bestSecondPin = 0;
int i = currentPin;
// For current pin, check lines to all other valid pins
for(int j = 1 + ignoreNeighbors; j < numberOfPins - ignoreNeighbors; ++j) {
int nextPin = (i + j) % numberOfPins;
if(nextPin == i) continue;
// Calculate line intensity by sampling points along the line
double dx = px[nextPin] - px[i];
double dy = py[nextPin] - py[i];
double len = lengths[j];
double intensity = 0;
for(int k = 0; k < len; ++k) {
double s = (double)k/len;
intensity += img.getRGB((int)(px[i] + dx * s),
(int)(py[i] + dy * s));
}
// Update if darkest line found
double currIntensity = intensity / len;
if(limit > currIntensity) {
limit = currIntensity;
bestFirstPin = i;
bestSecondPin = nextPin;
}
}
// Draw the found line and update the source image
drawLine(bestFirstPin, bestSecondPin);
currentPin = bestSecondPin; // Continue from end of last line
}
Cite this article
If this was of any use, the kindest citation is telling someone about it; the entry below covers the less kind occasions.
@article{serifovic2015discrete,
author = {Serifovic, Muriz},
title = {Approximating Images with a Single Continuous Thread},
journal = {muriz.ch},
year = {2015},
month = {November},
note = {https://muriz.ch/blog/discrete-optimization.html},
}
Bees · The Naturalist’s Library, vol. XXVI