# I used the following code for hiding a binarystring inside an image using lsb using the following code but an error occurred.

2 views (last 30 days)
Anushka on 2 Aug 2015
Answered: Image Analyst on 2 Aug 2015
I used the following code for hiding a binary string inside an image using lsb using the following code but an error occurred.
k = 1;
for r=1:3
for i = 1 : m
for j = 1 : n
C = dec2binvec(double(c(i,j,r)),8); %convert decimal number to binary vector
if k <= ml %embedd till message length
C(8) = binaryString(k); %embedding in LSB
end %convert binary vector to decimal number
s(i,j,r) = binvec2dec(C);
k = k + 1;
end
end
end
the error is Attempted to access c(1,385,1); index out of bounds because size(c)=[256,384,3].

Walter Roberson on 2 Aug 2015
You do not show us how you determined the value of m and n.
I suspect that you used
[m, n] = size(c);
If I am correct then you need to read the description of size() again:
n < ndims(X) di equals the size of the ith dimension of X for 0<i<n, but dn equals the product of the sizes of the remaining dimensions of X, that is, dimensions n through ndims(X).
Now follow that for the case of having two size() outputs for a 3D array.
##### 1 CommentShowHide None
Anushka on 2 Aug 2015
Yes I used
[m,n]=size(c);
What might be the reason for the error such that I didn't get it correctly?

Image Analyst on 2 Aug 2015
You say size(c)=[256,384,3] but then you say you got the sizes of c by doing this:
[m,n]=size(c);
Never use size that way with images. Since you say that c is a color image with 3 color channels, then n is really the number of columns multiplied by the number of color channels. Why? See Steve's blog: http://blogs.mathworks.com/steve/2011/03/22/too-much-information-about-the-size-function/. To correct, do this:
[m, n, numberOfColorChannels] = size(c);
or even better because it's more explicit and descriptive:
[rows, columns, numberOfColorChannels] = size(c);
Then rename m to rows and n to columns in the rest of your code.
I don't know what dec2binvec() function does, but make sure that it returns a single uint8 number because that's what
s(i,j,r) = binvec2dec(C);
requires. Finally, change
for r=1:3
to
for colorChannel = 1 : numberOfColorChannels
and rename "r" to the much more descriptive, understandable, and maintainable "colorChannel". Why numberOfColorChannels instead of 3? Because in general, the images might be grayscale and not have 3 planes. This will make it more general and robust and it will still work for color images.