【问题标题】:Draw a circle in a bitmap image and crop pixels outside circle in R在位图图像中绘制一个圆圈并在 R 中裁剪圆圈外的像素
【发布时间】:2015-04-19 16:24:48
【问题描述】:

我正在将尺寸约为 17,000 X 17,000 像素的位图图像加载到 R 中。我想找到一种方法在图片中心周围绘制一个我选择的半径(以像素为单位)的圆,并将圆外的所有像素转换为 NA。 例如,如果所需的半径为 500 像素,则距质心该距离 (500) 内的所有像素都将保持原样。任何比质心距离 (>= 501) 远的像素都将转换为 NA。

位图图像完全由 1 和 0 组成,因此这里有一个较小的示例来说明这些图像的外观。

img=matrix(sample(c(1,0),1000000,replace=TRUE),ncol=1000,nrow=1000)
image(0:1000,0:1000,img)

【问题讨论】:

    标签: r image crop


    【解决方案1】:

    这是 eipi10 解决方案的轻微变化。它不使用 reshape 包的“melt”功能,而是直接使用子集矩阵:

    # Number of rows and columns in image
    nr = 200
    nc = 100
    
    # Create image values
    set.seed(78)
    img <- matrix(sample(c(1,0), nr*nc, prob=c(0.8, 1-0.8), replace=TRUE), ncol=nc, nrow=nr)
    
    center <- c(median(1:nr), median(1:nc)) # center of image
    r <- 40 # radius
    
    # setting the matrix element inside the circle to value -1
    img[(row(img) - center[1])^2 + (col(img) - center[2])^2 < r^2] <- -1
    
    # plot image
    par(mar = c(0, 0, 0, 0))
    image(img, useRaster=TRUE, axes=FALSE)
    

    【讨论】:

      【解决方案2】:

      我创建了一个比你的更小的假图像,以便代码运行得更快:

      library(plotrix) # To draw a circle
      library(reshape2) # For "melt" function
      

      创建一个假图像:

      # Number of rows and columns in image
      nr = 200
      nc = 100
      
      # Create image values
      set.seed(78)
      img = matrix(sample(c(1,0), nr*nc, prob=c(0.8, 1-0.8), replace=TRUE), ncol=nc, nrow=nr)
      

      现在我们有了图像,删除所需圆圈之外的点:

      # melt matrix into "long" format
      img = melt(id.var=1:nrow(img), img)
      names(img) = c("rows","cols","z")
      
      # Find center of image
      center=c(median(1:nr), median(1:nc))
      
      # Set desired radial distance from center
      r=40
      
      # Set values outside radius to -1 (or some value that can't otherwise appear in
      # the matrix). You can set the value to NA, but then you won't be able to
      # control the color of the excluded region (it will just be white).
      img$z[sqrt((img$rows - center[1])^2 + (img$cols - center[2])^2) > r] = -1
      
      # Plot image. Colors ordered from lowest (-1) to highest (1) value
      image(1:nr, 1:nc, matrix(img$z, nrow=nr, byrow=FALSE), col=c("gray80", "green","red"))
      
      # Draw a circle around the selected points
      draw.circle(center[1], center[2], r, lwd=2)
      

      【讨论】:

      • 抱歉回复晚了。这很好用!谢谢eipi10。
      猜你喜欢
      • 2015-10-20
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 2011-06-06
      • 1970-01-01
      • 2016-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多