繁体   English   中英

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

[英]Draw a circle in a bitmap image and crop pixels outside circle in R

我正在将位图图像加载到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)

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

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解决方案的细微变化。 它不使用重塑包的“融化”功能,而是直接对矩阵进行子集设置:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM