I am currently working on a physics experiment where I count particles. I have looked at and used a bit of code from the following sources: Cell counting from an image file and Count Elements in Image
However,this is my first attempt at the code.
(Note: this code wasn't giving good counts for the particles at particular slide depths. I attached my final solution to the end of this post):
locate = SystemDialogInput["FileOpen"];
img = Import[locate]
b = FillingTransform[ColorNegate[Binarize[img]]]
disT = DistanceTransform[b, Padding -> 0];
marker = MaxDetect[ImageAdjust[disT], 0];
w = WatershedComponents[GradientFilter[b, 3], marker,
Method -> "Rainfall"];
cells = SelectComponents[w, "Count",
0 < # < 500 &];(*Pixel interval*)measures =
ComponentMeasurements[
cells, {"Centroid", "EquivalentDiskRadius", "Label"}];
Grid[{{Style[
"Number of Particles is " <> ToString[Dimensions[measures][[1]]] <>
".", "Title"],
Button["Save it?",
Export[DirectoryName[locate] <> FileBaseName[locate] <> ".txt",
"Number of Cell is " <> ToString[Dimensions[measures][[1]]] <>
". " <> DateString[]]]}, {Show[img,
Graphics[{Red, Circle @@ # & /@ (measures[[All, 2, 1 ;; 2]]),
MapThread[
Text, {measures[[All, 2, 3]], measures[[All, 2, 1]]}]}]]}}]
isn't working very well with my images.
Furthermore, I am having to adjust the value of x in Binarize[img, x] for each image in order to get accurate counts. I don't exactly know how to adjust Binarize to get consistent counts for my data
The final picture in my data set is also proving to be a challenge to process.
I solved the ImageCrop[] problem of this question by pre-processing all of my images, now I just need to find a way to make Binarize[] give good counts of the particles in my image(s).
Final Code
For those who need it.
(The above method gave somewhat inaccurate results so I settled on this one, it basically searches for the images called ker, ker2, and ker3 and finds the points associated with these images in the file that you input to the function. It produced some nice counts)
(ker) = Kernal 1 =
(ker2) = Kernal 2 =
(ker3) = Kernal 3 =
ker = (*Image of Kernal 1*)
locate = SystemDialogInput["FileOpen"];
img = Import[locate];
i = ImageCorrelate[img, ker, NormalizedSquaredEuclideanDistance];
dots = Point[#[[2]]] & /@
ComponentMeasurements[
MorphologicalComponents[ColorNegate[Binarize[i, 0.22]]],
"Centroid"];
Length[dots]
Show[img, Graphics[{Red, dots}]]
ker2 = (*Image of Kernal 2*)
i = ImageCorrelate[img, ker2, NormalizedSquaredEuclideanDistance];
dots2 = Point[#[[2]]] & /@
ComponentMeasurements[
MorphologicalComponents[ColorNegate[Binarize[i, 0.22]]],
"Centroid"];
Length[dots2]
Show[img, Graphics[{Red, dots2}]]
ker3 = (*Image of Kernal 3*)
i = ImageCorrelate[img, ker3, NormalizedSquaredEuclideanDistance];
dots3 = Point[#[[2]]] & /@
ComponentMeasurements[
MorphologicalComponents[ColorNegate[Binarize[i, 0.22]]],
"Centroid"];
Length[dots3]
Show[img, Graphics[{Red, dots2}]]
Length[dots] + Length[dots2] + Length[dots3]