mask <- array(0L, c(21, 21, 21))
mask[6:16, 6:16, 6:16] <- 1L
mask[11, 11, 11] <- 0L
# a thin bridge to another object
mask[17:20, 11, 11] <- 1L
# the erosion cuts the bridge, the largest component drops what is left
cleaned <- morph_volume(mask, "erode", radius = 1)
cleaned <- morph_volume(cleaned, "largest_component")
cleaned <- morph_volume(cleaned, "dilate", radius = 1)
cleaned <- morph_volume(cleaned, "fill_holes")
oldpar <- par(mfrow = c(1, 2), mar = c(0.1, 0.1, 3.1, 0.1))
image(mask[, , 11], asp = 1, main = "Original mask", axes = FALSE)
image(cleaned[, , 11], asp = 1, main = "Cleaned mask", axes = FALSE)
par(oldpar)
Run the code above in your browser using DataLab