Calculate the mean of nonzero pixels
Mostrar comentarios más antiguos
I have a 3D volume and a 3D binary mask. I want to calculate the mean of the pixels which correspond to the regions where the mask is equal to 1.
I thought to calculate the volume with the mask in order to have only the regions I am interested and then I calculated the mean.
I wrote the following piece of code but the mean value is extremely small and I think it's because I am taking into account the whole 3D volume (even the areas where the volume is zero) and not only the regions which I am interested.
r=volume;
for i=1:size(r,1)
for j=1:size(r,2)
for k=1:size(r,3)
masked_volume(i,j,k) = volume(i,j,k)*mask(i,j,k);
end
end
end
mean = mean(masked_volume(:))
1 comentario
Guillaume
el 24 de Oct. de 2019
Note: there was an issue that prevented any sort of editing/commenting on this question and its answers. The issue has been fixed now.
Respuesta aceptada
Más respuestas (1)
Cyrus Tirband
el 24 de Oct. de 2019
Replace the last line by
meanval = mean(nonzeros(masked_volume));
That said, are mask and volume the same size? Those for loops are incredibly inefficient, and the whole snippet can be replaced by the one-liner if the dimensions of volume and mask are identical by using point-wise multiplication:
meanval = mean(nonzeros(volume.*mask));
3 comentarios
Gina Carts
el 24 de Oct. de 2019
Guillaume
el 24 de Oct. de 2019
This solution multiplies the volume with the mask resulting in 0s everywhere that is mask (like your original code did). It then removes all the 0s, that is the 0s that are the result of masking but also all the 0s in the non-masked area. So yes, you'll get different results unless there's no 0s in the non-masked area.
My solution simply discards the masked pixels (with logical indexing) and average what's left so will give you the correct mean in all cases.
Guillaume
el 4 de Nov. de 2019
You're commenting on the wrong answer, making the conversation a bit more difficult.
Answer to that as a comment to my answer.
Categorías
Más información sobre Region and Image Properties en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!