2
votes

I am new to matlab and programming. I have a RGB image of size [640 780]. Now lets say I need only those pixels whose red value is more than 100 and remaining less pixels I convert to 255. Now I would like to know how can I store those needed pixels in a different matrix so that I can use those values to directly navigate in the original RGB picture for drawing an ROI ???

a = 1; b = 1;
maybe_red = RGB;
for i = 1:sizeim(1)
     for j = 1:sizeim(2)
if RGB(i,j,1) > 100 
        red_trace_x(a) = i;
        red_trace_y(b) = j;
        b = b+1;
    else
        maybe_red(i,j,:) = 1;
    end
end
a = a+1;
end

Currently I am storing x and y in separate arrays. But I would like to know how to store both x,y values in single matrix.

Thank you.!

2

2 Answers

2
votes

The following generates a mask (a logical array of same size as the original image) where pixels with red channel value greater than 100 are stored as 1s and other pixels as 0s:

img= imread('peppers.jpg');
mask=img(:,:,1)>100;

You can use the mask to index into your original image and make changes to it using find to determine the linear indices corresponding to mask pixels with value 1:

indlin=find(mask);
img2 = img;

You can use the linear indices directly, for instance to saturate the red channel:

img2(indlin) = 255;

or the green channel:

n = numel(img)/3;
img2(indlin+n) = 255;

From left to right, the original image, mask, sat'd red, and sat'd green:

enter image description here

edit

You can retrieve array subscripts ix and iy from the linear indices with

[ix iy]=ind2sub(size(mask),indlin);
1
votes

How about if you just store the index of the element?

%% Load a sample image
RGB = imread('football.jpg'); 

b = 1; 
maybe_red = RGB;
red = RGB(:,:,1); % Get the red component

% i will represent the index of the matrix
for i = 1:length(red(:))  % length(red(:)) = rows*cols
    if red(i) > 100 
        red_trace(b) = i;
        b = b+1;
    else
        [r,c] = ind2sub(size(red),i);  % Convert the index to rows and cols
        maybe_red(r,c,:) = 1;
    end
end

imshow(maybe_red);

but it might just be easier to do

red = RGB(:,:,1); % Get the red component of the image
[r,c] = find(red>100);
coord = [r c];