I am Mathematica novice and am trying to find a fast way to replace labels in some rather large matrices (512x512 or 1024x1024) that have resulted from segmenting images with WatershedComponents or MorphologicalComponents. At present I have written the function below that takes a "label matrix" (matrix that results from segmentation) and a list of "keeper" labels (labels that I want to remain in place in the returned matrix) and returns a new matrix with only those labels remaining in place that are in the listOfKeepersIn. All other labels are replaced in the returned matrix with a single "background" label, here designated as 100.
I suspect there are many more efficient ways to achieve this than what I have written here, so I welcome your suggestions. I have tried to convert this to a Compiled Function using Compile but haven't had any success (get an error message about "tensors of different ranks"). I also tried to use ParallelTable instead of Table but didn't notice much improvement. Thanks in advance for any help you can provide. -GR
ComponentKeeperFunction[matrixIn_, listOfKeepersIn_] :=
Block[{matrixToReturn},
matrixToReturn =
Table[
Which[
MemberQ[listOfKeepersIn, matrixIn[[r, c]]] == True,
(* If label value is on the keeper list then just keep that
label in its place, (i.e. make the value in the table the same as
matrixIn[[r,c]])*)
matrixIn[[r, c]],
MemberQ[listOfKeepersIn, matrixIn[[r, c]]] == False,
(* If label value is not on the keeper list then replace that label with a
designated background label *)
100 (*here I designate the background label as having a value of 100 *)
] (* close Which *),
{r, 1, Dimensions[matrixIn][[1]]}, {c, 1, Dimensions[matrixIn][[2]]}
] (*close Table *);
Return[matrixToReturn]
](*close Block*)
matrixToReturn =
andReturn[matrixToReturn
. If you do not put a semicolon at the end ofTable
it will return its result automatically. AlsoModule
is recommended rather thanBlock
, which you can read about here. Overall, usingTable
like this is typical for someone with a background in procedural languages, but Mathematica is faster with functional programming so you should try to use corresponding functional alternatives, such asMap
. $\endgroup$