Getting Index in position 1 exceeds arrray bound error

I wrote a MATLAB code which will put a black box of 10 pixels width at the center of image but I am getting error which says "Index in position 1 exceeds array bounds error"
Here is the code for same
image = imread('image.jpg');
[r,c]=size(image);
width=10;
color=6;
new_image=ones(r,c)*color;
new_image=uint8(new_image);
for row=1:r
for column=1:(c-width)/2
new_image(row,column)=image(row,column);
end;
for column=(c+width)/2:c
new_image(row,column)=image(row,column);
end;
end;
for column=1:c
for row=1:(r-width)/2
new_image(row,column)=image(row,column);
end;
for row=(r+width)/2:c
new_image(row,column)=image(row,column);
end;
end;
imshow(new_image);
And for the logic of the code this code makes a matrix of ones as the size of image pixels and after that I iterate the code from the matrix and adding the pixels value of original image to the new matrix where the box is not present.

 Respuesta aceptada

Stephen23
Stephen23 el 3 de Oct. de 2020
Editada: Stephen23 el 3 de Oct. de 2020
A better approach is to use indexing, eg.:
>> I = imread('peppers.png');
>> N = 10;
>> V = 1:N;
>> I(fix((end-N)/2)+V,fix((end-N)/2)+V,:) = 6;
>> imshow(I)

3 comentarios

Thank you very much for this answer. Can you please briefly explain what this code is doing in that 4th line. I just started with MATLAB and learning things. Well thank you again for this.
"Can you please briefly explain what this code is doing in that 4th line"
I(fix((end-N)/2)+V,fix((end-N)/2)+V,:) = 6;
(end-N)/2 % row = midway up-down, shift down by N/2
fix( )+V % indices of N pixels starting from row
(end-N)/2 % col = midway left-right, shift left by N/2
fix( )+V % indices of N pixels starting from col
: % all pages (RGB has 3 pages, grayscale has 1)
I( , , ) = 6; % allocate 6 to those elements of the image
You should check if that matches your definition of "middle", for both odd and even numbers of pixels.
Thanks for your explanation. Got the point.

Iniciar sesión para comentar.

Más respuestas (1)

Walter Roberson
Walter Roberson el 3 de Oct. de 2020
jpeg images are almost always rgb even when they look grey. Not always but quite rare for real grey jpeg.
When you ask for size() of an rgb image but you only provide two output variables, then the second output is not the number of columns, and is instead the number of columns multiplied by 3.
Please read the details of size() carefully.

1 comentario

Thanks for your comment I didn't knew about that. I will look into this.

Iniciar sesión para comentar.

Preguntada:

el 3 de Oct. de 2020

Comentada:

el 3 de Oct. de 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by