Pono Pono - 10 months ago 94
Swift Question

Calculate hue angle range for red colours

I'm trying to correctly calculate colour hue angle range. Given an input default hue say

and a threshold value of
the range is between
100 - 140
(yes, I know - complex math).

Now in the application, when filtering an image, I can check if a given pixel falls into that range:

let inputHue = 120
let threshold = 20

let minHue = inputHue - threshold // 100
let maxHue = inputHue + threshold // 140

if (pixelHue > minHue && pixelHue < maxHue) {
// do something

Now the problem is with red colours range where the most saturated red colour is at
on the colour wheel. Given an input hue of
is now
(with a threshold of
) and
. Because of that negative value for
the condition fails:

let pixelHue = 355 // this falls into a valid red range I want to get
let minHue = -10
let maxHue = 30

if (pixelHue > minHue && pixelHue < maxHue) {
// do something

Does anyone know how to tackle this problem of a colour wheel? I'm trying to develop a general solution that would work for any given input hue (not only red colours).

Thanks in advance.

Answer Source

Hues should be considered modulo 360. Hence the range for red is 0-30 AND 350-360.

Now your value of 355 passes because (355>350 AND 355<30) OR (350>30 AND (355>350 OR 355<30)).

The critical bit here starts after the first OR. In normal arithmetic, you check against lower and upper bound, and you have to pass both tests. But in modular arithmetic, if the lower bound is higher than the upper bound, the range wraps around 0 and you only need to pass one of the two both tests.

To recap: (hue>min AND hue<max) OR (min>max AND (hue>min OR hue<max))