I am trying to to subtract the background from a picture of an object to leave only the foreground object. I have found the RGB values of the background as 218 220 219 using imshow(). How can I use the RGB values with imsubtract()?
y = [218 220 219];
z = imsubtract(img,y);
Error using imsubtract (line 55) X and Y must have the same size and class, or Y must be a scalar double.
You can use bsxfun to do that
z = bsxfun( @minus, img, permute( [218 220 219], [1 3 2] ) );
You need to pay attention to data type and range. If img
is of type uint8
pixel values will be in range 0..255 but it will be difficult to subtract values as you'll see results underflowing at 0: uint8(4) - uint8(10)
is 0
...
Thus, you might want to convert img
to double
using im2double
having pixel values in range 0..1. In that case you'll have to convert the "gray" vector [2218 220 219]
to 0..1 range by dividing it by 255
.
So, a more complete solution would be
z = bsxfun( @minus, im2double(img), permute( [218 220 219]/255, [1 3 2] ) );