LeafTeaNeko
LeafTeaNeko

Reputation: 113

Histogram equalisation code generates indexing error

I am implementing histogram equalisation of an image without using inbuilt functions, specifically imhist and histeq. I am only allowed to use cumsum and hist or histcounts. I have a test function that checks my code for different values that I've added for reference.

This is my code:

function eq_img = histeq_contrast(img)
%input image data is assumed to be in range 0..1
image = img;
[m,n] = size(image);
L = 256;
H = histcounts(image(:),(0:256));
H = H.';
[counts] = H;
x = 0:255;
myCDF = cumsum(counts)/(m*n);
eqI = (L-1)*myCDF(double(image)+1);
eqI = uint8(eqI);
histMyOutput = histcounts(eqI,256);
eq_img = histMyOutput;

This is the error message that is generated

Array indices must be positive integers or logical values.
Error in histeq_contrast (line 22)
eqI = (L-1)*myCDF(double(image)+1);
Error in histeq_test (line 16)
I1eq = histeq_contrast(I1);

For reference, my test function is:

%histeq_test test script%

I1 = imread('pout.tif');
I1=im2double(I1);

% damage contrast
I1=0.8*I1;

I1eq = histeq_contrast(I1);
figure
subplot(1,2,1);
imagesc(I1); caxis([0 1]); title('Test Image 1'); axis equal tight
subplot(1,2,2);
imagesc(I1eq); caxis([0 1]); title('Histeq Result');  axis equal tight
colormap(gray);

fprintf(1,'Min/max of input image  1: %3.3f %3.3f\n', min(I1(:)),max(I1(:)) );
fprintf(1,'Min/max of output image 1: %3.3f %3.3f\n', min(I1eq(:)),max(I1eq(:)) );

% damage contrast
I2 = I1*0.25 + 0.25;

I2eq = histeq_contrast(I2);
figure
subplot(1,2,1);
imagesc(I2); caxis([0 1]); title('Test Image 2');  axis equal tight
subplot(1,2,2);
imagesc(I2eq); caxis([0 1]); title('Histeq Result');  axis equal tight
colormap(gray);

fprintf(1,'Min/max of input image  2: %3.3f %3.3f\n', min(I2(:)),max(I2(:)) );
fprintf(1,'Min/max of output image 2: %3.3f %3.3f\n', min(I2eq(:)),max(I2eq(:)) );

Upvotes: 1

Views: 75

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60504

Your input image is:

I1 = imread('pout.tif');
I1=im2double(I1);

% damage contrast
I1=0.8*I1;

After im2double, I1 contains values in the range 0-1. Inside your histeq_contrast function, on the line where you get an error message, you index using this image:

eqI = (L-1)*myCDF(double(image)+1);

Thus, you are indexing at non-integer locations, as the error message indicates. (Also, the conversion to double is not necessary, as it already was doubles.) Correct would be:

eqI = (L-1)*myCDF(round(image*255)+1);

Alternatively, don't use im2double.

Upvotes: 1

Related Questions