I'm working on implementing a terminal renderer, and after quantizing the original image down to 256 colors, I need to find the closest representation for each pixel of the image.
I was looking at doing this by comparing the squared distances, but the naive way would require me to store 16 bit integers in a vector.
So, the meat of the question is: can I achieve an approximate result using only 8 bit vectors by calculating ((a - b) ** 2 & 0xff00) >> 8
.
I know of a way to calculate the absolute difference of bytes, as highlighted here (https://stackoverflow.com/a/46970204/12954733), and I'm only missing is a _mm256_mulhi_epu8
instruction, sadly it doesn't exist in both avx2 and avx512, only 16bit and higher versions exist.
This is a plain C version of what I'm trying to achieve:
struct col {
uint8_t r,g,b;
};
struct col cols[256];
int find_i(struct col x) {
int mini = INT_MAX;
int mind = INT_MAX;
for (int i = 0; i < 256; i++) {
int dr, db, dg;
dr = x.r - cols[i].r;
dg = x.g - cols[i].g;
db = x.b - cols[i].b;
int32_t d = dr*dr + dg*dg + db*db;
if (d < mind) {
mind = d;
mini = i;
}
}
return mini;
}