Mercurial > hg > octave-lyh
diff scripts/image/rgb2hsv.m @ 3904:6b00ac653c0f
[project @ 2002-04-24 04:56:10 by jwe]
author | jwe |
---|---|
date | Wed, 24 Apr 2002 04:56:11 +0000 |
parents | 63c75bc3db82 |
children | 22bd65326ec1 |
line wrap: on
line diff
--- a/scripts/image/rgb2hsv.m +++ b/scripts/image/rgb2hsv.m @@ -43,48 +43,40 @@ error ("rgb2hsv: argument must be a matrix of size n x 3"); endif - # get saturation and value - v = max (rgb'); - s = (v' > 0) .* (1 .- min (rgb') ./ v)'; - - # if v==0 set s to 0 too - s(isnan (s)) = 0; + ## get the max and min + s = min (rgb')'; + v = max (rgb')'; - # subtract minimum and divide trough maximum - # to get the bright and saturated colors - sc = (rgb - kron ([1, 1, 1], min (rgb')')); - sv = sc ./ kron([1, 1, 1], max (sc')'); - - # if r=g=b (gray value) set hue to 0 - sv(isnan (sv)) = 0; - - # hue=f(color) must be splitted into 6 parts - # 2 for each color + ## set hue to zero for undefined values (gray has no hue) + h = zeros (size (v)); + notgray = (s != v); + + ## blue hue + idx = (v == rgb(:,3) & notgray); + if (any (idx)) + h(idx) = 2/3 + 1/6 * (rgb(idx,1) - rgb(idx,2)) ./ (v(idx) - s(idx)); + endif - # h1(green) - tmp = (sv(:, 1) == 1 & sv(:,3) == 0) .* (1/6 * sv(:,2) + eps); - # avoid problems with h2(red) since hue(0)==hue(1) - h = (tmp < 1/6) .* tmp; - # h2(green) - h = h + ((h == 0) & sv(:,1) == 0 & sv(:,3) == 1) \ - .* (-1/6 * sv(:,2) + 2/3 + eps); - - # h1(red) - h = h + ((h == 0) & sv(:,2) == 1 & sv(:,3) == 0) \ - .* (-1/6 * sv(:,1) + 1/3 + eps); + ## green hue + idx = (v == rgb(:,2) & notgray); + if (any (idx)) + h(idx) = 1/3 + 1/6 * (rgb(idx,3) - rgb(idx,1)) ./ (v(idx) - s(idx)); + endif - # h2(red) - h = h + ((h == 0) & sv(:,2) == 0 & sv(:,3) == 1) \ - .* (1/6 * sv(:,1) + 2/3 + eps); + ## red hue + idx = (v == rgb(:,1) & notgray); + if (any (idx)) + h(idx) = 1/6 * (rgb(idx,2) - rgb(idx,3)) ./ (v(idx) - s(idx)); + endif - # h1(blue) - h = h + ((h == 0) & sv(:,1) == 1 & sv(:,2) == 0) \ - .* (-1/6 * sv(:,3) + 1 + eps); + ## correct for negative red + idx = (h < 0); + h(idx) = 1+h(idx); - # h2(blue) - h = h + ((h == 0) & sv(:,1) == 0 & sv(:,2) == 1) \ - .* (1/6 * sv(:,3) + 1/3); + ## set the saturation + s(! notgray) = 0; + s(notgray) = 1 - s(notgray) ./ v(notgray); - hsval = [h, s, v']; + hsval = [h, s, v]; endfunction