I have a stack of DICOM images which have been used to create a 3D image. This image has been put through specific filters in order to isolate only the areas of interest and binarize the 3D image. I would like to now calculate the number of specific colored pixels in the filtered image but am unable to find the right functions. Please help. Here is a screen shot of the 3D image. image.

  • 1
    $\begingroup$ DominantColors[img, 4, {"Color", "Count"}]? $\endgroup$
    – kglr
    Oct 4, 2018 at 14:31

1 Answer 1


If you've already processed to the point where BinaryImageQ returns True and are confident you've selected the right pixels, you've done most of the work.

In v11.3, Arithmetic functions were added to image functionality, so you can use Total to count the number of pixels of interest.

rand3DIm = RandomImage[1, {20, 20, 20}];
myBinIm = Binarize[rand3DIm];
pixelsChosenCount = Total[myBinIm]


This method relies on you having already binarized the image. Any pixel of interest has value 1, and any pixel that you have decided in your processing not to count should have 0.

Alternatively, if you don't have a recent enough version to use Total on Images directly:

Count[Flatten[ImageData[myBinIm]], 1]


Nest[Total, ImageData[myBinIm], 3]

should both work.

  • 1
    $\begingroup$ Starting from Mathematica 9 there is ImageMeasurements, so one could use pixelsChosenCount = ImageMeasurements[myBinIm, "Total"] as well. My quick measurements showed that this is as fast as Total[myBInIm], while the other two methods were much slower (Count appro. 50 times, Nest approx. 8 times). $\endgroup$
    – UDB
    Oct 5, 2018 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.