0

I would like to read an image pixel by pixel and store how many of each pixel value there are (grayscale 0-255):

img = imread('jetplaneCor.jpg');
imgGray = rgb2gray(img);
sizex = size(imgGray,1);
sizey = size(imgGray,2);
grayArray = [0:0:255]; %Not working

for i=0:1:sizex
   for j=0:1:sizey
       pixelValue = imgGray(i,j);
       grayArray(pixelValue)=grayArray(pixelValue)+1;
   end
end

How can i allocate an array with 256 places?

1
  • You should use initialize grayArray as zeros(1,256). But see my solution, which is much faster than using two loops Commented Sep 29, 2013 at 23:30

2 Answers 2

2

You can do that easily with hist. No need to use loops:

img = imread('jetplaneCor.jpg');
imgGray = rgb2gray(img);
grayArray = hist(imgGray(:),0:255);
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, thanks. The point of the program is to write what imhist() does and compare it to our code.
I've just edited my answer, there was a (:) missing. As for your code, as I said in my first commnent, you only had to initialize grayArray as zeros(1,256).
0

This will create a 1 x 256 array where every entry is a 0:

grayArray = zeroes(1, 256);

You can reference each element with:

grayArray(1, index);

2 Comments

How can i hist grayArray once its filled in. When i use hist(grayArray) i dont get the right data.
Have you tried hist(transpose(grayArray))? Or you can reverse what I told you and use grayArray = zeroes(256, 1) and reference an element with grayArray(index, 1).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.