Search code examples
matlabhistogramnormalizationdicom

Histogram - Index must be a positive integer or logical


I do the histogram normalization. When I try with another image lena256.bmp, the code is running. But when I try with another image it will show error:

Attempted to access ; index must be a positive integer or logical.
Error in test2 (line 10)
Histo(a(n,m)+1)=Histo(a(n,m)+1)+1;

Here's the code :

a = dicomread('011fp5_256.dcm');
a = double(a);  
a=a/max(a(:)); 
figure; imshow(a);
figure; imhist(a); 
[N, M] = size(a);  
Histo(1:256) = 0;   
for n = 1 : N   
    for m = 1 : M
        Histo(a(n,m)+1) = Histo(a(n,m)+1)+1;  
    end
end
Histo = Histo/(N*M);
figure; plot(Histo);

Solution

  • the matrix index can't be a decimal value, therefore, you need to approximate the a(n,m) to the nearest integer value.

    a = dicomread('CT-MONO2-16-ankle.dcm');
    a = double(a);  
    a=a/max(a(:)); 
    figure; imshow(a);
    figure; imhist(a); 
    [N, M] = size(a);  
    Histo(1:256) = 0;   
    for n = 1 : N   
        for m = 1 : M
            if a(n,m)+1 ~= floor(a(n,m)+1)%I use this code for find the error
                disp(a(n,m)+1);
            end
            ind = floor(a(n,m)+1);% apprx. to the nearest integer.
            Histo(ind) = Histo(ind)+1;  
        end
    end
    Histo = Histo/(N*M);
    figure; plot(Histo);