Running the exact same lines of code in a function produces just a return of the original image without any points identified, whereas when I run the exact body of the function line by line it works consistently. Is something wrong with my function?
points[img_] := (src = ColorConvert[img, "Grayscale"];
white = Closing[src, DiskMatrix[5]];
srcAdjusted = Image[ImageData[src]/ImageData[white]];
components =
ComponentMeasurements[
ColorNegate@Binarize[srcAdjusted], {"ConvexArea", "Mask"}][[All,
2]];
largestComponent = Image[SortBy[components, First][[-1, 2]]];
mask = FillingTransform[Closing[largestComponent, 2]];
lY = ImageMultiply[
MorphologicalBinarize[
GaussianFilter[srcAdjusted, 3, {2, 0}], {0.02, 0.05}], mask];
lX = ImageMultiply[
MorphologicalBinarize[
GaussianFilter[srcAdjusted, 3, {0, 2}], {0.02, 0.05}], mask];
verticalGridLineMasks =
SortBy[ComponentMeasurements[
lX, {"CaliperLength", "Centroid", "Mask"}, # > 100 &][[All,
2]], #[[2, 1]] &][[All, 3]];
horizontalGridLineMasks =
SortBy[ComponentMeasurements[
lY, {"CaliperLength", "Centroid", "Mask"}, # > 100 &][[All,
2]], #[[2, 2]] &][[All, 3]];
centerOfGravity[l_] :=
ComponentMeasurements[Image[l], "Centroid"][[1, 2]]
gridCenters =
Table[centerOfGravity[
ImageData[Dilation[Image[h], DiskMatrix[2]]]*
ImageData[Dilation[Image[v], DiskMatrix[2]]]], {h,
horizontalGridLineMasks}, {v, verticalGridLineMasks}];
Show[src,
Graphics[{Red,
MapIndexed[{Point[#1], Text[#2, #1, {1, 1}]} &,
gridCenters, {2}]}]])
Desired output: