Adding elements of a matrix based on an if condition
Show older comments
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;
Answers (1)
Guillaume
on 19 Oct 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 Comments
Aishwarya Jayachandran
on 19 Oct 2019
Guillaume
on 19 Oct 2019
red(red >= 150) is a vector containing all the elements of red which are greater than or equal to 150. If you take the mean of that, you get the mean of all the elements >= 150. It's what you tried to do.
sum(red(:)) %double(xxx) not needed
will return the sum of all of red
sum(red(red >= 150))
would return the sum of red whose value are >= 150. You could then divide by nnz(red >= 150) to get the mean, but it's simpler to call mean directly.
Note:
>> x = uint8([200 100])
x =
1×2 uint8 row vector
200 100
>> x(1) + x(2) %sum is greater than 255, but since it's uint8 returns 255
ans =
uint8
255
>> sum(x) %sum automatically convert to double, so works properly
ans =
300
So avoid summing uint8 in a loop. Convert to double beforehand. sum and mean do it automatically.
Aishwarya Jayachandran
on 19 Oct 2019
Aishwarya Jayachandran
on 19 Oct 2019
Guillaume
on 20 Oct 2019
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.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!