我正在将位图图像加载到R中,其尺寸大约为17,000 X 17,000像素。我想找到一种方法来绘制一个圆圈,其中我选择的半径(以像素为单位)围绕图片的中心,并将圆圈外的所有像素转换为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)
答案 0 :(得分:0)
我创建了一个比你小的假图像,以便代码运行得更快:
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)
答案 1 :(得分:0)
这是eipi10解决方案的细微变化。它不使用重塑包的“融化”功能,而是直接对矩阵进行子集设置:
# 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)