本文介绍了栅格绘制图像,绘制圆并在圆外遮罩像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码绘制图像,然后在该图像上绘制圆圈.我要使落在该圆圈之外的所有像素变黑.我该怎么办?

Code below plots an image and then plots circle on that image. I want to make all pixels that fall outside that circle black. How could I do that?

library(raster)
library(plotrix)
r1 <- brick(system.file("external/rlogo.grd", package="raster"))
width=50
height=40
x <- crop(r1, extent(0,width,0,height))
plotRGB(x)
circlex=20
circley=15
radius=10
draw.circle(circlex,circley,radius,border="blue")

推荐答案

使用str()查看'x'对象,您会看到以下内容:

Look at the 'x'-object with str() and you see this:

..@ data    :Formal class '.MultipleRasterData' [package "raster"] with 14 slots
  .. .. ..@ values    : num [1:2500, 1:3] 255 248 221 199 198 210 221 190 104 79 ...
  .. .. .. ..- attr(*, "dimnames")=List of 2
  .. .. .. .. ..$ : NULL
  .. .. .. .. ..$ : chr [1:3] "red" "green" "blue"

.... so,因此将1:50 x 1:50值映射到三列. X值可能是0:2500 %% 50,y值可能是0:2500 %/% 50

....so the 1:50 by 1:50 values are mapped to three columns. The X values are probably 0:2500 %% 50 and the y values are probably 0:2500 %/% 50

因此请记住,原点"是栅格对象的左上角,而绘图功能的左下角,因此y值20变为50-20或30,这将使您接近要求的值(为将y序列放在首位而道歉):

So remembering that the "origin" if upper left corner for raster objects but the lower left corner for plot functions, and so the y-value of 20 becomes 50-20 or 30, this gives you close to what you ask for (with apologies for putting the y-sequence first):

x@data@values[( ((1:2500 %/% 50 )- 30)^2 + ((1:2500 %% 50) - 20)^2 ) >=100, 1] <- 0
 x@data@values[( ((1:2500 %/% 50 )- 30)^2 + ((1:2500 %% 50) - 20)^2 ) >=100, 2] <- 0
 x@data@values[( ((1:2500 %/% 50 )- 30)^2 + ((1:2500 %% 50) - 20)^2 ) >=100, 3] <- 0
 plotRGB(x)
 draw.circle(20,20,10,border="blue")

逻辑是准则的形式为(x-dx)^ 2 +(y-dy)^ 2> r ^ 2,其中dx和dy是圆的中心坐标,r是半径== 10.

The logic is that the criteria are of the form (x-dx)^2+(y-dy)^2 > r^2 where dx and dy are the center coordinates of the circle and r is the radius == 10.

问题后的修改已更改:

对于每个颜色层,带有命名参数的代码将类似于使颜色最深的红色"的代码.尽管没有正确处理中心,但这给出了大致圆形的遮罩:

For each color layer, the code with named parameters would be similar to this one that makes the darkest "red". This gives a roughly circular mask although getting the centers to line up is not handled correctly:

x@data@values[( ((1:(height*width) %/% (height*5/4) )- (height-circley*5/4) )^2 +
            ((1:(height*width) %% width) -       circlex )^2 ) >= radius^2, 1] <- 0

进一步的实验提供了这一点,这似乎非常接近:

Further experimentation delivers this which seems pretty close:

x@data@values[( ((1:(height*width) %/% (height) )- (height-circley) *5/4)^2 +
                 ((1:(height*width) %% width) -       circlex )^2 ) >= radius^2, 1] <- 0
plotRGB(x, asp=5/4, addfun=function() draw.circle(circlex,circley,radius,border="blue") )

很明显,您可以在出现5/4的任何地方用width/height比例因子替换新的宽高比.

Obviously you could substitute the width/height scaling factor for the new aspect ratio everywhere that 5/4 appears.

这篇关于栅格绘制图像,绘制圆并在圆外遮罩像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 10:28