Qix- / color-convert

Plain color conversion functions in JavaScript
MIT License
746 stars 96 forks source link

Extremely slow conversion from rgb to hsv #40

Closed stefvw93 closed 6 years ago

stefvw93 commented 7 years ago

Hey Qix!

I have used your rgb to hsv algorithm for a while, until I tried writing my own algorithm. I did a performance test on a high-res image (6000 x 4000 pixels). My algorithm was 12 times (!!!) faster than your algorithm. I haven't looked into your code to see what we do differently, but I took the time to give you my solution.

Context: I used your algorithm to do a pixel-by-pixel conversion from rgb to hsv, to calculate the difference in hue. So practically I'm iterating 24 000 000 times. Using your algorithm, the entire loop took about 12 seconds on chrome on an early 2015 macbook pro. My solution ended up taking a bit over 1 second to complete.

So yea here it is:

const rgb_hsv = (red, green, blue) => {
    let rdif,
        gdif,
        bdif,
        h, s;

    const r = red / 255,
        g = green / 255,
        b = blue / 255,
        v = Math.max(r, g, b),
        diff = v - Math.min(r, g, b),
        diffc = (c) => {
            return (v - c) / 6 / diff + 1 / 2;
        }

    if (diff == 0) {
        h = s = 0;
    } else {
        s = diff / v;
        rdif = diffc(r);
        gdif = diffc(g);
        bdif = diffc(b);

        if (r === v) {
            h = bdif - gdif;
        } else if (g === v) {
            h = (1 / 3) + rdif - bdif;
        } else if (b === v) {
            h = (2 / 3) + gdif - rdif;
        }
        if (h < 0) {
            h += 1;
        } else if (h > 1) {
            h -= 1;
        }
    }
    return [
        Math.round(h * 360),
        Math.round(s * 100),
        Math.round(v * 100)
    ];
}

Edit: context

stefvw93 commented 7 years ago

No idea why I can't get the code insertion done properly, though...

Qix- commented 7 years ago

Hey there :) Sorry for taking so long on this.

Firstly, code insertion on GitHub takes place between three backticks (```).

Secondly, neat! I don't doubt that some of the algorithms are slow (some of them are quite old and could probably be updated).

I don't have a lot of time to look into this at this very moment, but if you want to take a whack at a PR for replacing the existing algorithm (and making sure the existing tests still pass) then that'd be very much appreciated :)

Thank you for the issue and for the implementation!

caub commented 6 years ago

@stefvw93 you could use my package, see https://repl.it/@caub/rgbToHsv-bench

Qix- commented 6 years ago

Published as 1.9.2. Thanks again @stefvw93 :)