Search code examples
image-processingopencvcomputer-visionemgucv

How to mask green pixels?


I need to mask a green pixels in the image. I have have example of the masking red pixels. Here the example:

Image<Hsv, Byte> hsv = image.Convert<Hsv, Byte>()

Image<Gray, Byte>[] channels = hsv.Split();

               //channels[0] is the mask for hue less than 20 or larger than 160

CvInvoke.cvInRangeS(channels[0], new MCvScalar(20), new MCvScalar(160), channels[0]);
               channels[0]._Not();

but, I cant understand from where those parameters where token:

new MCvScalar(20), new MCvScalar(160)

Any idea which parameters I have to take to mask the green pixels? Thank you in advance.


Solution

  • The code masks pixels with Hue outside the range 20 - 160 (or rather masks pixeles inside the range and then inverts the mask).

    First, understand HSV (Hue, Saturation, Value): http://en.wikipedia.org/wiki/HSL_and_HSV

    The actual Hue is in degrees and goes from 0 to 360 like:

    Hue angles

    Then see OpenCV documentation on 8-bit HSV format:

    Hue is first calculated in 0 - 360, then divided by 2 to fit into 8-bit integer.

    This means that in the original example the masked pixels have actual Hue under 40 or above 320 degrees. Apparently that's 0 degrees plus / minus 40.

    For a similar range of greens you'd want 120 +/- 40, i.e. from 80 to 160. Finally converting that to 8-bit representation - from 40 to 80.

    The actual code will differ from your sample though: for red they had to mask 20,160 then invert the mask. For green just masking from 40 to 80 is enough (i.e. you'll have to omit the channels[0]._Not(); part).