MATLAB: Getting the values ​​of the pixels inside the sphere of radius (r1) and center (x1, y1, z1).

digital image processingimage analysisimage processingMATLAB

I want to get the values ​​of the pixels inside the sphere of radius (r1), center coordinates (x1, y1, z1) in the 3D image (xyz).
As a matter of fact, I'm not interested in the values ​​of individual pixels and want to get statistics such as mean and SD.
Since there is not one sphere, but hundreds or more, so I'm looking for an efficient way to quantify them.
I have the values ​​of radius (r1, r2, r3 …) and center coordinates ((x1, y1, z1), (x2, y2, z2), (x3, y3, z3) …) .
Please tell me how to do it easily.
If my explanation is inadequate, please ask and I'll get back to you soon.

Best Answer

Supposing you have a 3D grid Pixel_x, Pixel_y, Pixel_z, and you have Center_x, Center_y, Center_z, and Radii
Center_x_row = reshape(Center_x, 1, []);
Center_y_row = reshape(Center_y, 1, []);
Center_z_row = reshape(Center_z, 1, []);
Radiisq_row = reshape(Radii, 1, []).^2;
Pixel_x_col = reshape(Pixel_x, [], 1);
Pixel_y_col = reshape(Pixel_y, [], 1);
Pixel_z_col = reshape(Pixel_z, [], 1);
distssq = (Pixel_x_col - Center_x_row).^2 + (Pixel_y_col - Center_y_row).^2 + (Pixel_z_col - Center_z_row).^2;
%at this point, rows correspond to individual pixels, and columns correspond to sphere centers
%and distssq is distances squared
pixel_within_sphere = distssq <= Radiisq_row;
num_pixel_within_sphere = sum(pixel_within_sphere); %single row, one column per sphere center
and now you can take mean(num_pixel_within_sphere) and so on.