user3298890
user3298890

Reputation: 11

finding & saving RGB value of some selected pixels of an image

I selected some pixels from an RGB image using ginput. Now I need a code to extract RGB value of all of selected pixels in a same time and save them in coordinate matrix of pixels. Any suggestion?

A=imread('AMAR.jpg');
imshow(A)
samp1= ginput(A)

samp1 is <47x5 double>

some results are:

95 92 95 81 99 66 97 66 100 58 105 51 108 42 116 33

Upvotes: 1

Views: 1768

Answers (2)

chappjc
chappjc

Reputation: 30589

Say you click on N points in an RGB image:

N=4;
imagesc(img)
[x,y]=ginput(N);

The x,y values can be used to lookup the RGB vector for each location:

x = round(x(:)); y = round(y(:));
locs = sub2ind(size(img),repmat(y,3,1),repmat(x,3,1),kron(1:3,ones(1,N)).'); %'
RGBvals = reshape(img(locs),N,3)

That gives you an N-by-3 array of RGB values for each point. Use the interactive tool impixelregion to visually verify the color values.

Note: See here for a bit about kron that should hopefully deflate any mystery about its use here.

Upvotes: 1

Floris
Floris

Reputation: 46415

@chappjc's answer would work; I would like to offer a small change that is a bit more "readable":

First - call ginput without any arguments. It will keep accumulating points clicked until you hit "enter". A little more user friendly.

Second - there's a time and a place for vectorization. When you have just a handful of points (namely, one point per click) it is unlikely that the speedup of vectorized code is worth the pain of sub2ind, repmat, kron...). That leaves us with the following:

imshow(A);
disp( 'Click points in the image; press return when finished' );
[xf, yf] = ginput;

xi = round(xf);
yi = round(yf);

N = numel(xi);
rgbValues = zeros(N, 3);

for ii = 1:numel(xi)
  rgbValues(ii,:) = reshape(A(yi(ii), xi(ii), :), 1, 3);
end

This will put the values you want into rgbValues.

Do check that the values of xi and yi are returned in the order shown; I think this is right, but if I'm wrong you would have to use the order A(xi(ii), yi(ii), :) when you read the image).

Upvotes: 1

Related Questions