[R-sig-Geo] Need some help with rasterize...

Jonathan Greenberg jgrn at illinois.edu
Wed Apr 2 02:58:17 CEST 2014


Robert et al.:

I'm seeing a potential issue with rasterize that I'm having a hard
time solving.  Here is the goal: I want to create two masks based on a
polygon: 1) a rasterized version of the ENTIRE polygon, and 2) a
rasterized version of only the edge of the polygon.  I thought it
would be sufficient to simply convert the SpatialPolygons to a
SpatialLines, but the rasterized SpatialLines does not coincide with
the edge of the SpatialPolygons.  Any help would be much appreciated.

I'm going to reference two test files that are in spatial.tools:

install.packages("spatial.tools",
repos="http://R-Forge.R-project.org",type="source")

# Some polys:
y <- readOGR(
dsn=system.file("external",
package="spatial.tools"),layer="tahoe_highrez_training")

# A brick:
x <- brick(system.file("external/tahoe_highrez.tif", package="spatial.tools"))

# We'll pull out a single poly:
y_poly <- y[1,]
# And crop the raster to it to make it a bit easier to see:
miniraster <- crop(x,y_poly)

# Now, we'll rasterize the polygon:
test_poly <- rasterize(y_poly,miniraster)

# And plot it:
plot(test_poly)
plot(y_poly,add=TRUE)

# Convert the poly to a SpatialLines:
y_line <- as(y_poly,"SpatialLines")

# Confirm it is in the same place as the poly:
plot(test_poly)
plot(y_poly,add=TRUE)
plot(y_line,col="red",add=TRUE)
# (Same place)

# Now rasterize the line:
test_line <- rasterize(y_line,miniraster)
plot(test_line,col="blue",add=TRUE)

Notice the line is being rasterized on both sides, but the polygon is
only rasterized inside (this is what I assume it is doing).  Any ideas
for how to tweak this so the test_line is simply the "edge" of the
test_poly (the outer set of pixels)?  Using the rasterized polygon as
a mask for the rasterized line isn't doing the trick (notice that the
"ring" of pixels is not continuous:

test_line_masked <-  test_poly * test_line
plot(test_poly)
plot(test_line_masked,col="blue",add=TRUE)

Ideas?

--j

-- 
Jonathan A. Greenberg, PhD
Assistant Professor
Global Environmental Analysis and Remote Sensing (GEARS) Laboratory
Department of Geography and Geographic Information Science
University of Illinois at Urbana-Champaign
259 Computing Applications Building, MC-150
605 East Springfield Avenue
Champaign, IL  61820-6371
Phone: 217-300-1924
http://www.geog.illinois.edu/~jgrn/
AIM: jgrn307, MSN: jgrn307 at hotmail.com, Gchat: jgrn307, Skype: jgrn3007



More information about the R-sig-Geo mailing list