Skip to content

Commit

Permalink
use integer math for the rgb to hsv conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
Yay295 committed Sep 22, 2024
1 parent 0d818be commit 4f11b04
Showing 1 changed file with 21 additions and 33 deletions.
54 changes: 21 additions & 33 deletions src/libImaging/Convert.c
Original file line number Diff line number Diff line change
Expand Up @@ -310,45 +310,33 @@ rgb2bgr24(UINT8 *out, const UINT8 *in, int xsize) {
}

static void
rgb2hsv_row(UINT8 *out, const UINT8 *in) { // following colorsys.py
double h, s, rc, gc, bc, cr;
UINT8 maxc, minc;
UINT8 r, g, b;
UINT8 uh, us, uv;

r = in[0];
g = in[1];
b = in[2];
maxc = MAX(r, MAX(g, b));
minc = MIN(r, MIN(g, b));
uv = maxc;
if (minc == maxc) {
uh = 0;
us = 0;
} else {
cr = (double)(maxc - minc);
s = cr / (double)maxc;
rc = ((double)(maxc - r)) / cr;
gc = ((double)(maxc - g)) / cr;
bc = ((double)(maxc - b)) / cr;
rgb2hsv_row(UINT8 *out, const UINT8 *in) {
// following https://literateprograms.org/rgb_to_hsv_color_space_conversion__c_.html

const UINT8 r = in[0];
const UINT8 g = in[1];
const UINT8 b = in[2];
const UINT8 maxc = MAX(r, MAX(g, b));
const UINT8 minc = MIN(r, MIN(g, b));

UINT8 h = 0, s = 0;
const UINT8 v = maxc;

if (v != 0 && minc != maxc) {
if (r == maxc) {
h = bc - gc;
h = 0 + 43 * (g - b) / (maxc - minc);
} else if (g == maxc) {
h = 2.0 + rc - bc;
h = 85 + 43 * (b - r) / (maxc - minc);
} else {
h = 4.0 + gc - rc;
h = 171 + 43 * (r - g) / (maxc - minc);
}
// incorrect hue happens if h/6 is negative.
//h = fmod((h / 6.0 + 1.0), 1.0);
h = h / 6.0 + 1.0;
h = h - (int)h;

uh = (UINT8)CLIP8((int)(h * 255.0));
us = (UINT8)CLIP8((int)(s * 255.0));
s = (UINT16)255 * (maxc - minc) / v;
}
out[0] = uh;
out[1] = us;
out[2] = uv;

out[0] = h;
out[1] = s;
out[2] = v;
}

static void
Expand Down

0 comments on commit 4f11b04

Please sign in to comment.