Diff of /R/partition_lung.R [000000] .. [3b2327]

Switch to unified view

a b/R/partition_lung.R
1
#' Partition the lung
2
#'
3
#' @param img Lung scan to be partitioned. Can be in 3D matrix or ANTs image file format.
4
#' @param kernel_size Size of the kernel, in voxel units of width, depth, and height. Must be c(3,3,3) or greater. Default: c(30,30,30)
5
#' @param kernel_stride Stride (or spacing) between kernels, in voxel units, for width, depth, and height. If kernel_stride = kernel_size, the partitions are non-overlapping. If stride = c(1,1,1), then each voxel is returned.
6
#' @param centroid Logical. If true, output includes the centroids of each partition.
7
#'
8
#' @return Matrix of x, y, and z coordinates for each partition
9
#' @export
10
partition_lung = function(img,
11
                          kernel_size = c(30,30,30),
12
                          kernel_stride = c(30,30,30),
13
                          centroid = TRUE){
14
15
  # Put in array format
16
  img <- as.array(img)
17
18
  # Dimensions of image
19
  dim_x <- dim(img)[1]
20
  dim_y <- dim(img)[2]
21
  dim_z <- dim(img)[3]
22
23
  # Kernel sequences -- start points
24
  x1 = seq(1, dim_x, by = kernel_stride[1])
25
  y1 = seq(1, dim_y, by = kernel_stride[2])
26
  z1 = seq(1, dim_z, by = kernel_stride[3])
27
28
  # Kernel endpoints
29
  xend <- x1 + kernel_size[1] - 1
30
  yend <- y1 + kernel_size[2] - 1
31
  zend <- z1 + kernel_size[3] - 1
32
33
  # Kernel endpoints can't be larger than dimension of image
34
  xend[xend > dim_x] = dim_x
35
  yend[yend > dim_y] = dim_y
36
  zend[zend > dim_z] = dim_z
37
38
  # Put into dataframe
39
  coords1 <- expand.grid(x1, y1, z1)
40
  coords_end <- expand.grid(xend, yend, zend)
41
  coords1 <- cbind(coords1, coords_end)
42
  colnames(coords1) <- c('x1','y1','z1','xend','yend','zend')
43
  coords1$partition <- 1:dim(coords1)[1]
44
45
  # Find the centroid for each partition
46
  if(centroid == TRUE){
47
    coords1$x <- apply(cbind(coords1$x1, coords1$xend), 1, median)
48
    coords1$y <- apply(cbind(coords1$y1, coords1$yend), 1, median)
49
    coords1$z <- apply(cbind(coords1$z1, coords1$zend), 1, median)
50
  }
51
52
  # Return coordinates
53
  return(coords1)
54
55
}