Here is how to Generate data
the function is below with two images to generate data
img1
segmentImage[binarizedMask_?ImageQ] :=
Module[{seg, areas, indexMaxarea, maxArea},
seg = MorphologicalComponents@*ColorNegate@Dilation[binarizedMask, 1];
areas = ComponentMeasurements[seg, "Area"];
{indexMaxarea, maxArea} = First@MaximalBy[areas, Last] /. Rule -> List;
If[maxArea > 20000, ArrayComponents[seg, Length@areas, indexMaxarea -> 0], seg] ~
Dilation~1(* 20000 is just a threshold *)
];
generating data
{seg1, seg2} = segmentImage /@ {img1, img2};
Now the question
I have two 2-D arrays with dimensions {651,823}
. Each array has labelled components i.e. at each position the value is either zero or an integer label. I have 51 objects in the first seg1
and 50 objects in the second array seg2
.
I wish to calculate the number of positions where a given object from the first array intersects the objects in the second array.
I have concocted this strategy but it seems terribly slow:
(pos = Table[
Length@Intersection[Position[seg1, i], Position[seg2, j]], {i,
51}, {j, 50}];) // AbsoluteTiming
(* {143.607, Null} *)
Since these arrays need to be modified and consequently the intersections need to recalculated in an iteration later, I find that this is not the best way to do it.
Any ideas of speeding the process up will be welcomed.
the output i have looks something like this (each row represents an integer label in seg1
and each column represents a label in seg2
and the values represent the number of positions the labelled objects in both arrays intersect):
Note: In the image attached the values 267 and 564 in the first line delineates that the object (label 1) in seg1
intersects an object labeled 5 and 7 in seg2
at 267 and 564 positions respectively
seg1
intersects an object labeled 5 inseg2
at 267 positions $\endgroup$seg1
is1,2,3....51
andseg2
is labeled with1,2,3....50
so the entries being non-zero means that the 4th and 6th labels inseg1
intersect with the label 1 inseg2
$\endgroup$SparseArray[SparseArray@Normal[Rest@Counts[Flatten[(1 - Unitize[seg1 - #]) seg2]]]&/@Range[51]]// Normal
? $\endgroup$