Adding elements of a matrix based on an if condition

15 visualizaciones (últimos 30 días)
Aishwarya Jayachandran
Aishwarya Jayachandran el 19 de Oct. de 2019
Comentada: Guillaume el 20 de Oct. de 2019
In this code, the value of rblush at the end of the loop shows 255 but it should be a really large number.
could somebody tell me how to rectify this mistake?
red(x,y) is a matrix of all the red pixels of an image. I want to get the sum of all the elements of the matrix greater 150. Thanks!
for x=1:rows
for y=1:columns
rd_pixel= red(x,y);
if(rd_pixel>=150)
n = n+1;
rtot = sum(rd_pixel);
end
end
end
rmean= rtot/n;

Respuestas (1)

Guillaume
Guillaume el 19 de Oct. de 2019
There is no rblush in your code.
Note that sum(scalar_value) is simply scalar_value. The code you've written does not work at all, since each time you encounter a pixel above the treshold you simply copy its value in rtot instead of adding it to rtot.
I strongly suspect you're working with uint8 values. Note that the range of uint8 is 0-255. If you add two uint8 numbers and their theoretical sum is greater than 255, matlab will give you 255. Converting to double would avoid this problem, but even better getting rid of the loop and using simple logical indexing with mean would work just as well.
rmean = mean(red(red >= 150)); %mean will convert the pixels to double.
  5 comentarios
Aishwarya Jayachandran
Aishwarya Jayachandran el 19 de Oct. de 2019
Ive modified the code as such
for x=1:rows
for y=1:columns
if(red(x,y)>rmean)
rblush= sum(red(red >= 200));
blush= blush+1;
end
end
end
Is this correct? Is there anyway to make this take less time?
Guillaume
Guillaume el 20 de Oct. de 2019
No, you need to learn logical indexing. You shouldn't have any loop.
mask = red >= 200 & red > rmean; %which pixels to take into account
rblush = sum(red(mask)); %use mask to compute the mask
blush = nnz(mask); %number of true pixels in the mask
is all that is needed.
Note that
for x = ...
result = something
end
will always overwrite result on each step of the loop. When the loop finishes, you're left with just the result from the last iteration, so clearly your loop was never going to work.

Iniciar sesión para comentar.

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by