【问题标题】:Find biggest contour and apply mask in imageR package在 imageR 包中找到最大的轮廓并应用蒙版
【发布时间】:2019-09-10 21:06:16
【问题描述】:

我正在尝试使用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 函数,可能会有所帮助。它返回一个列表,其中连接的掩码是每个元素。但是,这些也不是按区域排序的……

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

第二个问题
假设我们有对象,我们如何裁剪原始图像并分割最大的对象(输出应该是原始图像尺寸)?

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

【问题讨论】:

    标签: r image-processing contour


    【解决方案1】:

    好吧,我已经能够通过使用来解决这个问题

      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)]] 
    

    【讨论】:

      猜你喜欢
      • 2019-11-29
      • 2011-11-27
      • 1970-01-01
      • 2020-04-15
      • 2017-04-06
      • 2020-09-14
      • 2019-04-06
      • 1970-01-01
      • 2016-12-10
      相关资源
      最近更新 更多