Francisco García
Francisco García

Reputation: 238

Matlab to OpenCV: mask of pixels with value inside a range

I have this Matlab code to find a mask (skin) of the pixel with values inside the ranges for H and S channels of my HSV image hsv_im:

h_range = [0.02 0.085]; 
s_range = [0.18 .754];

H = hsv_im(:,:,1);
S = hsv_im(:,:,2);

%targets skin by only selecting values within the rectangle skin range
skin = (S>s_range(1) & S<s_range(2) & H>h_range(1) & H<h_range(2));

I need to port this to OpenCV. So far I have this:

  float h_range[2] = {0.02, 0.085};
  float s_range[2] = {0.18, 0.754};

  vector<Mat> channels;
  split(imageHSV, channels);
  Mat H = channels[0];
  Mat S = channels[1];

but I failed to do the rest.

Upvotes: 1

Views: 609

Answers (1)

Miki
Miki

Reputation: 41765

I assume that your imageHSV has values in range [0,1], otherwise you just need to change the range values. This is because in Matlab images are usually in range [0,1], while in OpenCV in range [0,255].

Actually for HSV images this is a little different:

  • If imageHSV is of type CV_8UC3, then the ranges are: H in [0,180], S and V in [0,255].
  • If imageHSV is of type CV_32FC3, the valid ranges for OpenCV are: H in [0,360], S and V in [0,1].

You can do this using inRange. Just define lower and upper range for the 3 channels. Take care to correct the Matlab range for OpenCV:

Mat imgHSV = ... type should CV_32FC3

Mat skin;
inRange(imgHSV, Scalar(0.02, 0.18, 0), Scalar(0.085, 0.754, 1), skin);
//                      h     s    v            h      s    v
//                      lower range              upper range

// skin will be a binary mask of type CV_8UC1, with values either 0 or 255

Upvotes: 1

Related Questions