在位图图像中绘制一个圆圈并在 R 中的圆圈外裁剪像素

Draw a circle in a bitmap image and crop pixels outside circle in R

我正在将尺寸约为 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)

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

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 的解决方案的细微变化。它不使用重塑包的 "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)