MATLAB Answers

Trying to save the red positions of an image

1 view (last 30 days)
I'm trying to save all the position's of an image with red color.
im = imread('image.png');
locations = find(im(:,:,1) == 36)
This code is giving me an empty array. Why this is happening? How can I fix it?


Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 7 Aug 2020
Oliver, this works:
rgbImage = imread('image.png');
subplot(1, 2, 1);
impixelinfo; % Let's you mouse around and see rgb values.
% Split image into components:
[r, g, b] = imsplit(rgbImage);
% Red spots are r=237, g=28, b=36.
% Get red mask
redMask = r > 200 & g < 50 & b < 50;
subplot(1, 2, 2);
% Get rows and columns where the red pixels are
[redRows, redColumns] = find(redMask)
redRows and redColumns are paired row,column coordinates for each pixel that is red in the image, in column-major order. Not sure what you're going to do with that, but there you have it.


Oliver Lestrange
Oliver Lestrange on 7 Aug 2020
Hi there,
With your code I'm geting and error:
Undefined function or variable 'imsplit'
Maybe my MATLAB version doesn't have this function...
Image Analyst
Image Analyst on 7 Aug 2020
You have an old version. Try this
r = rgbImage(:, :, 1);
g = rgbImage(:, :, 2);
b = rgbImage(:, :, 3);

Sign in to comment.

More Answers (1)

Sudheer Bhimireddy
Sudheer Bhimireddy on 7 Aug 2020
Does your image has that Red value? Double-check it.
To test your code, follow this example.
A = imread('ngc6543a.jpg'); % Read MATLAB example figure
A_read = A(:,:,1); % Read Red channel
A_ind = find(A_read == 36); % Find non-zeros where the value is equal to 36
A_sz = size(A_read);
[A_row,A_col] = ind2sub(A_sz,A_ind); % Convert linear indices to matrix subscripts
If you change the above find statement to
A_ind = find(A_read == 3600);
you will get an empty A_ind array because there exists no such value inside A_read.


Show 7 older comments
Image Analyst
Image Analyst on 7 Aug 2020
Like I said in my answer, your values are r=237, g=28, b=36.
Sudheer Bhimireddy
Sudheer Bhimireddy on 7 Aug 2020
To understand that, you need to understand the way image color data is stored in MATLAB.
For an RGB image, if you are storing the pixel values in a [m,n,3] array; where m and n gives the size of the image. If you are storing them in unit8 format, they can varry from [0 255] and if you store them in double format they varry from [0 1].
Now, lets say pixel at index (10,10) in your image is filled with red alone, then the corresponding cell values will be (in unit8 format)
(10,10,1) = 255;
(10,10,2) = 0;
(10,10,3) = 0;
Similarly if it is filled with blue alone, they will have values
(10,10,1) = 0;
(10,10,2) = 0;
(10,10,3) = 255;
So, the first channel of the image contains the amount of Red color on a scale of [0 255] at each pixel.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by