Reputation: 2789
I am reading two images as matrices in Matlab and want to create a third image, which is calculated as:
(im1-im2)./(im1+im2)
However, I believe Matlab is rounding the values of the element-wise division (which of course I don't want). For example, the first value of im1-im2
is 32 and the first value of im1+im2
is 70. So, the first value of the resulting matrix is supposed to be 32/70=0.4571
, but it is 0.
How can I do this matrix operation maintaining the original division result values in the final matrix?
Upvotes: 1
Views: 94
Reputation: 1390
im1
and im2
are uint8
or uint16
most likely, convert them to double
and perform this operation. Note that converting them implicitly like *1.0
or something doesn't work.
So, something like
im1 = double(im1);
im2 = double(im2);
thingYouWant = (im1 - ...;
Note that converting back to uint
will again leave you with 1 (values above 0.5) or 0 (values below 0.5). To convert back to uint8
, you need to do something like:
resultInUint8 = uint8(thingYouWant * 255); % Linear scale from 0 to 255
Another thing to note is that double(im1 - im2)
will result in 0 if im2
is larger than im1
. So you might end up with half of image being 0. Better to convert before doing any operation.
Upvotes: 1
Reputation: 25232
It depends on your image data and how you load it. An 8-bit image loaded e.g. with imread
, is stored as integer matrix (uint8
). Images with higher bit-depth are stored with uint16
or more.
So you could either process your image by casting the matrix to double
and cast it back to an appropriate bit-depth afterwards, or you cast it directly to your desired bit-depth and accept the rounding, as it needs to be done anyway at the end.
im1 = double( imread('fig1.png') );
im2 = double( imread('fig2.png') );
result = uint32( (im1-im2)./(im1+im2) );
Upvotes: 1