0

After converting an image x to a black and white image by using im2bw(x), imfilter returns black and white images only. How can I convert this black and white image into a normal matrix such that imfilter can return a matrix of reals? Demo:

>> k = [0.3 0.3; 0   0.3];
>> x = [0.9 0.3; 0.4 0.2];
>> y = im2bw(x)
y =

  1 0
  0 0
>> imfilter(y, k)
ans = 

  1  0
  0  0
>> imfilter([1 0; 0 0], k)
ans =

  0.30000  0.00000
  0.00000  0.00000
>> 

As you can see, imfilter rounds the results when applying to a binary image. I would like to prevent this. How can I convert the binary image to a regular matrix while keeping its values?

Ell
  • 4,238
  • 6
  • 34
  • 60
  • 1
    have you tried `y = double(y)`? – beaker Nov 04 '17 at 20:10
  • @beaker Nope - and it works. I will accept this if you add it as an answer. I can't believe how long I spent googling and how simply the answer is... thanks! – Ell Nov 04 '17 at 20:16

1 Answers1

2

Looking at the documentation for imfilter,

The result B has the same size and class as A.

Since the output from im2bw is a logical array, the output of imfilter is too. In order to get a floating-point output from imfilter you need to cast the thresholded image to a float type:

y = double(y);   % or, y = single(y);

Result:

>> k = [0.3 0.3; 0   0.3];
>> x = [0.9 0.3; 0.4 0.2];
>> y = im2bw(x)
y =

  1  0
  0  0

>> y = double(y)
y =

   1   0
   0   0

>> imfilter(y, k)
ans =

   0.30000   0.00000
   0.00000   0.00000
beaker
  • 16,331
  • 3
  • 32
  • 49