在 imageR 包中找到最大的轮廓并应用蒙版

Find biggest contour and apply mask in imageR package

我正在尝试使用 imageR 包找到最大的轮廓。我认为问题分为两个阶段:

1)找到最大的轮廓
2) 用它来遮盖原图

这是一个可重现的例子:

fpath <- system.file('extdata/parrots.png',package='imager')
im <- load.image(fpath)

执行一些随机变换以获得掩码

binary <- im  %>% 
  grayscale() %>%
  threshold() %>%
  clean(2) %>%
  imager::fill(15)

第一个问题:
我可以在二进制图像上使用 contours 函数。原来结果没有排序。所以在这种情况下,最大的轮廓是数字 5.

# find largest contour ?
largest <- as.data.frame(contours(binary)[[5]])
plot(binary)
lines(largest$x, largest$y, col="cyan", lwd=3)

该软件包提供了一个可能有帮助的 split_connected 功能。它 returns 一个列表,其中连接的掩码是每个元素。但是,这些也没有按区域排序...

li <- split_connected(binary)
# This is the one we want now
li[[2]] %>% plot

第二题:
假设我们有对象,我们如何裁剪原始图像并对最大对象进行分割(输出应为原始图像尺寸)?

我希望像 li[[2]] * im 这样的东西是可能的

好吧,我已经能够使用

解决这个问题
  out <- im %>% threshold() %>%
    clean(2) %>%
    imager::fill(15)

  cont_list <- imager::contours(out)

  # polyarea calculates the area of a polygon defined by the vertices with coordinates x and y. 
  # Areas to the left of the vertices are positive, those to the right are counted negative.
  # We can wrap this function
  get_max_area <- function(cont_list){
    purrr::map(cont_list, function(li, x, y) abs(pracma::polyarea(li$x, li$y)))
  }

  areas <- get_max_area(cont_list)
  # get max contour
  biggest <- cont_list[[which.max(areas)]]