Reputation: 2840
The idea is to create a box(draw the lines) around an image which is represented as a binary matrix. For that I need to extract the first and last non-zero row and column on each of the four sides. For exemplification, here is a snippet that creates the figure bellow:
R = 50; b = 10
x = 1:(3*R); y = x; x.cent = R; y.cent = R; r = R-b
A = outer(x, y, function(x,y) sqrt(((x-x.cent)^2)+((y-y.cent)^2)))
circle <- ifelse(A<r, 1, 0)
The circle is for exemplification purpose. In reality it can be any shape. True, it can be done by slicing each side and look for each row/column for non-zero values but I'm looking for an elegant way to do it to be computationally fast.
Upvotes: 1
Views: 48
Reputation: 35594
Use rowSums()
and colSums()
to identify the indices of non-zero row/column sums and then use range()
to exract the first and last values.
range(which(rowSums(circle) != 0))
# [1] 11 89
range(which(colSums(circle) != 0))
# [1] 11 89
Upvotes: 3