user3891236
user3891236

Reputation: 607

Wrong dimensions when normalizing an image

I am getting some error in this code section

 X=imread ('Lighthouse.jpg'); %reads picture as int8 matrix  
figure, imagesc(X), colormap gray, title('original picture'), % display picture  
filter=[-1 0 1; -2 0 2; -1 0 1]; % builds Sobel filter matrix  
filter=single(filter); %convert double to single 
x=single(X); % convert int8 to single  
x=x/max(max(x)); %normalisation to [0,1] 

The error I get:

Error using  / 
Inputs must be 2-D, or at least one input must be scalar.
To compute elementwise RDIVIDE, use RDIVIDE (./) instead.
Error in sobel (line 10)
x=x/max(max(x)); %normalisation to [0,1]

Also when I am using ./ as suggested, I get new error:

Array dimensions must match for binary array op.
Error in sobel (line 10)
x=x./max(max(x)); %normalisation to [0,1]

I am doing something wrong in the normalization step.

How do I resolve this issue?

Upvotes: 1

Views: 247

Answers (3)

Yuval Harpaz
Yuval Harpaz

Reputation: 1426

When I run your code the error message says "Use RDIVIDE (./)". implement it like this:

x=x./max(max(x)); 

This divides each RGB layer by its maximum. You may have to replicate the max values (I guess this depends on matlab version), use this line instead

x=x./repmat(max(max(x)),size(X,1),size(X,2),1); 

Upvotes: -2

Adriaan
Adriaan

Reputation: 18187

Whilst Caduceus' answer is correct; it normalises over all three colours in one go. What's probably better for your case is rgb2gray, to get a single colour channel and then normalise that instead (using x/max(x(:))).

X=imread ('lighthouse.png'); %reads picture as int8 matrix  
filter=[-1 0 1; -2 0 2; -1 0 1]; % builds Sobel filter matrix  
filter=single(filter); %convert double to single 
x = single(rgb2gray(X)); % rgb2gray gives a uint8, you want single
% x=x/max(x(:)); %normalisation to [0,1] , not needed here as x can directly be used
% for Sobel purposes as it's a grey scale image.

figure;
subplot(1,2,1)
imagesc(X)
colormap(gray)
title('original picture'), % display picture 
subplot(1,2,2)
imagesc(x)
colormap(gray)
title 'Grey scale'

enter image description here


The reason for the first error is is that max gives a column-wise maximum, and that this is a 3D matrix. max(max()) thus gives a 1D one, instead of the desired scalar.

Then the second error occurs because max(max()) gives an array, which doesn't have the same amount of entries as the full matrix (obviously).

Basically if size(x) = [row, column channels], size(max(x)) = [row channels] and size(max(max(x)) = [row]. Using the colon operator actually makes the entire 3D matrix a single column vector, and max(x(:)) thus gives a single value, which is the maximum across all rows, columns and channels.

Upvotes: 2

Molitoris
Molitoris

Reputation: 1035

Why do you call max twice. If I run the code with

x=x/max(x(:))

I do not get an error. This runs the matrix in 1D.

Upvotes: 2

Related Questions