user2029767
user2029767

Reputation:

converting image to grayscale using arrays

Here is my code. Im not sure why this isnt working. It says index exceed matrix dimensions. and then it says Error in grayscale1 (line 7) avg=mean(pic(col, row, :)); I want to use the function by inputing image(grayscale1(imagename))

Also here is my prompt Write a function named “grayscale1.m” that receives a filename for an image file and returns a 3-D array with a grayscale version of the image. It should work for images of any size. Your solution should use nested loops to set the value of every pixel.

function grayscale1(picture)
pic = imread(picture);
[r c] = size(pic); 
    for row = 1:r 
         for col = 1:c 
             avg=mean(pic(row, col, :));
               pic(row,col,:)=avg;
          end
    end   
 end

Upvotes: 0

Views: 994

Answers (1)

miy
miy

Reputation: 306

If pic is a 3-dimensional array, then this:

[r c] = size(pic);

will give you size of 1st dimension in r and multiplication of sizes of 2nd and 3rd dimensions in c. It's probably not what you want. So you should do:

[r c ignore] = size(pic);  

or

r = size(pic, 1);
c = size(pic, 2);

Upvotes: 1

Related Questions