2
votes

I'm using matlab to get counts of specific pixel values in an image.

Images are RGBA <512x512x4 uint8> when read into matlab (although we can disregard the alpha channel).

Other than;

[width, height, depth] = size(im);

for x = 1 : width;
    for y = 1: height;

        r = im(x,y,1);
        g = im(x,y,2);
        b = im(x,y,3);

        ...

    end
end

Is there a way I can do this using matrix operations? Something along the lines of:

X = find(im(:,:,1) == 255 && im(:,:,2) == 255 && im(:,:,3) == 255);
count = length(X);
% Count being the number of pixels with RGB value (255,255,255) in the image.

I'm guessing there's more than a few ways to do this (looking at intersect, unique functions) but I'm not clever enough with matlab to do this yet. Any help?

2

2 Answers

4
votes

It's actually pretty simple. Something like this

count = sum(im(:, :, 1) == 255 & im(:, :, 2) == 255 & im(:, :, 3) == 255);

will give you the count of such pixels. Replace sum with find to get the indices of those pixels if you need that.

1
votes

You can do it with many ways. One way is this. Let's say your image is HxWx3 create a HxW table with the r value you want to search for, one HxW for the g and one for the blue. You can combine all thos tables as dimensions in a HxWx3 table F. Substract F from im and use the find() function to get the indexes of zeroed values.

F(:,:,1)=R*ones(H,W); F(:,:,2)=G*ones(H,W); F(:,:,3)=B*ones(H,W);

then if you do im-F you get zeroes on the wanted positions

d=F-im;    [r,c]=find((d(:,:,1))==0)

That way you can input also a threshold of how close you want the rgb set to be.