Last active
January 29, 2018 09:14
-
-
Save Erkaman/80a2407ca70c50958dc983bbaad40c64 to your computer and use it in GitHub Desktop.
This program implements color quantization with K-means clustering using Lloyd's algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The MIT License (MIT) | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in | |
all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
THE SOFTWARE. | |
*/ | |
/* | |
This program implements color quantization with K-means clustering using Lloyd's algorithm. | |
Based on the article | |
https://en.wikipedia.org/wiki/K-means_clustering | |
The only dependency is lodepng. You compile and run in g++ with the line | |
g++ -o quantize -std=c++11 main.cpp lodepng.cpp -O2 && ./quantize | |
*/ | |
#include "lodepng.h" | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <math.h> | |
#include <vector> | |
#include <set> | |
#include <map> | |
#define NUM_QUANTIZATION_COLORS 16 // number of colors to quantize into | |
#define MAX_ITERATIONS 200 | |
#define EPSILON 0.001f | |
#define RANDOM_SEED 1 | |
#define INPUT_FILE "smallcat.png" | |
#define OUTPUT_FILE "quantized_cat.png" | |
class vec3 { | |
public: | |
float x, y, z; | |
vec3(float x, float y, float z) { this->x = x; this->y = y; this->z = z; } | |
vec3(float v) { this->x = v; this->y = v; this->z = v; } | |
vec3() { this->x = this->y = this->z = 0; } | |
vec3& operator+=(const vec3& b) { (*this) = (*this) + b; return (*this); } | |
friend vec3 operator-(const vec3& a, const vec3& b) { return vec3(a.x - b.x, a.y - b.y, a.z - b.z); } | |
friend vec3 operator+(const vec3& a, const vec3& b) { return vec3(a.x + b.x, a.y + b.y, a.z + b.z); } | |
friend vec3 operator*(const float s, const vec3& a) { return vec3(s * a.x, s * a.y, s * a.z); } | |
friend vec3 operator*(const vec3& a, const float s) { return s * a; } | |
static float length(const vec3& a) { return sqrt(vec3::dot(a, a)); } | |
static float dot(const vec3& a, const vec3& b) { return a.x*b.x + a.y*b.y + a.z*b.z; } | |
static float distance(const vec3& a, const vec3& b) { return length(a - b); } | |
}; | |
int main() { | |
srand(RANDOM_SEED); // use different seed, for different initial means | |
std::vector<unsigned char> image; | |
unsigned width, height; | |
unsigned error = lodepng::decode(image, width, height, INPUT_FILE); | |
if(error) { | |
printf("could not open input image: %s\n", lodepng_error_text(error)); | |
exit(1); | |
} | |
const int k = NUM_QUANTIZATION_COLORS; | |
// we treat every color value in the image, as a point 3D-space that should be quantized. | |
std::vector<vec3> pl; | |
for(int i = 0; i < image.size(); i+=4) { | |
pl.push_back(vec3(image[i + 0] / 255.0f,image[i + 1] / 255.0f,image[i + 2] / 255.0f)); | |
} | |
// set the initial means to random samples from pl. | |
// we use an std::set to ensure that these samples are unique. | |
std::vector<vec3> m; | |
{ | |
std::set<int> im; | |
while(im.size() < k) { | |
im.insert(rand() % pl.size()); | |
} | |
for(const int i: im) { | |
m.push_back(pl[i]); | |
} | |
} | |
std::vector<std::vector<int> > clusters; | |
for(int i = 0; i < k; ++i) { | |
clusters.push_back(std::vector<int>()); | |
} | |
for(int iter = 0; iter < MAX_ITERATIONS; ++iter) { | |
printf("iteration %d\n", iter); | |
for(int i = 0; i < k; ++i) { | |
clusters[i].clear(); | |
} | |
// we will assign every single point to a cluster. | |
// every cluster has a mean, and the point is assigned | |
// to the cluster whose mean it is closest to(in terms of | |
// the euclidean distance) | |
for(int i_point = 0; i_point < pl.size(); ++i_point) { | |
int i_closest = -1; | |
float i_dist = -1; | |
for(int i_cluster = 0; i_cluster < k; ++i_cluster) { | |
float dist = vec3::distance(pl[i_point], m[i_cluster]); | |
if(i_closest == -1 || dist < i_dist) { | |
i_dist = dist; | |
i_closest = i_cluster; | |
} | |
} | |
clusters[i_closest].push_back(i_point); | |
} | |
bool different_enough = false; | |
// now all the points have been assigned to clusters. | |
// this means that k clusters have been formed. | |
// now we update the means of these clusters. | |
for(int i_cluster = 0; i_cluster < k; ++i_cluster) { | |
float w = 1.0 / clusters[i_cluster].size(); | |
vec3 avg = vec3(0.0); | |
for(int i = 0; i < clusters[i_cluster].size(); ++i) { | |
avg += w * pl[clusters[i_cluster][i]]; | |
} | |
if(vec3::distance(m[i_cluster],avg) > EPSILON) { | |
different_enough = true; | |
} | |
m[i_cluster] = avg; | |
} | |
// if all the updated means barely moved at all, then we have attained | |
// local maximum. we can't do any better, so terminate. | |
if(!different_enough) { | |
printf("Found local maximum. Done!\n"); | |
break; | |
} | |
} | |
printf("Clustering done!\n"); | |
std::map<int, int> color_map; // maps the original colors to their quantized clors. | |
for(int i_cluster = 0; i_cluster < k; ++i_cluster) { | |
for(int i = 0; i < clusters[i_cluster].size(); ++i) { | |
color_map[clusters[i_cluster][i]] = i_cluster; | |
} | |
} | |
// finally, output the quantized image. | |
image.clear(); | |
for(int i = 0; i < pl.size(); ++i) { | |
vec3 col = m[color_map[i]]; | |
unsigned char r = (unsigned char)(col.x * 255.0f); | |
unsigned char g = (unsigned char)(col.y * 255.0f); | |
unsigned char b = (unsigned char)(col.z * 255.0f); | |
image.push_back(r); | |
image.push_back(g); | |
image.push_back(b); | |
image.push_back(255); | |
} | |
lodepng::encode(OUTPUT_FILE, image, width, height); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment