8

I am looking for a function in openCV to help me make masks of images.

for example in MATLAB:

B(A<1)=0;

or

B=zeros(size(A));

B(A==10)=c;

A S
  • 2,924
  • 5
  • 22
  • 27

2 Answers2

10

Some functions allow you to pass mask arguments to them. To create masks the way you describe, I think you are after Cmp or CmpS which are comparison operators, allowing you to create masks, by comparison to another array or scalar. For example:

im = cv.LoadImageM('tree.jpg', cv.CV_LOAD_IMAGE_GRAYSCALE)
mask_im = cv.CreateImage((im.width, im.height), cv.IPL_DEPTH_8U, 1)
#Here we create a mask by using `greater than 100` as our comparison
cv.CmpS(im, 100, mask_im, cv.CV_CMP_GT)
#We set all values in im to 255, apart from those masked, cv.Set can take a mask arg.
cv.Set(im, 255, mask=mask_im)
cv.ShowImage("masked", im)
cv.WaitKey(0)

Original im:

enter image description here

im after processing:

enter image description here

fraxel
  • 34,470
  • 11
  • 98
  • 102
3

OpenCV C++ supports the following syntax you might find convenient in creating masks:

Mat B= A > 1;//B(A<1)=0

or

Mat B = A==10;
B *= c;

which should be equivalent to:

B=zeros(size(A));
B(A==10)=c;

You can also use compare(). See the following OpenCV Documentation.

Shai
  • 111,146
  • 38
  • 238
  • 371
Yonatan Simson
  • 2,395
  • 1
  • 24
  • 35
  • 1
    Would you have any idea why the result of (matrix == 1) would result in those values that are 1 in the source matrix being 255 in the output matrix? – Joey Carson Apr 25 '16 at 16:25
  • OpenCV has concept called masking. The convention is that a binary mask is implemented using chars where 0->0 and 1->255. So the best answer is that 255 is retrned for no special reason other then convention. Note that when using a mask in OPenCV functions you don't have to stick to this convention. Any number between 1-255 is true and 0 is false. – Yonatan Simson Apr 25 '16 at 21:11
  • Thanks! Yes I realize 255 will evaluate as true, but in MATLAB it's common to add up the 1's in the binary matrix output. I was confused that I was getting huge numbers because all were 255. I'll keep that in mind. Thanks again. – Joey Carson Apr 25 '16 at 21:21
  • 1
    I agree that it can be inconvenient. You could mask it this way `A =& 0x1` in order to force it to 1. – Yonatan Simson Apr 26 '16 at 05:36