简体   繁体   中英

Matlab imread function confusion

I'm implementing an ant colony algorithm in a grayscale image, and I'm confused in getting the right heuristic values. I always get 0 or 1.

Here's the part of the code:

x = imread('test.jpg');

y = max(x(:));

For example, I get 226 as the max intensity value. I try x/y and I get a matrix with values of 1's and mostly 0's on single digit intensity values. Is there a part here I'm missing?

I tried creating a zero 4x4 matrix with 255 in the diagonal. Then I divide it with y. I get some "same integer class error".

This is because the image type of the image you are reading in with imread is one of an unsigned integer type, most likely uint8 and so when you are performing division, it is actually performing integer division and so the "decimal values" are truncated or removed. Here's a reproducible example. Let's say I had the following 2 x 2 image in uint8 format:

>> A = uint8([1 2; 3 4])

A =

    1    2
    3    4

Now if I tried to divide each intensity image by 4, I get:

>> B = A / 4

B =

    0    1
    1    1

This is because the image type is uint8 and so when division happens and the result is a floating-point number, the result is rounded , and this is most likely what is happening in your situation.


If you want to maintain floating point precision, you need to explicitly cast the image to double :

x = imread('test.jpg');
x = double(x); %// Change
y = max(x(:));
out = x / y;

BTW, since you want to normalize the image so that it falls in the range of [0,1] , I highly recommend you do not do this and use the im2double function instead. It will perform this normalization for you as well as make other sanity checks:

x = imread('test.jpg');
out = im2double(x);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM